Created
November 6, 2024 21:25
-
-
Save mmastrac/31d3fc4134a7376fa0b9cf02d7651293 to your computer and use it in GitHub Desktop.
This file contains 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 -euf -o pipefail | |
# Check if the correct number of arguments are provided | |
if [ "$#" -ne 2 ]; then | |
echo "Usage: $0 <PR-number> <origin-branch>" | |
exit 1 | |
fi | |
# Arguments | |
PR_NUMBER=$1 | |
ORIGIN_BRANCH=$2 | |
# Fetch the latest from the origin branch | |
git fetch origin $ORIGIN_BRANCH | |
# Check if the branch for the PR is already checked out in any worktree | |
if git worktree list | grep -q "pull/$PR_NUMBER"; then | |
echo "PR branch 'pull/$PR_NUMBER' is already checked out in a worktree." | |
exit 1 | |
fi | |
# Fetch the PR head and create a local branch for it | |
git fetch --force origin "refs/pull/$PR_NUMBER/head:pull/$PR_NUMBER" | |
# Create a temporary worktree | |
WORKTREE_DIR=$(mktemp -d) | |
git worktree add "$WORKTREE_DIR" "pull/$PR_NUMBER" | |
# Move to the worktree | |
cd "$WORKTREE_DIR" || exit 1 | |
# Function to clean up the worktree and branch on exit | |
cleanup() { | |
# Move back to the original directory | |
cd - > /dev/null | |
git worktree remove "$WORKTREE_DIR" > /dev/null | |
git branch -D "pull/$PR_NUMBER" > /dev/null | |
} | |
trap cleanup EXIT | |
# Squash all commits in the PR into a single commit with your username and email | |
# Get configured Git author name and email | |
GIT_AUTHOR_NAME=$(git config user.name) | |
GIT_AUTHOR_EMAIL=$(git config user.email) | |
COMMON_ANCESTOR=$(git merge-base "origin/$ORIGIN_BRANCH" HEAD) | |
echo "Common ancestor: $COMMON_ANCESTOR" | |
git reset --soft "$COMMON_ANCESTOR" | |
git commit --author="$GIT_AUTHOR_NAME <$GIT_AUTHOR_EMAIL>" -m "Squashed PR #$PR_NUMBER" | |
# Print the new commit hash | |
NEW_COMMIT=$(git rev-parse HEAD) | |
echo "Squashed commit: $NEW_COMMIT" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment