如何使用JGit查找提交的分支?

7
我需要使用JGit获取与特定提交相关联的分支名称。我使用JGit获取存储库的完整提交SHA列表,现在需要知道它所属的分支的名称。 如果有人能告诉我如何实现这一点,我将不胜感激。

1
只有分支的提示(最近提交)实际上与该分支“关联”。对于其他提交,您只能通过查看提交图和历史记录来猜测。 - everton
2个回答

4
在Git中,提交(commit)不属于分支。提交是不可变的,而分支可以更改它们的名称以及它们所指向的提交。
如果有一个分支直接指向提交或是提交的后继,那么从分支(或标签,或其他引用)可以到达该提交。
在JGit中,可以使用NameRevCommand命令查找一个分支是否直接指向了某个提交。例如:
Map<ObjectId, String> map = git
  .nameRev()
  .addPrefix("refs/heads")
  .add(ObjectId.fromString("<SHA-1>"))
  .call();

上面的代码片段在 refs/heads 命名空间中查找指向给定提交的引用。返回的映射最多包含一个条目,其中键是给定的提交 ID,值表示指向它的分支。

当给定的映射为空时是什么意思(遇到了期望“master”的问题)。 - Antoniossss
似乎找不到指向使用“add”命令提供的提交ID的引用。原生Git会返回任何内容吗? - Rüdiger Herrmann
没有进行检查(因为这是临时存储库,只获取了单个分支)。我怀疑这与我实际使用的fetch_head有关 - 例如,我必须使用“additionalRefs”才能使log像在存储库数据库中一样工作,因为refs为空。如果使用.all()进行提取,则可以找到分支名称(无需使用additionalRefs)。 - Antoniossss
你可以尝试使用addRefFETCH_HEADRef让命令考虑它。 - Rüdiger Herrmann

2

根据文档所述,

ListBranchCommand类

setContains方法(String containsCommitish)

该方法用于设置包含指定提交的分支列表。

setContains

public ListBranchCommand setContains(String containsCommitish)

If this is set, only the branches that contain the specified commit-ish as an ancestor are returned.

Parameters:
containsCommitish - a commit ID or ref name

Returns:
this instance

Since:
3.4

这个API对应于git branch --contains <commit-ish>

如果您想列出远程分支(-r)或者远程和本地分支(-a),您也可能需要使用此API。

setListMode

public ListBranchCommand setListMode(ListBranchCommand.ListMode listMode)

Parameters:
listMode - optional: corresponds to the -r/-a options; by default, only local branches will be listed

Returns:
this instance

示例:

#list all the branches that "HEAD" belongs to.
try {
    Git git = Git.open(new File("D:/foo/.git"));
    List<Ref> refs = git.branchList().setContains("HEAD").setListMode(ListBranchCommand.ListMode.ALL).call();
    System.out.println(refs);
} catch (Exception e) {
    System.out.println(e);
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接