[英]How to checkout a remote branch without knowing if it exists locally in JGit?
使用普通的git checkout
命令可以完全按照我的预期运行。 以下是我试图用同一段代码允许的用例:
1) git checkout branchname
其中branchname
在本地不存在但在远程存在
2) git checkout branchname
,其中branchname
已在本地存在
3) git checkout commitid
对于上下文,以前已按以下方式克隆了存储库:
repo = Git.cloneRepository()
.setCloneSubmodules(true)
.setURI(repoUrl)
.setDirectory(createTempDir())
.setCloneAllBranches(true)
.call();
标准JGit checkout命令不会在本地自动创建分支。 以下代码适用于方案2和3:
repo.checkout()
.setName(branchOrCommitId)
.call();
通过修改创建新分支,它仅适用于方案1:
repo.checkout()
.setCreateBranch(true)
.setName(branchOrCommitId)
.call();
考虑到标准的Git CLI已经在我正在寻找的命令中提供了自动功能,我可以使用这个问题的一个简洁的解决方案吗?
您想要做的是当且仅当本地分支不存在时才创建分支。 以下是我使用的流程,其中exampleRepo是git repo对象,checkout命令是CheckoutCommand,branchName是分支名称:
.setCreateBranch(!exampleRepo.branchList() .call() .stream() .map(Ref::getName) .collect(Collectors.toList()) .contains("refs/heads/" + branchName));
到目前为止我找到的一个可能的解决方案是检查本地分支是否存在并且是一个ID,以便结合问题中提到的两种方法:
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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.