简体   繁体   中英

git: deleting a descendant branch

Assume the following commit structure:

master:      A-B-C-D-E----------------
                  \                   \
branch a:          F-G-H     branch d: N-O
                      \
branch b:              I-J
                          \
branch c:                  K-L-M

I want to delete all branches descending from branch a (in this case, b and c). Is there a way to detect that branch b and c descended from branch a?

Right now I'm thinking of accomplishing this by discovering which branches the common ancestor (G) exists on; which will return a, b, and c; and then comparing the time the branches were provisioned. Afterwards, delete all but the earliest branch.

I'm wondering if there is a cleaner way to do this, and if not, how can I retrieve the timestamp for branch creation?

Desired result:

master:      A-B-C-D-E----------------
                  \                   \
branch a:          F-H'      branch d: N-O

Ok, this may not be the most elegant way, but the following seems to do the trick:

git reflog <branch>

Running this on "b", from the example above, will return something similar:

137c91f b@{0}: branch: Created from a

It's possible to reconstruct the branching tree by running this command on every branch associated to the target commit.

I would use a very small shell script.

#!/bin/bash

# identify the bad commit
BAD_COMMIT=$(git rev-parse "$1")

# loop through branches
for BRANCH in $(git for-each-ref --format="%(refname)" refs/heads); do
  # detect if the branch is in the history, for which fgrep will exit 0
  if (git rev-list $BRANCH | fgrep -q $BAD_COMMIT); then
    echo "Deleting $BRANCH"
    git branch -D $BRANCH
  else
    echo "Keeping $BRANCH"
  fi
done

See also: SO Answer: Iterating through branches

1) delete branch C 2) delete branch B I'm not sure what the H' is; I'm going to guess you want to squash commit H into commit G.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM