[英]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.