如何在不知道 JGit 本地是否存在的情况下检出远程分支?
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 已经在我正在寻找的命令中提供了自动功能,我可以使用这个问题的巧妙解决方案吗?
到目前为止我发现的一个可能的解决方案是检查本地分支是否存在并且是一个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();
当且仅当本地分支不存在时,您想做的是创建一个分支。这是我使用流想到的,其中 exampleRepo 是 git 回购对象,checkout 命令是 CheckoutCommand,branchName 是分支名称。:
git.setCreateBranch(git.branchList()
.call()
.stream()
.map(Ref::getName)
.noneMatch("refs/heads/" + branchName);
使用普通的 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 已经在我正在寻找的命令中提供了自动功能,我可以使用这个问题的巧妙解决方案吗?
到目前为止我发现的一个可能的解决方案是检查本地分支是否存在并且是一个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();
当且仅当本地分支不存在时,您想做的是创建一个分支。这是我使用流想到的,其中 exampleRepo 是 git 回购对象,checkout 命令是 CheckoutCommand,branchName 是分支名称。:
git.setCreateBranch(git.branchList()
.call()
.stream()
.map(Ref::getName)
.noneMatch("refs/heads/" + branchName);