8

我正在尝试使用 libgit2 来读取当前分支的名称。我必须做某种解决吗?

我尝试使用

git_branch_lookup

查找git_referencefor HEAD,但结果是

Unable to find local branch 'HEAD'

谢谢!

4

3 回答 3

9

运行git branch -a不列出HEAD。在 libgit2 中,HEAD也不被视为有效分支。这只是一个参考

如果您想发现哪个引用是当前分支,那么您应该

  • 加载当前HEAD参考(尝试git_repository_head()方便的方法)
  • 确定其类型(使用git_reference_type()
  • 根据其类型(GIT_REF_SYMBOLICGIT_REF_OID)检索以下之一
    • 分支名称(使用git_reference_symbolic_target()
    • 指向的提交(使用git_reference_target()
于 2012-08-26T19:43:02.953 回答
0

当遇到这个确切的问题时,我没有发现现有的答案/评论有帮助。相反,我结合了git_reference_lookup()and git_reference_symbolic_target()

git_reference* head_ref;
git_reference_lookup(&head_ref, repo, "HEAD");
const char *symbolic_ref;
symbolic_ref = git_reference_symbolic_target(head_ref);
std::string result;
// Skip leading "refs/heads/" -- 11 chars.
if (symbolic_ref) result = &symbolic_ref[11];
git_reference_free(head_ref);

这感觉像是一种肮脏的黑客行为,但这是我管理过的最好的。该result字符串要么以空结尾(例如,分离头,没有签出分支),要么包含签出分支的名称。符号目标由 ref 拥有,因此在释放它之前将该值复制到字符串中!

于 2021-01-21T19:26:35.747 回答
0

在https://libgit2.org/libgit2/ex/HEAD/status.html有一个例子。它是基于方法的get_reference_shorthand。这应该给出分支名称而不是引用,因此不需要字符串操作,并且它也应该在分支和远程具有不同名称的边缘情况下工作。

static void show_branch(git_repository *repo, int format)
{
  int error = 0;
  const char *branch = NULL;
  git_reference *head = NULL;

  error = git_repository_head(&head, repo);

  if (error == GIT_EUNBORNBRANCH || error == GIT_ENOTFOUND)
    branch = NULL;
  else if (!error) {
    branch = git_reference_shorthand(head);
  } else
    check_lg2(error, "failed to get current branch", NULL);

  if (format == FORMAT_LONG)
    printf("# On branch %s\n",
      branch ? branch : "Not currently on any branch.");
  else
    printf("## %s\n", branch ? branch : "HEAD (no branch)");

  git_reference_free(head);
}
于 2021-01-31T22:26:59.690 回答