Skip to content
Advertisement

Jgit – checkout from a specific branch

I am using jgit. I want to create and checkout a new branch. I have seen the git.checkout.createnewbranch command. Is there a way to specify the base branch for the checkout, say “test” (or) we have to checkout,pull “test” first and then checkout/create the new branch from it?

Advertisement

Answer

Yes, it’s possible:

Git git = Git.cloneRepository()
    .setURI("https://github.com/eclipse/jgit.git") // just an example uri
    .setDirectory("/path/to/repo")
    .setCloneAllBranches(true)
    .call();

git.checkout()
    .setCreateBranch(true)
    .setName("new-branch")
    .setStartPoint("<base branch>") // if it's a remote base then use origin/ prefix
    .call();

Don’t forget to call git.close() or use try-with-resources once you are done with git.

Advertisement