Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to checkout a remote branch without knowing if it exists locally in JGit?

Using ordinary git checkout the command works exactly how I would expect it to. Here are the use cases I am trying to allow for with the same piece of code:

1) git checkout branchname where branchname does not exist locally but does on remote

2) git checkout branchname where branchname already exists locally

3) git checkout commitid

For context, the repository has previously been cloned as follows:

repo = Git.cloneRepository()
    .setCloneSubmodules(true)
    .setURI(repoUrl)
    .setDirectory(createTempDir())
    .setCloneAllBranches(true)
    .call();

The standard JGit checkout command does not automatically create branches locally. The following piece of code works for scenarios 2 and 3:

repo.checkout()
      .setName(branchOrCommitId)
      .call();

With the amendment to create a new branch it only works with scenario 1:

repo.checkout()
      .setCreateBranch(true)
      .setName(branchOrCommitId)
      .call();

Is there a neat solution to this issue I can use, considering the standard Git CLI already provides the automatic functionality within the command I am looking for?

like image 533
MarkRobbo Avatar asked Aug 09 '17 10:08

MarkRobbo


People also ask

How do I checkout a remote branch in Visual Studio?

Find the remote branch in remotes -> origin , then double-click that branch to get it selected locally.

What happens when you checkout a remote branch in git?

There is no actual command called “git checkout remote branch.” It's just a way of referring to the action of checking out a remote branch. Git is a way for software developers to track different modifications of their code. It keeps all the various versions in a unique database.

How do I checkout to an existing branch?

First, make sure that the target branch exists by running the “git branch” command. Now that you made sure that your branch exists, you can switch from the master branch to the “feature” branch by executing the “git checkout” command. That's it!


1 Answers

What you want to do is create a branch if and only if a local one is NOT present. Here's what I came up with using streams where exampleRepo is the git repo object, checkout command is the CheckoutCommand, and branchName is the branch name.:

    git.setCreateBranch(git.branchList()
                            .call()
                            .stream()
                            .map(Ref::getName)
                            .noneMatch("refs/heads/" + branchName);
like image 169
randypaq13 Avatar answered Nov 04 '22 14:11

randypaq13