Last active
December 20, 2023 04:38
-
-
Save KurtGokhan/d1fd49cac394276be53769b0dfb20795 to your computer and use it in GitHub Desktop.
Squash a git branch without rebasing
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/sh | |
squash_branch() { | |
# Usage: squash_branch [branch_name] | |
# This is an implementation of Option 1 here: https://blog.oddbit.com/post/2019-06-17-avoid-rebase-hell-squashing-wi/ | |
# WARNING: This function will delete the target branch and replace it with a squashed version of itself | |
BASE_BRANCH="master" | |
if [ -z "$1" ]; then | |
# Get the current branch name | |
BRANCH_NAME=$(git rev-parse --abbrev-ref HEAD) | |
else | |
BRANCH_NAME="$1" | |
fi | |
if [ "$BRANCH_NAME" = "$BASE_BRANCH" ]; then | |
echo "Error: The target branch is the same branch as the base branch. Please provide a different branch name." | |
return 1 | |
fi | |
TEMP_BRANCH="temp/squash/${BRANCH_NAME}" | |
# Check out a new temporary branch based on the base branch | |
git checkout -b "${TEMP_BRANCH}" "${BASE_BRANCH}" || return 1 | |
# Bring in the changes from the feature branch using git merge --squash | |
git merge --squash "${BRANCH_NAME}" || { | |
git checkout "${BRANCH_NAME}" | |
git branch -D "${TEMP_BRANCH}" | |
return 1 | |
} | |
# Commit the changes with an appropriate commit message | |
git commit --no-verify || return 1 | |
# Return to the feature branch and reset it to the squashed version | |
git checkout "${BRANCH_NAME}" || return 1 | |
git reset --hard "${TEMP_BRANCH}" || return 1 | |
# Optionally clean up the temp branch | |
git branch -D "${TEMP_BRANCH}" | |
## Additional optional steps: | |
# Push the changes to the remote feature branch (with force) | |
# git push -f | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment