简体   繁体   中英

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?

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)); 

One possible solution to this I have found so far is to check whether the local branch exists and is an ID in order to combine the two approaches mentioned in the question:

    boolean createBranch = !ObjectId.isId(branchOrCommitId);
    if (createBranch) {
        Ref ref = repo.getRepository().exactRef("refs/heads/" + branchOrCommitId);
        if (ref != null) {
            createBranch = false;
        }
    }
    repo.checkout()
            .setCreateBranch(createBranch)
            .setName(branchOrCommitId)
            .call();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM