Skip to content

Instantly share code, notes, and snippets.

@Tehnix
Created January 21, 2025 09:51
Show Gist options
  • Save Tehnix/6d17640d96786b768916d22eb7d028c2 to your computer and use it in GitHub Desktop.
Save Tehnix/6d17640d96786b768916d22eb7d028c2 to your computer and use it in GitHub Desktop.
Helper function for blocking push to main and automatically creating a Pull Request on push if none exist
#!/usr/bin/env bash
# Optional, if you have gp aliased already:
# unalias gp
function gp() {
branchName=$(git branch --show-current)
# Only run if in a specific organization.
# gitRemote=$(git config --get remote.origin.url)
# Use this instead: if [[ "$gitRemote" = *":yaaytravel/"* && "$branchName" != "main" ]]; then
if [[ "$branchName" != "main" ]]; then
prJson=$(gh pr view --json state,url)
prState=$(echo "$prJson" | jq -r .state)
if [[ "$prState" == "OPEN" ]]; then
prUrl=$(echo "$prJson" | jq -r .url)
echo "✦ Pull Request already exists, pushing commits..."
echo " └── $prUrl"
echo "✦ Pushing commits..."
git push "$@"
else
echo "✦ Branch doesn't have Pull Request, creating one based on branch name..."
prTitle="$branchName"
# Turn branch style of "<type>/<description>" into the PR title style of "[<type>] <description>".
if [[ "$prTitle" == *"/"* ]]; then
firstPart=$(echo "$branchName" | cut -d "/" -f 1)
restParts=$(echo "$branchName" | cut -d "/" -f 2-)
prTitle="[$firstPart] $restParts"
fi
# Push the branch first, so that GitHub knows where the PR should go.
git push "$@"
gh pr create --title "$prTitle" --fill-verbose --draft --assignee "@me"
fi
else
# Otherwise block pushes to main.
echo "✦ Pushing to main is blocked, please create a branch and push to it."
fi
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment