“git log -1 fullpath/myfile” with libgit2

橙三吉。 提交于 2020-01-02 23:44:12

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/8481914/git-log-1-fullpath-myfile-with-libgit2

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!