|
| 1 | +#!/bin/bash |
| 2 | +# |
| 3 | +# Fork TheAlgorithms/Python (if needed), push the current work to a branch on |
| 4 | +# the fork, and open a pull request against the FORK's default branch. |
| 5 | +# |
| 6 | +# The pull request never targets the upstream repository: `gh pr create` |
| 7 | +# defaults to the parent repo for forks, so --repo is always set to the fork. |
| 8 | +# |
| 9 | +# Usage: |
| 10 | +# scripts/fork_pr.sh <branch> "<pr title>" [<fork issue number>] |
| 11 | +# |
| 12 | +# Examples: |
| 13 | +# scripts/fork_pr.sh devcontainer-ci "Add devcontainer CI workflow" 1 |
| 14 | +# DRY_RUN=1 scripts/fork_pr.sh my-branch "My change" |
| 15 | +# |
| 16 | +# Environment variables: |
| 17 | +# UPSTREAM Repository to fork (default: TheAlgorithms/Python). |
| 18 | +# DRY_RUN=1 Print the commands instead of running them. |
| 19 | + |
| 20 | +set -euo pipefail |
| 21 | + |
| 22 | +if [[ $# -lt 2 ]]; then |
| 23 | + sed -n '2,18p' "$0" |
| 24 | + exit 1 |
| 25 | +fi |
| 26 | + |
| 27 | +branch="$1" |
| 28 | +title="$2" |
| 29 | +issue="${3:-}" |
| 30 | +upstream="${UPSTREAM:-TheAlgorithms/Python}" |
| 31 | + |
| 32 | +run() { |
| 33 | + if [[ -n "${DRY_RUN:-}" ]]; then |
| 34 | + echo "+ $*" |
| 35 | + else |
| 36 | + "$@" |
| 37 | + fi |
| 38 | +} |
| 39 | + |
| 40 | +user="$(gh api user --jq .login)" |
| 41 | +fork="${user}/${upstream#*/}" |
| 42 | + |
| 43 | +# 1. Fork once; `gh repo fork` is a no-op if the fork already exists. |
| 44 | +if ! gh repo view "$fork" >/dev/null 2>&1; then |
| 45 | + run gh repo fork "$upstream" --clone=false |
| 46 | +fi |
| 47 | + |
| 48 | +# 2. Make sure an `origin`-independent remote points at the fork. |
| 49 | +if ! git remote get-url fork >/dev/null 2>&1; then |
| 50 | + run git remote add fork "https://github.com/${fork}.git" |
| 51 | +fi |
| 52 | + |
| 53 | +# 3. Push the branch to the fork. |
| 54 | +if ! git rev-parse --verify --quiet "$branch" >/dev/null; then |
| 55 | + run git checkout -b "$branch" |
| 56 | +fi |
| 57 | +run git push -u fork "$branch" |
| 58 | + |
| 59 | +# 4. Open the PR against the fork's default branch, never upstream. |
| 60 | +base="$(gh repo view "$fork" --json defaultBranchRef --jq .defaultBranchRef.name)" |
| 61 | +body="$(cat .github/pull_request_template.md)" |
| 62 | +if [[ -n "$issue" ]]; then |
| 63 | + body="Fixes #${issue}"$'\n\n'"${body}" |
| 64 | +fi |
| 65 | +run gh pr create --repo "$fork" --base "$base" --head "$branch" \ |
| 66 | + --title "$title" --body "$body" |
0 commit comments