Skip to content

Instantly share code, notes, and snippets.

@usmansaleem
Created November 23, 2017 07:29
Show Gist options
  • Save usmansaleem/3ccad1e8c1066827aa5e4c332e7daece to your computer and use it in GitHub Desktop.
Save usmansaleem/3ccad1e8c1066827aa5e4c332e7daece to your computer and use it in GitHub Desktop.
JGit Usage in Kotlin
package info.usmans.blog.vertx
import org.eclipse.jgit.api.Git
import org.eclipse.jgit.revwalk.RevCommit
import org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider
import java.io.File
internal const val GIST_REPO_URL = "https://gist.github.com/someid.git"
fun gitCredentialProvider(gistToken: String = System.getenv("GITHUB_GIST_TOKEN")) = UsernamePasswordCredentialsProvider(gistToken, "")
fun checkoutGist(gistUrl: String = GIST_REPO_URL): File {
val tmpDir = createTempDir()
Git.cloneRepository().
setURI(gistUrl).
setDirectory(tmpDir).
call().use {
println("Git cloned at: $tmpDir")
}
return tmpDir
}
fun commitGist(checkoutDir: File, msg:String="commit from jgit"): RevCommit {
//open existing repo and commit and push data.json
return Git.open(File(checkoutDir, ".git")).use {
it.add().addFilepattern("data.json").call()
it.commit().setMessage(msg).call()
}
}
fun pushGist(checkoutDir: File, credentialProvider: UsernamePasswordCredentialsProvider = gitCredentialProvider()) {
//open existing repo and commit and push data.json
Git.open(File(checkoutDir, ".git")).use {
it.push().setCredentialsProvider(credentialProvider).call()
}
}
@TSampley
Copy link

Which Kotlin version is this? I think this is weird:

.use {
                println("Git cloned at: $tmpDir")
}

Did you mean let?

In Kotlin, use can be called on a Closeable? resource to execute a block on the resource and then close it neatly. It's the Kotlin way to do a try-with-resources statement.

@rammohan816
Copy link

Hi, Can you please tell me how to use this code using git ssh keys instead of token. And the dependencies for gradle.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment