Finding what branch a Git commit came from

后端 未结 14 2379
失恋的感觉
失恋的感觉 2020-11-22 10:43

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.

14条回答
  •  无人及你
    2020-11-22 11:33

    TL;DR:

    Use the below if you care about shell exit statuses:

    • branch-current - the current branch's name
    • branch-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.


    Aliases useful in scripting

    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\" #"
    

    Commit only reachable from only one branch

    % git branch-name eae13ea
    master
    % echo $?
    0
    
    • Output is to STDOUT
    • Exit value is 0.

    Commit reachable from multiple branches

    % git branch-name 4bc6188
    Multiple branches:
    attempt-extract
    master%
    % echo $?
    1
    
    • Output is to STDERR
    • The exit value is 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 #"
    

提交回复
热议问题