How to detect what commit a branch has been created from in LibGit2Sharp

拜拜、爱过 提交于 2019-12-12 15:26:53

问题


So given an instance of LibGit2Sharp Branch how do you work out what commit that it was initially created from?


回答1:


A Branch is merely an object depicting a git head reference. A head is a text file, mostly living under the .git/refs/heads hierarchy. This text file contains the hash of the commit this head currently points to. Similarly, a Branch bears a Tip property which points to a Commit.

When working with git repositories and performing actions such as committing, resetting, rebasing... the head file is updated with different hashes, pointing to different commits.

A head keeps no track of previous pointed at commits. Neither does the Branch.

With git, when creating a new branch, a new reflog is created. Git takes care of adding a first entry with a message identifying the object the branch has been created from.

Given an existing branch backup

$ cat .git/refs/heads/backup
7dec18258252769d99a4ec9c82225e47d58f958c

Creating a new branch will create and feed its reflog

$ git branch new_branch_from_branch backup

$ git reflog new_branch_from_branch
7dec182 new_branch_from_branch@{0}: branch: Created from backup

Of course, that also works when directly creating a branch from a commit

$ git branch new_branch_from_sha 191adce

$ git reflog new_branch_from_sha
191adce new_branch_from_sha@{0}: branch: Created from 191adce

LibGit2Sharp exposes the reflog as well. For instance, the following code will enumerate the log entries for a specific Branch.

var branch = repository.Head; // or repository.Branches["my_branch"]...

foreach (ReflogEntry e in repository.Refs.Log(branch.CanonicalName))
{
    Console.WriteLine("{0} - {1} : {2}",
        e.From.ToString(7), e.To.ToString(7), e.Message);
}

So "good news", the reflog may contain what you're after ;-)

but...

  • you'll have to find out the correct entry by yourself by searching within each message the "branch: Created from" pattern
  • If your branch is too old, older entries in the reflog may have been removed by the built-in git gc housekeeping process (by default reflog entries are kept for 90 days) and the initial "Created from" entry may now be lost

Note: As of today, LibGit2Sharp doesn't create an entry when creating or removing a branch. However, this is currently tackled by the amazing @dahlbyk as part of Pull Request #499



来源:https://stackoverflow.com/questions/18503208/how-to-detect-what-commit-a-branch-has-been-created-from-in-libgit2sharp

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