Question

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

Was it helpful?

Solution

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

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