Skip to content

Instantly share code, notes, and snippets.

@th3nolo
Created May 26, 2025 13:30
Show Gist options
  • Save th3nolo/f1fa03796895b4a868b1c81cf8fe6f63 to your computer and use it in GitHub Desktop.
Save th3nolo/f1fa03796895b4a868b1c81cf8fe6f63 to your computer and use it in GitHub Desktop.

Revisions

  1. th3nolo created this gist May 26, 2025.
    49 changes: 49 additions & 0 deletions checkout_pr_branch.sh
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,49 @@
    #!/usr/bin/env bash
    # ---------------------------------------------------------------------------
    # checkout_pr_branch.sh · Quick‑test any PR branch locally
    # ---------------------------------------------------------------------------
    # Given the name of a remote branch (e.g. the head branch of a Pull Request),
    # this script will:
    # 1. Fetch that branch from the chosen remote (default: "origin").
    # 2. Create (or reset) a local branch that tracks the remote branch.
    # 3. Switch you to the new local branch so you can run / build / test.
    #
    # ---------------------------------------------------------------------------
    # Usage
    # ./checkout_pr_branch.sh <branch-name> [remote] [local-alias]
    #
    # <branch-name> – The head branch of the PR (e.g. feat/migration-alert-message)
    # [remote] – Git remote to fetch from (default: origin)
    # [local-alias] – Optional different name for the local branch
    #
    # Examples
    # # 1. Typical workflow – same name locally & remote, remote is origin
    # ./checkout_pr_branch.sh feat/migration-alert-message
    #
    # # 2. Remote PR in upstream and you want to call your local branch "test‑pr"
    # ./checkout_pr_branch.sh feat/xyz upstream test-pr
    # ---------------------------------------------------------------------------
    set -e # Exit on first error

    if [[ -z "$1" ]]; then
    echo "Usage: $0 <branch-name> [remote] [local-alias]"
    exit 1
    fi

    BRANCH="$1"
    REMOTE="${2:-origin}"
    LOCAL_ALIAS="${3:-$BRANCH}"

    # Verify remote exists -------------------------------------------------------
    if ! git remote | grep -qx "$REMOTE"; then
    echo "❌ Remote '$REMOTE' not found. Add it first: git remote add $REMOTE <url>"
    exit 1
    fi

    echo "➜ Fetching '$BRANCH' from '$REMOTE' …"
    git fetch "$REMOTE" "$BRANCH"

    echo "➜ Creating/updating local branch '$LOCAL_ALIAS' to track '$REMOTE/$BRANCH' …"
    git checkout -B "$LOCAL_ALIAS" --track "$REMOTE/$BRANCH"

    echo "✅ Done! You are now on branch '$LOCAL_ALIAS'. Happy testing!"