Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 36 additions & 11 deletions .github/workflows/argocd-promote-helm.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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}`;
}
Expand Down Expand Up @@ -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'
Expand Down
2 changes: 2 additions & 0 deletions .github/workflows/on-pr.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
20 changes: 14 additions & 6 deletions .github/workflows/preview-cleanup.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand Down
42 changes: 42 additions & 0 deletions scripts/merge-promotion-pr.sh
Original file line number Diff line number Diff line change
@@ -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
61 changes: 61 additions & 0 deletions tests/test_merge_promotion_pr.py
Original file line number Diff line number Diff line change
@@ -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)
Loading