Is there a way to find out what branch a commit comes from given its SHA-1 hash value?
Bonus points if you can tell me how to accomplish this using Ruby Grit.
Update December 2013:
sschuberth comments
git-what-branch
(Perl script, see below) does not seem to be maintained anymore. git-when-merged is an alternative written in Python that's working very well for me.
It is based on "Find merge commit which include a specific commit".
git when-merged [OPTIONS] COMMIT [BRANCH...]
Find when a commit was merged into one or more branches.
Find the merge commit that broughtCOMMIT
into the specified BRANCH(es).Specifically, look for the oldest commit on the first-parent history of
BRANCH
that contains theCOMMIT
as an ancestor.
Original answer September 2010:
Sebastien Douche just twitted (16 minutes before this SO answer):
git-what-branch: Discover what branch a commit is on, or how it got to a named branch
This is a Perl script from Seth Robertson that seems very interesting:
SYNOPSIS
git-what-branch [--allref] [--all] [--topo-order | --date-order ]
[--quiet] [--reference-branch=branchname] [--reference=reference]
<commit-hash/tag>...
OVERVIEW
Tell us (by default) the earliest causal path of commits and merges to cause the requested commit got onto a named branch. If a commit was made directly on a named branch, that obviously is the earliest path.
By earliest causal path, we mean the path which merged into a named branch the earliest, by commit time (unless
--topo-order
is specified).PERFORMANCE
If many branches (e.g. hundreds) contain the commit, the system may take a long time (for a particular commit in the Linux tree, it took 8 second to explore a branch, but there were over 200 candidate branches) to track down the path to each commit.
Selection of a particular--reference-branch --reference tag
to examine will be hundreds of times faster (if you have hundreds of candidate branches).EXAMPLES
# git-what-branch --all 1f9c381fa3e0b9b9042e310c69df87eaf9b46ea4
1f9c381fa3e0b9b9042e310c69df87eaf9b46ea4 first merged onto master using the following minimal temporal path:
v2.6.12-rc3-450-g1f9c381 merged up at v2.6.12-rc3-590-gbfd4bda (Thu May 5 08:59:37 2005)
v2.6.12-rc3-590-gbfd4bda merged up at v2.6.12-rc3-461-g84e48b6 (Tue May 3 18:27:24 2005)
v2.6.12-rc3-461-g84e48b6 is on master
v2.6.12-rc3-461-g84e48b6 is on v2.6.12-n
[...]
This program does not take into account the effects of cherry-picking the commit of interest, only merge operations.
I deal with the same problem (Jenkins multibranch pipeline) - having only commit information and trying to find a branch name where this commit originally came from. It must work for remote branches, local copies are not available.
This is what I work with:
git rev-parse HEAD | xargs git name-rev
Optionally you can strip the output:
git rev-parse HEAD | xargs git name-rev | cut -d' ' -f2 | sed 's/remotes\/origin\///g'