I searched Google and Stackoverflow for an answer to a question on how to code the equivalent of git commit -a -m "message" in libgit2 ( https://libgit2.github.com ) and C or C ++. But I can’t find a ready and working answer to this question. I am using libgit2-0.21.
Below is the code that initializes the git repository, adds two files to it, and splits the two files so that they are ready to commit.
My question is how to code "git commit -a -m" msg "in libgit2?
#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 ();
string directory = "repository";
mkdir (directory.c_str(), 0777);
git_repository *repo = NULL;
int result = git_repository_init (&repo, directory.c_str(), false);
if (result != 0) cerr << giterr_last ()->message << endl;
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 ();
git_index * index = NULL;
result = git_repository_index (&index, repo);
if (result != 0) cerr << giterr_last ()->message << endl;
result = git_index_add_all (index, NULL, 0, NULL, NULL);
if (result != 0) cerr << giterr_last ()->message << endl;
result = git_index_write (index);
if (result != 0) cerr << giterr_last ()->message << endl;
system ("cd repository; git status");
git_index_free (index);
git_repository_free (repo);
git_threads_shutdown ();
return 0;
}
The code can be compiled as follows:
g++ -Wall -I/opt/local/include -L/opt/local/lib -lgit2 -o test git.cpp
The following is the result of running the compiled binary:
On branch master
Initial commit
Changes to be committed:
(use "git rm --cached <file>..." to unstage)
new file: file1
new file: file2
source
share