How to find the nearest parent of a Git branch?

后端 未结 21 2064
野性不改
野性不改 2020-11-22 00:54

Let\'s say I have the following local repository with a commit tree like this:

master --> a
            \\
             \\
      develop c --> d
               


        
21条回答
  •  庸人自扰
    2020-11-22 01:26

    A rephrasal

    Another way to phrase the question is "What is the nearest commit that resides on a branch other than the current branch, and which branch is that?"

    A solution

    You can find it with a little bit of command line magic

    git show-branch \
    | sed "s/].*//" \
    | grep "\*" \
    | grep -v "$(git rev-parse --abbrev-ref HEAD)" \
    | head -n1 \
    | sed "s/^.*\[//" 
    

    With awk:

    git show-branch -a \
    | grep '\*' \
    | grep -v `git rev-parse --abbrev-ref HEAD` \
    | head -n1 \
    | sed 's/[^\[]*//' \
    | awk 'match($0, /\[[a-zA-Z0-9\/-]+\]/) { print substr( $0, RSTART+1, RLENGTH-2 )}'
    

    Here's how it works:

    1. Display a textual history of all commits, including remote branches.
    2. Ancestors of the current commit are indicated by a star. Filter out everything else.
    3. Ignore all the commits in the current branch.
    4. The first result will be the nearest ancestor branch. Ignore the other results.
    5. Branch names are displayed [in brackets]. Ignore everything outside the brackets, and the brackets.
    6. Sometimes the branch name will include a ~# or ^# to indicate how many commits are between the referenced commit and the branch tip. We don't care. Ignore them.

    And the Result

    Running the above code on

     A---B---D <-master
          \
           \
            C---E---I <-develop
                 \
                  \
                   F---G---H <-topic
    

    Will give you develop if you run it from H and master if you run it from I.

    The code is available as a gist

提交回复
热议问题