使用普通的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已经在我正在寻找的命令中提供自动功能,我可以使用这个问题吗?
答案 0 :(得分:3)
您想要做的是仅当不存在本地分支时才创建分支。这是我使用流制作的,其中exampleRepo是git repo对象,checkout命令是CheckoutCommand,branchName是分支名称。:
.setCreateBranch(!exampleRepo.branchList()
.call()
.stream()
.map(Ref::getName)
.collect(Collectors.toList())
.contains("refs/heads/" + branchName));
答案 1 :(得分:0)
到目前为止我找到的一个可能的解决方案是检查本地分支是否存在并且是一个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();