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.
Use the below if you care about shell exit statuses:
branch-current
- the current branch's namebranch-names
- clean branch names (one per line)branch-name
- Ensure that only one branch is returned from branch-names
Both branch-name
and branch-names
accept a commit as the argument, and default to HEAD
if none is given.
branch-current = "symbolic-ref --short HEAD" # https://stackoverflow.com/a/19585361/5353461
branch-names = !"[ -z \"$1\" ] && git branch-current 2>/dev/null || git branch --format='%(refname:short)' --contains \"${1:-HEAD}\" #" # https://stackoverflow.com/a/19585361/5353461
branch-name = !"br=$(git branch-names \"$1\") && case \"$br\" in *$'\\n'*) printf \"Multiple branches:\\n%s\" \"$br\">&2; exit 1;; esac; echo \"$br\" #"
% git branch-name eae13ea
master
% echo $?
0
0
.% git branch-name 4bc6188
Multiple branches:
attempt-extract
master%
% echo $?
1
1
.Because of the exit status, these can be safely built upon. For example, to get the remote used for fetching:
remote-fetch = !"branch=$(git branch-name \"$1\") && git config branch.\"$branch\".remote || echo origin #"