From 72a33a1ef95918d684cc3b80fcee29a312484889 Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Thu, 19 Nov 2026 16:52:11 -0600 Subject: [PATCH 1/2] fix: wait for branch checks before merging preview PRs --- .github/workflows/argocd-promote-helm.yaml | 47 +++++++++++++++++----- .github/workflows/preview-cleanup.yaml | 20 ++++++--- scripts/merge-promotion-pr.sh | 42 +++++++++++++++++++ 3 files changed, 92 insertions(+), 17 deletions(-) create mode 100644 scripts/merge-promotion-pr.sh diff --git a/.github/workflows/argocd-promote-helm.yaml b/.github/workflows/argocd-promote-helm.yaml index 0d527d6..cd87695 100644 --- a/.github/workflows/argocd-promote-helm.yaml +++ b/.github/workflows/argocd-promote-helm.yaml @@ -254,7 +254,8 @@ jobs: config.prBody = `Promotes ${config.name} to ${config.sourceInfo}`; config.prBranch = `promote/${config.name}-${refName}`; } else { - config.prTitle = `Preview ${config.name}`; + const source = mode === 'pr' ? `${baseRepository}#${pr.number}` : config.name; + config.prTitle = `feat(${context.repo.repo}): preview ${source}`; config.prBody = `Preview environment for ${config.sourceInfo}`; config.prBranch = `preview/${config.name}`; } @@ -653,29 +654,53 @@ jobs: gh pr create --repo ${{ inputs.environment_repository }} --title "${{ env.PR_TITLE }}" --body "${{ env.PR_BODY }}" --base ${DEFAULT_BRANCH} --head ${{ env.PR_BRANCH }} fi - - name: "[Promotion PR] Merge Pull Request" - if: inputs.dry_run == false && steps.config.outputs.promotion_mode == 'pull-request-merge' && steps.commit_changes.outputs.committed_changes == 'true' + - name: "[Promotion PR] Find the Open Pull Request" + id: promotion-pr + if: inputs.dry_run == false && steps.config.outputs.promotion_mode == 'pull-request-merge' && (inputs.preview || steps.commit_changes.outputs.committed_changes == 'true') env: GH_TOKEN: ${{ steps.auth.outputs.token }} PR_BRANCH: ${{ env.PR_BRANCH }} + ENVIRONMENT_REPOSITORY: ${{ inputs.environment_repository }} + COMMITTED_CHANGES: ${{ steps.commit_changes.outputs.committed_changes }} run: | PR_NUMBER=$(gh pr list \ - --repo ${{ inputs.environment_repository }} \ + --repo "${ENVIRONMENT_REPOSITORY}" \ --head "${PR_BRANCH}" \ --state open \ --json number \ - --jq '.[0].number') + --jq '.[0].number // empty') - if [ -z "${PR_NUMBER}" ]; then + if [ -z "${PR_NUMBER}" ] && [ "${COMMITTED_CHANGES}" = true ]; then echo "No open promotion PR found for branch ${PR_BRANCH}" exit 1 fi - echo "Squash-merging promotion PR #${PR_NUMBER}" - gh pr merge "${PR_NUMBER}" \ - --repo ${{ inputs.environment_repository }} \ - --squash \ - --delete-branch + echo "number=${PR_NUMBER}" >> "$GITHUB_OUTPUT" + + - name: Checkout the promotion merge helper + if: inputs.preview && steps.promotion-pr.outputs.number != '' + uses: actions/checkout@v7 + with: + repository: hops-ops/workflows-gitops + ref: ${{ job.workflow_sha }} + path: .hops-workflows + sparse-checkout: scripts + persist-credentials: false + + - name: "[Promotion PR] Merge Pull Request" + if: steps.promotion-pr.outputs.number != '' + env: + GH_TOKEN: ${{ steps.auth.outputs.token }} + PR_NUMBER: ${{ steps.promotion-pr.outputs.number }} + ENVIRONMENT_REPOSITORY: ${{ inputs.environment_repository }} + PREVIEW: ${{ inputs.preview }} + run: | + if [ "$PREVIEW" = true ]; then + expected_head="$(git -C environment rev-parse HEAD)" + bash .hops-workflows/scripts/merge-promotion-pr.sh "$ENVIRONMENT_REPOSITORY" "$PR_NUMBER" "$expected_head" + else + gh pr merge "$PR_NUMBER" --repo "$ENVIRONMENT_REPOSITORY" --squash --delete-branch + fi - name: "[Dry Run][Preview][Promotion PR] Create Pull Request" if: inputs.dry_run && steps.config.outputs.promotion_pr == 'true' && inputs.preview && steps.commit_changes.outputs.has_changes == 'true' diff --git a/.github/workflows/preview-cleanup.yaml b/.github/workflows/preview-cleanup.yaml index d90650e..648a6cb 100644 --- a/.github/workflows/preview-cleanup.yaml +++ b/.github/workflows/preview-cleanup.yaml @@ -192,24 +192,32 @@ jobs: --repo "${ENVIRONMENT_REPOSITORY}" \ --base "${DEFAULT_BRANCH}" \ --head "${PR_BRANCH}" \ - --title "Remove preview for ${{ github.repository }}#${{ github.event.pull_request.number }}" \ + --title "chore(${{ github.event.repository.name }}): remove preview for ${{ github.repository }}#${{ github.event.pull_request.number }}" \ --body "Removes the preview environment for ${{ github.event.pull_request.html_url }}.") PR_NUMBER=${PR_URL##*/} fi echo "number=${PR_NUMBER}" >> "${GITHUB_OUTPUT}" + - name: Checkout the promotion merge helper + if: steps.cleanup-pr.outputs.number != '' && inputs.promotion_mode == 'pull-request-merge' + uses: actions/checkout@v7 + with: + repository: hops-ops/workflows-gitops + ref: ${{ job.workflow_sha }} + path: .hops-workflows + sparse-checkout: scripts + persist-credentials: false + - name: Merge Cleanup Pull Request - if: steps.commit.outputs.committed == 'true' && inputs.promotion_mode == 'pull-request-merge' + if: steps.cleanup-pr.outputs.number != '' && inputs.promotion_mode == 'pull-request-merge' env: GH_TOKEN: ${{ steps.auth.outputs.token }} PR_NUMBER: ${{ steps.cleanup-pr.outputs.number }} ENVIRONMENT_REPOSITORY: ${{ inputs.environment_repository }} run: | - gh pr merge "${PR_NUMBER}" \ - --repo "${ENVIRONMENT_REPOSITORY}" \ - --squash \ - --delete-branch + expected_head="$(git rev-parse HEAD)" + bash .hops-workflows/scripts/merge-promotion-pr.sh "$ENVIRONMENT_REPOSITORY" "$PR_NUMBER" "$expected_head" - name: Find Cleanup Comment if: steps.commit.outputs.committed == 'true' diff --git a/scripts/merge-promotion-pr.sh b/scripts/merge-promotion-pr.sh new file mode 100644 index 0000000..87bbcc8 --- /dev/null +++ b/scripts/merge-promotion-pr.sh @@ -0,0 +1,42 @@ +#!/usr/bin/env bash +set -euo pipefail + +repository="$1" +number="$2" +expected_head="$3" +deadline=$((SECONDS + 300)) + +while true; do + pr="$(gh api "repos/$repository/pulls/$number" --jq '[.head.sha, .state, .merged] | @tsv')" + IFS=$'\t' read -r head state merged <<< "$pr" + if [[ "$head" != "$expected_head" ]]; then + echo "::error::Promotion PR #$number no longer points to $expected_head" + exit 1 + fi + if [[ "$merged" == true ]]; then + echo "Promotion PR #$number is merged" + exit 0 + fi + if [[ "$state" != open ]]; then + echo "::error::Promotion PR #$number closed before it could merge" + exit 1 + fi + + if result="$(gh pr merge "$number" --repo "$repository" --squash --delete-branch \ + --match-head-commit "$expected_head" 2>&1)"; then + printf '%s\n' "$result" + exit 0 + fi + + case "$result" in + *'base branch policy prohibits the merge'*|*'Required status check '*) ;; + *) printf '%s\n' "$result" >&2; exit 1 ;; + esac + if (( SECONDS >= deadline )); then + printf '%s\n' "$result" >&2 + echo "::error::Branch policy still blocks promotion PR #$number after five minutes" + exit 1 + fi + echo "Waiting for branch policy to allow promotion PR #$number" + sleep 10 +done From 181de78cd0ccbdd6df02a178b3a427257d5cc633 Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Thu, 19 Nov 2026 16:55:13 -0600 Subject: [PATCH 2/2] test: exercise preview PR merge retries in CI --- .github/workflows/on-pr.yaml | 2 ++ tests/test_merge_promotion_pr.py | 61 ++++++++++++++++++++++++++++++++ 2 files changed, 63 insertions(+) create mode 100644 tests/test_merge_promotion_pr.py diff --git a/.github/workflows/on-pr.yaml b/.github/workflows/on-pr.yaml index 9a3c686..40b9567 100644 --- a/.github/workflows/on-pr.yaml +++ b/.github/workflows/on-pr.yaml @@ -20,6 +20,8 @@ jobs: run: | yq -o=json .github/workflows/argocd-promote-helm.yaml > "$RUNNER_TEMP/promotion.json" python3 tests/test_values_merge.py "$RUNNER_TEMP/promotion.json" + - name: Exercise the preview PR merge retry + run: python3 tests/test_merge_promotion_pr.py # Release promotions would not normally go in PRs, but we include them here for testing purposes diff --git a/tests/test_merge_promotion_pr.py b/tests/test_merge_promotion_pr.py new file mode 100644 index 0000000..a14f619 --- /dev/null +++ b/tests/test_merge_promotion_pr.py @@ -0,0 +1,61 @@ +"""Exercise the merge helper with the errors from a protected environment repo.""" +import json +import os +from pathlib import Path +import subprocess +import tempfile + +SCRIPT = Path(__file__).resolve().parents[1] / "scripts/merge-promotion-pr.sh" +REPOSITORY = "example/preview-envs" +NUMBER = "42" +HEAD = "a" * 40 +STATUS = ["api", f"repos/{REPOSITORY}/pulls/{NUMBER}", "--jq", "[.head.sha, .state, .merged] | @tsv"] +MERGE = ["pr", "merge", NUMBER, "--repo", REPOSITORY, "--squash", "--delete-branch", "--match-head-commit", HEAD] + +GH = """#!/usr/bin/env python3 +import json +import os +from pathlib import Path +import sys + +fixture = Path(os.environ["FIXTURE"]) +responses = json.loads(fixture.read_text()) +args, output, code = responses.pop(0) +assert sys.argv[1:] == args, (sys.argv[1:], args) +fixture.write_text(json.dumps(responses)) +print(output, file=sys.stderr if code else sys.stdout) +sys.exit(code) +""" + +OPEN = (STATUS, f"{HEAD}\topen\tfalse", 0) +BLOCKED = (MERGE, "the base branch policy prohibits the merge", 1) +REQUIRED = (MERGE, 'Required status check "gate / CI gate" is expected.', 1) +SUCCESS = (MERGE, "Merged", 0) +MERGED = (STATUS, f"{HEAD}\tclosed\ttrue", 0) +CHANGED = (STATUS, f"{'b' * 40}\topen\tfalse", 0) +CLOSED = (STATUS, f"{HEAD}\tclosed\tfalse", 0) +DENIED = (MERGE, "Resource not accessible by integration", 1) + +for name, expected_code, responses in ( + ("immediate success", 0, [OPEN, SUCCESS]), + ("both merge errors while waiting for CI", 0, [OPEN, BLOCKED, OPEN, REQUIRED, OPEN, SUCCESS]), + ("another run merges the expected head", 0, [OPEN, BLOCKED, MERGED]), + ("the head changes during the wait", 1, [OPEN, BLOCKED, CHANGED]), + ("the PR closes without merging", 1, [CLOSED]), + ("the credential cannot merge", 1, [OPEN, DENIED]), +): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + for command, body in (("gh", GH), ("sleep", "#!/bin/sh\nexit 0\n")): + stub = root / command + stub.write_text(body) + stub.chmod(0o755) + fixture = root / "responses.json" + fixture.write_text(json.dumps(responses)) + env = dict(os.environ, PATH=f"{root}:{os.environ['PATH']}", FIXTURE=str(fixture)) + result = subprocess.run(["bash", SCRIPT, REPOSITORY, NUMBER, HEAD], env=env, + capture_output=True, text=True, timeout=5) + assert result.returncode == expected_code, (name, result.stdout, result.stderr) + assert not json.loads(fixture.read_text()), (name, result.stdout, result.stderr) + assert "Traceback" not in result.stderr, (name, result.stderr) + print("PASS:", name)