p-ranav/cppgit2

Trying to commit fires a libgit2 exception

Opened this issue · 0 comments

Hello, your example about git add and git commit only works with non-existing repo.
Trying to launch it against pre-cloned one leads to

terminate called after throwing an instance of 'cppgit2::git_exception'
  what():  failed to create commit: current tip is not the first parent
Aborted (core dumped)

Ok, no problem. Looks like libgit wants us to put head commit to the list of parents. So, I changed your example code to:

#include <cppgit2/repository.hpp>
#include <fstream>
#include <iostream>
using namespace cppgit2;

int main(int argc, char **argv) {
  if (argc == 2) {
    // Create new repo
    auto repo = repository::init(argv[1], false);

    // Write README file
    std::ofstream readme;
    readme.open(std::string{argv[1]} + "/README.md");
    readme << "Hello, World!";
    readme.close();

    // Stage README.md
    auto index = repo.index();
    index.add_entry_by_path("README.md");
    index.write();
    auto tree_oid = index.write_tree();

    // Prepare signatures
    auto author = signature("foobar", "foo.bar@baz.com");
    auto committer = signature("foobar", "foo.bar@baz.com");
    auto head_commit = repo.lookup_commit(repo.head().target());

    // Create commit
    auto commit_oid =
        repo.create_commit("HEAD", author, committer, "utf-8", "Update README",
                           repo.lookup_tree(tree_oid), {head_commit});

    std::cout << "Created commit with ID: " << commit_oid.to_hex_string()
              << std::endl;

  } else {
    std::cout << "Usage: ./executable <new_repo_path>\n";
  }
}

Changes:
1: added
auto head_commit = repo.lookup_commit(repo.head().target());
2: changed

auto commit_oid = 
  repo.create_commit("HEAD", author, committer, "utf-8", "Update README", 
  repo.lookup_tree(tree_oid), {});

to

auto commit_oid = 
  repo.create_commit("HEAD", author, committer, "utf-8", "Update README", 
  repo.lookup_tree(tree_oid), {head_commit});

However this time all I get is

Created commit with ID: ae140784904fab2e8f8ca8cce2fbecd06d79af09
testgit: /home/user/src/cpp/contrib/libgit2-1.0.0/src/mwindow.c:102: git_mwindow_put_pack: Assertion `git__pack_cache' failed.
Aborted (core dumped)

As you see. technically the code does work and commit is made, however I cannot rid of that exception which breaks the rest of the code.