Skip to content

Instantly share code, notes, and snippets.

@jkimbo
Last active April 12, 2022 14:20
Show Gist options
  • Save jkimbo/71648f2053b19f6b8b03c410d0a633b9 to your computer and use it in GitHub Desktop.
Save jkimbo/71648f2053b19f6b8b03c410d0a633b9 to your computer and use it in GitHub Desktop.
#!/usr/bin/env bash
if [ -z "$1" ]; then
echo "Diff or diff range not provided"
exit 1
fi
diff_range=$1
shift
set -Eeuo pipefail
function get_branch_from_commit() {
commit=$1
set -x
branch=$(git notes show $commit 2> /dev/null || echo "")
if [[ $branch != "branch:"* ]]; then
echo ""
return
else
branch_name=${branch#"branch:"}
echo $branch_name
return
fi
}
function sync_single_commit {
commit=$1
short_commit=$(echo $commit | cut -c1-7)
echo "Syncing diff $short_commit"
# Check that commit is valid
git cat-file -e "$commit"
# Determine base branch
# If parent commit has a branch then use that
# Otherwise assume origin/main
parent_commit=$(git rev-parse "$commit^")
base_ref=$(get_branch_from_commit $parent_commit)
if [[ -z "$base_ref" ]]; then
base_ref="origin/main"
else
echo "Parent commit has been synced to $base_ref"
read -p "Would you like to stack your change? [y/n] " -n 1 -r
echo # (optional) move to a new line
if [[ ! $REPLY =~ ^[Yy]$ ]]; then
base_ref="origin/main"
fi
fi
branch_name=$(get_branch_from_commit $commit)
if [[ -z "$branch_name" ]]; then
echo "Creating new branch"
# Generate branch name
branch_name="$(git show --no-patch --format="%f" "$commit" | awk '{print tolower($0)}')"
git notes add -m "branch:$branch_name" $commit
fi
current_branch=$(git rev-parse --abbrev-ref HEAD)
echo "Syncing $short_commit to branch $branch_name"
set -x
# Delete branch locally
git branch -D "$branch_name" &> /dev/null || true
# Create branch on top of parent diff
git branch --no-track "$branch_name" $base_ref
git switch "$branch_name"
# Then cherry pick commit onto branch
if ! git cherry-pick "$commit"; then
git cherry-pick --abort
git switch "$current_branch"
exit 1
fi
# Force push branch
git push origin "$branch_name" --force
git switch "$current_branch"
set +x
echo ""
echo "Create a PR 🔽"
if [[ $base_ref == "origin/main" ]]; then
echo " https://github.com/frontedxyz/synthwave/compare/main...$branch_name"
else
echo " https://github.com/frontedxyz/synthwave/compare/$base_ref...$branch_name"
fi
echo ""
}
if [[ $diff_range == *"..."* ]]; then
echo "Diff range is not supported yet"
exit 1
fi
sync_single_commit $diff_range
exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment