Using jgit to checkout and modify gist from Kotlin
As I have discussed previously that gist can be an alternative way to store data online at GitHub and use in your application. However, in order to make changes to data, the gist is required to be cloned, make changes and push back. JGit is a lightweight Java library that can be used to checkout gist and commit and push changes to it. Following code snippet shows how to achieve it 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()
}
}
About Me
I am Daiki, Blockchain Engineer, specializing in the EVM, Solana Web3 ecosystem and web3 fronternd. if i resonate with you. follow me on
See you on the next Part