Last active
May 18, 2020 11:36
-
-
Save twolodzko/b70b24dc028c2d46af74792de233bd53 to your computer and use it in GitHub Desktop.
Git squash and rebase branch into a single commit branch
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/bin/bash | |
| set -e | |
| git fetch | |
| BRANCH=$(git rev-parse --abbrev-ref HEAD) | |
| NEWBRANCH="$BRANCH-pr" | |
| if [[ -n $(git rev-parse --verify $NEWBRANCH) ]]; then | |
| read -p "'$NEWBRANCH' exists, do you want to overwrite it? (y/[n])? " CONTINUE | |
| if [[ $CONTINUE != "y" ]]; then | |
| exit 0 | |
| fi | |
| git branch -D $NEWBRANCH | |
| fi | |
| if [[ -z $(git branch | grep dev) ]]; then | |
| TARGET=master | |
| else | |
| TARGET=dev | |
| fi | |
| git fetch | |
| git checkout -b $NEWBRANCH $TARGET | |
| git merge $BRANCH | |
| git reset --soft $TARGET | |
| git commit | |
| git push --force --set-upstream origin $NEWBRANCH | |
| git checkout $BRANCH |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/bin/bash | |
| set -e | |
| if [[ $# -eq 0 ]]; then | |
| BRANCH=$(git rev-parse --abbrev-ref HEAD) | |
| elif [[ "$1" == "-h" || "$1" == "--help" ]]; then | |
| echo "Usage: `basename $0` [branch] [target]" | |
| exit 0 | |
| else | |
| BRANCH=$1 | |
| fi | |
| if [[ $# -lt 2 ]]; then | |
| if [[ -z $(git branch | grep dev) ]]; then | |
| TARGET=master | |
| else | |
| TARGET=dev | |
| fi | |
| read -p "Do you want to squash '$BRANCH' and rebase it to '$TARGET'? (y/[n])? " CONTINUE | |
| if [[ $CONTINUE != "y" ]]; then | |
| exit 0 | |
| fi | |
| else | |
| TARGET=$2 | |
| fi | |
| TEMPORARY="$BRANCH-squashed" | |
| git fetch | |
| git checkout $BRANCH | |
| git diff $TARGET..HEAD > /tmp/1.diff | |
| git checkout $TARGET | |
| git checkout -b $TEMPORARY | |
| git merge $BRANCH | |
| git reset --soft $TARGET | |
| git commit | |
| git diff $TARGET..HEAD > /tmp/2.diff | |
| if [[ $(diff /tmp/1.diff /tmp/2.diff) ]]; then | |
| git branch -D $TEMPORARY | |
| exit 1 | |
| else | |
| rm -f /tmp/1.diff /tmp/2.diff | |
| fi | |
| git push origin $TEMPORARY:$BRANCH --force | |
| git checkout $BRANCH | |
| git branch -D $TEMPORARY | |
| git fetch --all | |
| git reset --hard origin/$BRANCH |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment