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

MarkRobbo :

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?

randypaq13 :

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.:

.setCreateBranch(!exampleRepo.branchList()
                        .call()
                        .stream()
                        .map(Ref::getName)
                        .collect(Collectors.toList())
                        .contains("refs/heads/" + branchName));

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=466092&siteId=1