LibGit2提交示例

Mic*_*kis 2 git

我试图使用LibGit2,我陷入了提交.我试过 这个只适用于"初始"提交的那个.对于下一次提交,它失败,-15"当前提示不是第一个父级".

两个问题:

  1. 我怎么知道如果我需要初始提交?
  2. 如何执行非初始提交?

谢谢.

Sch*_*ern 8

我怎么知道如果我需要初始提交?

您可以检查git_repository_head_unborn()以查看HEAD是否指向引用.

如何执行非初始提交?

您需要提供要提交的索引.这是使用git_repository_index()最简单的方法.但是,索引必须以树的形式提供.容易混淆的命名为git_index_write_tree()会将索引写入树中.

要获取父节点,请使用git_oid_fromstr()从散列或git_reference_name_to_id()获取对象ID,以从引用名称(例如"HEAD" )获取它.然后使用git_commit_lookup()从oids中获取提交对象.

然后将它们传递给git_commit_create()git_commit_create_v().使用git_commit_create_v()可以避免必须列出git_commit指针,只需将提交作为参数传递给printf().

在ex/general.c中有一个很好的例子,它比我更好地解释了所有步骤.我也喜欢使用围绕libgit2的Perl包装器Git :: Raw作为示例.查看.xs文件(基本上是C).

这是一个未经测试的将索引提交给HEAD的示例.我假设你已经有作者,提交者和回购.

git_oid tree_id, parent_id, commit_id;
git_tree *tree;
git_commit *parent;
git_index *index;

/* Get the index and write it to a tree */
git_repository_index(&index, repo);
git_index_write_tree(tree, index);

/* Get HEAD as a commit object to use as the parent of the commit */
git_reference_name_to_id(parent_id, repo, "HEAD");
git_commit_lookup(&parent, repo, parent_id);

/* Do the commit */
git_commit_create_v(
    commit_id,
    repo,
    "HEAD",     /* The commit will update the position of HEAD */
    author,
    committer,
    NULL,       /* UTF-8 encoding */
    message,
    tree,       /* The tree from the index */
    1,          /* Only one parent */
    parent      /* No need to make a list with create_v */
);
Run Code Online (Sandbox Code Playgroud)

  • 不要检查`git_repository_is_empty`,用`git_repository_head_unborn`检查你的`HEAD`是否指向一个天生的分支.否则,你会尝试在一个非空的仓库中查询父母你在一个未出生的分支上(来自`git checkout --orphan <branch>`). (3认同)