【问题标题】:Delete branch with jgit not working as expected使用 jgit 删除分支未按预期工作
【发布时间】:2014-07-26 04:20:17
【问题描述】:

我正在尝试使用 jgit 删除我的仓库中的一个分支。

DeleteBranchCommand command = git.branchDelete();
command.setBranchNames("myBranch");
command.setForce(true);
try {
    List<String> deletedBranches = new ArrayList<String>();
deletedBranches = command.call();
System.out.println(deletedBranches.toString());
} catch (GitAPIException e) {
throw new MyInternalErrorException("Error while deleting branch [" + branchName + "]", e);
}

deletedBranches 的值将是 [myBranch]

如果我检查分支是否仍在仓库中:

git.getRepository().getRef("myBranch");

我会收到true。 这是因为 cf to jgit javadoc:

getRef(name)

name 要查找的 ref 的名称。可以是简写形式,例如 "master" 自动扩展为 "refs/heads/master" 如果 “refs/heads/master”已经存在。

它正在检查“refs/heads/myBranch”而不是“myBranch”。

此外,如果我第二次运行deleteBranch 命令,deletedBranches 的值将是[refs/heads/myBranch]。

有人可以解释为什么会发生这种情况,我该如何解决这个问题? 谢谢。

更新

在jgit代码里面调试之后,我注意到了

String fullName = currentRef.getName();

https://github.com/eclipse/jgit/blob/a76a4acf87952249b94f4be29614565541eb8c46/org.eclipse.jgit/src/org/eclipse/jgit/api/DeleteBranchCommand.java#L133

返回“myBranch”而不是“heads/refs/myBranch”,因此它没有执行这段代码:

                if (fullName.startsWith(Constants.R_HEADS)) {
                    String shortenedName = fullName
                            .substring(Constants.R_HEADS.length());
                    // remove upstream configuration if any
                    final StoredConfig cfg = repo.getConfig();
                    cfg.unsetSection(
                            ConfigConstants.CONFIG_BRANCH_SECTION,
                            shortenedName);
                    cfg.save();
                }

https://github.com/eclipse/jgit/blob/a76a4acf87952249b94f4be29614565541eb8c46/org.eclipse.jgit/src/org/eclipse/jgit/api/DeleteBranchCommand.java#L158-L167

【问题讨论】:

    标签: git branch git-branch jgit


    【解决方案1】:

    它可能类似于git branch -d,它将拒绝删除未完全合并到其上游分支中的分支。

    这就是为什么您在org.eclipse.jgit.test/tst/org/eclipse/jgit/api/BranchCommandTest 中看到的示例使用setForce(true)(如git branch -D):

    List<String> deleted = git.branchDelete().setBranchNames("ForDelete")
                .setForce(true).call();
    

    【讨论】:

    • 我同意。这就是为什么我在调用命令之前使用command.setForce(true);,所以它应该等同于git branch -D
    • @victorsc 调用命令时没有异常? (因为您可以将其包装在 'try' 'catch' 中,如 github.com/eclipse/jgit/blob/…)
    • 我在我的问题中简化了一点代码。实际上我把它包裹在 try { deletedBranches = command.call(); System.out.println(deletedBranches.toString()); } catch (GitAPIException e) { throw new MyInternalErrorException("删除分支时出错 [" + branchName + "]", e); }
    • 我完全不明白的是为什么命令第一次删除[myBranch],第二次删除[refs/heads/myBranch]
    • @victorsc 可能是因为第二次没有找到 mybranch ,所以会尝试扩展名。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-12-18
    • 2016-02-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-07
    • 2020-03-12
    • 2011-08-06
    相关资源
    最近更新 更多