Question

I want to implement git log -1 fullpath/myfile with libgit2. I am fairly new to libgit2. Am I on the right track? This is what I have so far:

git_repository_head(&refToHead, repo);

headOID = git_reference_oid(refToHead);
git_commit_lookup(&headCommit, repo, headOID);

headTreeOID = git_commit_tree_oid(headCommit);
git_tree_lookup(&tree, repo, headTreeOID);

git_tree_entry_byname(tree, "repopath/myfile");

Unfortunately git_tree_entry_byname seems not to work for files in subdirectories of the repo. Any idea?

Thank you, Lars

Was it helpful?

Solution

Unfortunately git_tree_entry_byname seems not to work for files in subdirectories of the repo.

git_tree_entry_byname only works against the entries (trees, blobs and, when supported, submodules) which are immediately under the passed tree.

One simple solution to your question would be to rely on git_tree_get_subtree (see tests) to retrieve the deepest subtree contained in a tree, given its relative path. This would work no matter how deep the entry is in the tree structure.

Thus, you'd have to call git_tree_git_subtree to retrieve the parent tree of the entry you're after, then invoke get_tree_entry_byname passing it the parent tree.

I want to implement git log -1 fullpath/myfile with libgit2

If you're willing to retrieve which commit lastly updated a file, you might want to take a look at this answer which gives some general purpose hints on the file history topic and caveats.

I can't find any clue to get the commit in your linked answer.

You'll have to leverage the revision walking API.

  • Description of the feature can be found here.
  • A test demonstrating different walking strategies may also provide you with some help

Basically, you'd have to find out from the HEAD the oid of the tree entry matching your filename. Once this is done you'd have to recursively walk the parents of the HEAD commit and, for each commit tree, try and identify one of the two following changes.

  • Detect if the file has been renamed (the tree entry has disappeared from its parent tree, a new file with the same oid popped up under the parent tree)
  • Detect if the content of the file has changed (the tree entry still exists with its name but its oid has changed).

Exit from the loop ass soon as you detect one, or when you have no more commit to process.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top