OStack程序员社区-中国程序员成长平台

标题: Finding what branch a Git commit came from [打印本页]

作者: 菜鸟教程小白    时间: 2022-4-23 21:07
标题: Finding what branch a Git commit came from

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.



Best Answer-推荐答案


While Dav is correct that the information isn't directly stored, that doesn't mean you can't ever find out. Here are a few things you can do.

Find branches the commit is on

git branch -a --contains <commit>

This will tell you all branches which have the given commit in their history. Obviously this is less useful if the commit's already been merged.

Search the reflogs

If you are working in the repository in which the commit was made, you can search the reflogs for the line for that commit. Reflogs older than 90 days are pruned by git-gc, so if the commit's too old, you won't find it. That said, you can do this:

git reflog show --all | grep a871742

to find commit a871742. Note that you MUST use the abbreviatd 7 first digits of the commit. The output should be something like this:

a871742 refs/heads/completion@{0}: commit (amend): mpc-completion: total rewrite

indicating that the commit was made on the branch "completion". The default output shows abbreviated commit hashes, so be sure not to search for the full hash or you won't find anything.

git reflog show is actually just an alias for git log -g --abbrev-commit --pretty=oneline, so if you want to fiddle with the output format to make different things available to grep for, that's your starting point!

If you're not working in the repository where the commit was made, the best you can do in this case is examine the reflogs and find when the commit was first introduced to your repository; with any luck, you fetched the branch it was committed to. This is a bit more complex, because you can't walk both the commit tree and reflogs simultaneously. You'd want to parse the reflog output, examining each hash to see if it contains the desired commit or not.

Find a subsequent merge commit

This is workflow-dependent, but with good workflows, commits are made on development branches which are then merged in. You could do this:

git log --merges <commit>..

to see merge commits that have the given commit as an ancestor. (If the commit was only merged once, the first one should be the merge you're after; otherwise you'll have to examine a few, I suppose.) The merge commit message should contain the branch name that was merged.

If you want to be able to count on doing this, you may want to use the --no-ff option to git merge to force merge commit creation even in the fast-forward case. (Don't get too eager, though. That could become obfuscating if overused.) VonC's answer to a related question helpfully elaborates on this topic.






欢迎光临 OStack程序员社区-中国程序员成长平台 (http://ostack.cn/) Powered by Discuz! X3.4