Как сделать коммит из данных файлов? - PullRequest
0 голосов
/ 15 января 2019

Мне нужно использовать libgit2 для реализации команды "git commit -F ...".

Код ниже будет фиксировать 1.txt и 2.txt:

git_libgit2_init();

git_repository* pRepository;
git_index* pIndex;
git_oid oidTree, oidCommitted;
git_tree* pTree;
git_signature* pSignature;

git_repository_init(&pRepository, "C:\\Temp", false);
git_repository_index(&pIndex, pRepository);
git_index_add_bypath(pIndex, "1.txt");
git_index_add_bypath(pIndex, "2.txt");
git_index_write(pIndex);
git_index_write_tree(&oidTree, pIndex);
git_tree_lookup(&pTree, pRepository, &oidTree);
git_signature_now(&pSignature, "My name", "My email");
git_commit_create(&oidCommitted, pRepository, "refs/heads/master",
    pSignature, pSignature, NULL, "Initial commit with 1.txt", pTree, 0, NULL);
git_signature_free(pSignature);
git_tree_free(pTree);
git_index_free(pIndex);
git_repository_free(pRepository);

git_libgit2_shutdown();

Как изменить мой код для реализации:

git add 1.txt 2.txt
git commit 1.txt -m "Initial commit with 1.txt"

1 Ответ

0 голосов
/ 15 января 2019

Вы хотите создать древовидный объект для передачи на git_commit_create без изменения индекса репозитория. Есть несколько способов сделать это. Самый простой - создать собственный индекс в памяти и использовать его вместо индекса репозитория. По сути, сделайте что-то вроде этого:

...
git_repository_init(&repo, ...); // same as before
git_index_new(&index); // create in-memory index
git_index_read_tree(index, headTree); // initialize to the current HEAD
git_index_add_by_path(index, "1.txt"); // update the nominated file(s)
git_index_write_tree_to(&oid, index, repo); // write the tree into the repo
git_tree_lookup(&tree, repo, &oid); // same as before
...
...