Skip to content

Instantly share code, notes, and snippets.

@volhovm
Created February 20, 2025 18:11
Show Gist options
  • Save volhovm/5c13a7270f3a64eac9d7383a3b4f26f3 to your computer and use it in GitHub Desktop.
Save volhovm/5c13a7270f3a64eac9d7383a3b4f26f3 to your computer and use it in GitHub Desktop.
A bash script creating a branch for every commit in the current branch relative to the parent one (for PR trains)
#!/bin/env bash
parent_branch="$1"
original_branch="$2"
if [ -z "$parent_branch" ]; then
echo "Please provide branch name as argument"
exit 1
fi
if [ -z "$original_branch" ]; then
echo "Using current branch for the train"
original_branch=$(git rev-parse --abbrev-ref HEAD)
fi
# Get the branch point from master
branch_point=$(git merge-base "$parent_branch" "$original_branch")
# Get list of commits from branch point to tip of branch, in reverse order
commits=$(git rev-list --reverse "$branch_point..$original_branch")
commit_count=$(echo "$commits" | wc -l)
echo "This will create $commit_count branches:"
echo
git log --oneline "$branch_point..$original_branch" | nl
echo
read -p "Proceed? (y/n) " -n 1 -r
echo
if [[ ! $REPLY =~ ^[Yy]$ ]]
then
echo "Operation cancelled"
exit 1
fi
# Save current state
current_branch=$(git rev-parse --abbrev-ref HEAD)
# Counter for branch naming
counter=1
# Previous commit hash for chaining
previous=$branch_point
created_branches=()
for commit in $commits; do
new_branch_name="$original_branch-$counter"
# Create new branch from the previous commit
git checkout -b "$new_branch_name" "$previous"
# Cherry-pick this commit
git cherry-pick "$commit"
# Store this commit as previous for next iteration
previous=$commit
echo "Created branch $new_branch_name"
created_branches+=("$new_branch_name")
counter=$((counter + 1))
done
# Return to original branch
git checkout "$current_branch"
echo "Done! Created $((counter-1)) branches"
echo
read -p "Do you want to push these branches to origin? (y/n) " -n 1 -r
echo
if [[ $REPLY =~ ^[Yy]$ ]]
then
echo "Pushing branches to origin..."
for branch in "${created_branches[@]}"
do
echo "Pushing $branch..."
git push -u origin "$branch"
done
echo "All branches pushed to origin"
else
echo "Branches created locally only"
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment