Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find the branch a git commit is on? (Using libgit2sharp)

For a research project, I've been trying to replicate the graph view present in version control software like SourceTree or TortoiseGit.

The graph view I'm trying to implement The graph view I'm trying to implement

The biggest problem I'm having is finding what branch a commit belongs to. If I have this, I can assign the commit dot a column and a color. This is difficult because under the hood, Git doesn't store the branch the commit was initially on.

Looking at other solutions on StackOverflow, I found it is possible to get a list of branches that contain the commit, but I need a method of isolating a single one to display in my graph. In the same way SourceTree or TortoiseGit somehow manage to do it.

My problem is also identical to this one, Find out the branch a commit belongs to in LibGit2Sharp?

It looks like they discovered the actual solution in a private discussion room. However, I don't have the reputation to comment and ask what they found.

Does anyone have any ideas on how I could do this?

Or, @nulltoken if by chance you see this and remember, do you know what you guys discovered in that discussion room?

like image 979
Jade White Avatar asked Nov 14 '17 03:11

Jade White


2 Answers

Not sure how much of helpful this answer would prove to you. The LibGit2Sharp equivalent call for "git branch --contains $SHA1" is a requested feature on GitHub, an open one!

Long back, I used a query over all refs like this, but for your use-case it might be prohibitively slow.

I was trying to think for possible ways to mitigate this problem, could not come up with any guiding light. :( And then I discovered this comment which asserts that you need to traverse the DAG and validate the actual branch which has the commit. It all hints that you would need to go the slow traverse-all-refs approach.

like image 161
vishwarajanand Avatar answered Nov 14 '22 06:11

vishwarajanand


It turns out to generate the graph, SourceTree doesn't need to know what branch a commit is on.

The first commit in the graph always has a column of 0. Also, it's possible to get a list of parent commits of a given commit. By starting with the first commit and iterating backwards, they can generate a nice looking graph by only using this info.

like image 30
Jade White Avatar answered Nov 14 '22 06:11

Jade White