如何在 libgit2 中编码 "git commit"?

How to code "git commit" in libgit2?

我在 Google 和 Whosebug 上搜索了关于如何编写等同于 git 提交 -a -m "message" 在 libgit2 (https://libgit2.github.com) 和 C 或 C++ 中。 但是我找不到这个问题的现成有效答案。 我正在使用 libgit2-0.21.

下面是初始化 git 存储库、向其中添加两个文件并暂存这两个文件以准备提交的代码。

我的问题是如何在 libgit2 中编码 "git commit -a -m "msg"?

#include <sys/stat.h>
#include <string>
#include <fstream>
#include <iostream>
#include <git2.h>
using namespace std;


int main (int argc, char** argv)
{
  git_threads_init ();

  // Create repository directory.
  string directory = "repository";
  mkdir (directory.c_str(), 0777);

  // Initialize the repository: git init.
  git_repository *repo = NULL;
  int result = git_repository_init (&repo, directory.c_str(), false);
  if (result != 0) cerr << giterr_last ()->message << endl;

  // Store two files in the repository directory.
  ofstream file;
  file.open ("repository/file1", ios::binary | ios::trunc);
  file << "Contents of file one";
  file.close ();

  file.open ("repository/file2", ios::binary | ios::trunc);
  file << "Contents of file two";
  file.close ();

  // Run the equivalent of "git add ."

  // Get the git index.
  git_index * index = NULL;
  result = git_repository_index (&index, repo);
  if (result != 0) cerr << giterr_last ()->message << endl;

  // Add all files to the git index.
  result = git_index_add_all (index, NULL, 0, NULL, NULL);
  if (result != 0) cerr << giterr_last ()->message << endl;

  // Write the index to disk.
  result = git_index_write (index);
  if (result != 0) cerr << giterr_last ()->message << endl;

  // Run the equivalent of "git commit -a -m "commit message".

  // How to do that through libgit2?


  // Run "git status" to see the result.
  system ("cd repository; git status");

  // Free resources.
  git_index_free (index);
  git_repository_free (repo);
  git_threads_shutdown ();

  return 0;
}

代码可以这样编译:

g++ -Wall -I/opt/local/include -L/opt/local/lib -lgit2 -o test git.cpp

下面是 运行 编译二进制文件的输出:

On branch master

Initial commit

Changes to be committed:
  (use "git rm --cached <file>..." to unstage)

    new file:   file1
    new file:   file2

索引更新后

  • 通过 git_index_write_tree()
  • 从中创建一棵树
  • 创建一个通过 git_commit_create_v()
  • 引用此树的提交

查看此端到端 test 其执行等同于以下内容

 $ echo "test" > test.txt
 $ git add .
 $ git commit -m "Initial commit"