diff --git a/.github/scripts/cherry-pick-to-release.sh b/.github/scripts/cherry-pick-to-release.sh index 69a655d110..599ca084c2 100755 --- a/.github/scripts/cherry-pick-to-release.sh +++ b/.github/scripts/cherry-pick-to-release.sh @@ -32,6 +32,22 @@ # 5. Milestone lookup is best-effort. If the milestone doesn't exist yet # the PR is created without one and a warning note is added to the body. # +# 6. Backport issue lookup is also best-effort: if the original PR's +# closing keywords reference an issue, and that issue has a sub-issue +# milestoned VERSION (the backport issue created by +# create-backport-issue.sh when the issue was labeled +# "Hotfix "), a human-readable "Fixes #" line +# is appended to the cherry-pick PR body for visibility. Because the +# cherry-pick PR targets a release branch (not the default branch), +# GitHub does not parse closing keywords into 'closingIssuesReferences' +# for it at all (that's populated only for keywords on default-branch +# PRs, or issues manually linked via the PR's "Development" sidebar), so +# the "Fixes #N" text alone would never let close-backport-issue.yml +# find the issue to close. A machine-readable +# "" marker is also embedded in +# the body; close-backport-issue.sh reads that marker directly instead +# of relying on 'closingIssuesReferences'. +# # REQUIRED ENVIRONMENT VARIABLES # ------------------------------ # VERSION Full hotfix version, e.g. "7.0.1". @@ -154,6 +170,134 @@ lookup_milestone() { fi } +# -- Helper: look up the backport issue --------------------------------------- +# Best-effort, mirroring lookup_milestone. If the original PR's closing +# keywords reference an issue, and that issue has a sub-issue milestoned +# VERSION (the backport issue created by create-backport-issue.sh when the +# issue was labeled "Hotfix "), a "Fixes #" line is +# appended to the cherry-pick PR body for human visibility, and the issue +# number is also recorded in a "" marker. +# Because this PR targets a release branch rather than the default branch, +# GitHub does not populate 'closingIssuesReferences' for closing keywords in +# its body at all (only default-branch keyword references and manually +# sidebar-linked issues appear there), so the "Fixes #N" text by itself gives +# close-backport-issue.yml nothing to find. The marker is the only reliable +# record of which issue(s) to close once this PR merges. +# If nothing matches, this is silently skipped — it's a convenience, not a +# requirement. +# create-backport-issue.sh (creates that sub-issue) and this cherry-pick can +# run concurrently, both triggered by the same "Hotfix " label event +# — most directly when sync-hotfix-label-from-issue.sh dispatches +# cherry-pick-hotfix.yml in "reconcile" mode for an already-merged PR at the +# same time hotfix-label-issue.yml is creating the backport issue. To avoid +# a false "nothing to find" from that race, a missing sub-issue is retried a +# few times (with a short delay) as long as the parent issue still carries +# the label that would have triggered its creation. +lookup_backport_issue() { + local version="$1" + BACKPORT_ISSUE_NOTE="" + local backport_issue_numbers="" + + # closingIssuesReferences can include issues from other repositories (e.g. + # "Fixes owner/other#123"). Only consider references in this repository — + # a bare '.number' would otherwise let a cross-repo reference collide with + # an unrelated local issue of the same number. 'gh ... --jq' takes a single + # query string (no jq '--arg' passthrough — see note above), so the repo + # is escaped and interpolated directly. + local repo_escaped + repo_escaped=$(printf '%s' "${GITHUB_REPOSITORY}" | sed 's/["\\]/\\&/g') + + local closing_issues + closing_issues=$(gh pr view "${PR_NUMBER}" --repo "${GITHUB_REPOSITORY}" \ + --json closingIssuesReferences \ + --jq ".closingIssuesReferences[] | select((.repository.owner.login + \"/\" + .repository.name) == \"${repo_escaped}\") | .number" \ + 2>/dev/null || true) + + if [[ -z "${closing_issues}" ]]; then + return + fi + + # 'gh api --jq' takes a single query string and does not support jq's + # '--arg' for safe variable injection, so the version is escaped and + # interpolated directly into the filter expression. + local version_escaped + version_escaped=$(printf '%s' "${version}" | sed 's/["\\]/\\&/g') + + # A single PR can close multiple Hotfix-labeled parent issues for the same + # release (e.g. two related bugs fixed together); accumulate a "Fixes" line + # for every parent that has a matching backport issue instead of stopping + # at the first match, so the cherry-pick PR closes all of them. + # + # A parent issue's sub-issues can include unrelated children milestoned to + # the same release (e.g. a separate follow-up task), so matching on + # milestone alone can pick the wrong one. create-backport-issue.sh always + # titles the backport issue "[VERSION] ", so also require + # that deterministic prefix to identify the right sub-issue. + # create-backport-issue.sh (triggered by the same "Hotfix " label + # on the parent issue) runs concurrently with this cherry-pick, not before + # it — there's no ordering guarantee between the two. If the parent issue + # currently carries the label but its backport sub-issue hasn't shown up + # yet, retry briefly rather than silently missing it on the first look. + # A handful of short retries comfortably covers that workflow's runtime + # without meaningfully delaying the (far more common) case where no + # backport issue is expected at all. + local -r backport_lookup_max_attempts=6 + local -r backport_lookup_retry_delay_seconds=10 + + local issue_number backport_number match_count attempt issue_labels + while IFS= read -r issue_number; do + [[ -z "${issue_number}" ]] && continue + + for (( attempt = 1; attempt <= backport_lookup_max_attempts; attempt++ )); do + backport_number=$(gh api "repos/${GITHUB_REPOSITORY}/issues/${issue_number}/sub_issues" \ + --paginate --jq ".[] | select(.milestone.title == \"${version_escaped}\" and (.title | startswith(\"[${version_escaped}] \"))) | .number" \ + 2>/dev/null || true) + match_count=$(grep -c . <<< "${backport_number}" || true) + backport_number=$(head -n1 <<< "${backport_number}") + + if [[ -n "${backport_number}" ]]; then + break + fi + + # Nothing found yet. Only worth retrying if the parent issue still + # carries the label that would have triggered create-backport-issue.sh + # in the first place — otherwise no backport issue is expected and + # retrying would just waste time. + issue_labels=$(gh api "repos/${GITHUB_REPOSITORY}/issues/${issue_number}" \ + --jq '.labels[].name' 2>/dev/null || true) + if ! grep -qx "Hotfix ${version}" <<< "${issue_labels}"; then + break + fi + + if [[ "${attempt}" -lt "${backport_lookup_max_attempts}" ]]; then + echo "No backport issue found yet for #${issue_number} (milestone '${version}')," \ + "but the 'Hotfix ${version}' label is present; retrying" \ + "(attempt ${attempt}/${backport_lookup_max_attempts})..." + sleep "${backport_lookup_retry_delay_seconds}" + fi + done + + if [[ "${match_count}" -gt 1 ]]; then + echo "::warning::Issue #${issue_number} has multiple sub-issues titled" \ + "'[${version}] ...' milestoned '${version}'; using the first (#${backport_number})." + fi + + if [[ -n "${backport_number}" ]]; then + echo "Found backport issue #${backport_number} (sub-issue of #${issue_number}, milestone '${version}')." + BACKPORT_ISSUE_NOTE+=$'\n\nFixes #'"${backport_number}" + backport_issue_numbers+="${backport_number} " + fi + done <<< "${closing_issues}" + + # Prepend the machine-readable marker (if any backport issues were found) + # so close-backport-issue.sh can recover the issue numbers without relying + # on GitHub's closing-keyword parsing, which doesn't run for non-default- + # branch PRs. Kept on its own HTML-comment line so it never renders. + if [[ -n "${backport_issue_numbers}" ]]; then + BACKPORT_ISSUE_NOTE=$'\n\n'"${BACKPORT_ISSUE_NOTE}" + fi +} + # -- Step 4: Attempt the cherry-pick ------------------------------------------ # Options (--mainline) must precede the commit operand. if git cherry-pick ${MAINLINE_FLAG} "${MERGE_COMMIT_SHA}"; then @@ -162,12 +306,13 @@ if git cherry-pick ${MAINLINE_FLAG} "${MERGE_COMMIT_SHA}"; then git push origin "${CHERRY_PICK_BRANCH}" lookup_milestone "${VERSION}" + lookup_backport_issue "${VERSION}" gh pr create \ --base "${TARGET_BRANCH}" \ --head "${CHERRY_PICK_BRANCH}" \ --title "[${VERSION} Cherry-pick] ${PR_TITLE}" \ - --body "Cherry-pick of #${PR_NUMBER} (${MERGE_COMMIT_SHA}) into \`${TARGET_BRANCH}\`.${MILESTONE_NOTE}" \ + --body "Cherry-pick of #${PR_NUMBER} (${MERGE_COMMIT_SHA}) into \`${TARGET_BRANCH}\`.${MILESTONE_NOTE}${BACKPORT_ISSUE_NOTE}" \ ${MILESTONE_ARG} else # --- Conflict path --- @@ -192,6 +337,7 @@ else git push origin "${CHERRY_PICK_BRANCH}" lookup_milestone "${VERSION}" + lookup_backport_issue "${VERSION}" # Build the PR body using printf to avoid quoting pitfalls with embedded # newlines (mixed $'...' and '...' quoting can leave literal \n in output). @@ -199,6 +345,7 @@ else "Cherry-pick of #${PR_NUMBER} (${MERGE_COMMIT_SHA}) into " \ "\`${TARGET_BRANCH}\` **failed due to merge conflicts**." \ "${MILESTONE_NOTE}" \ + "${BACKPORT_ISSUE_NOTE}" \ $'\n\nPlease resolve manually:\n```bash\n' \ "git fetch origin" \ $'\n' \ diff --git a/.github/scripts/close-backport-issue.sh b/.github/scripts/close-backport-issue.sh new file mode 100755 index 0000000000..01ba7d3792 --- /dev/null +++ b/.github/scripts/close-backport-issue.sh @@ -0,0 +1,122 @@ +#!/usr/bin/env bash +################################################################################# +# Licensed to the .NET Foundation under one or more agreements. # +# The .NET Foundation licenses this file to you under the MIT license. # +# See the LICENSE file in the project root for more information. # +################################################################################# +# +# close-backport-issue.sh +# +# Explicitly closes the backport issue(s) that a cherry-pick PR (created by +# cherry-pick-to-release.sh) is meant to close, after that PR merges into a +# non-default branch (e.g. a release/X.Y branch). +# +# WHY THIS EXISTS +# ---------------- +# GitHub only auto-closes an issue referenced by closing keywords (Fixes, +# Closes, Resolves) when the referencing PR merges into the repository's +# *default* branch — and for PRs targeting any other branch, it doesn't even +# populate 'closingIssuesReferences' for keyword references (only issues +# manually linked via the PR's "Development" sidebar show up there). The +# cherry-pick PRs created by cherry-pick-to-release.sh always target a +# release/X.Y branch, so their "Fixes #" text is purely +# cosmetic and gives the GitHub API nothing to report. This script closes the +# gap by reading the "" marker that +# lookup_backport_issue() (in cherry-pick-to-release.sh) embeds in the PR +# body, and closing each issue named there explicitly. Using an explicit +# marker (rather than any closing keyword found in the PR body) also means +# this only ever closes issues our own automation created and recorded, never +# an issue a human happens to reference with "Fixes #N" in an unrelated, +# manually-authored release-branch PR. +# +# OVERVIEW +# -------- +# 1. Read the merged PR's body and extract the issue numbers recorded in +# its "" marker, if any. +# +# 2. For each such issue that is still open, close it with a comment +# linking back to the merged PR. +# +# This is a no-op (and not an error) when the PR has no marker, or when every +# referenced issue is already closed. +# +# REQUIRED ENVIRONMENT VARIABLES +# ------------------------------ +# PR_NUMBER The pull request number that just merged. +# GH_TOKEN GitHub token for 'gh' CLI authentication. +# GITHUB_REPOSITORY Owner/repo (e.g. "dotnet/SqlClient"). Set by Actions. +# +# OUTPUTS +# ------- +# Closes zero or more issues in this repository. +# +# USAGE +# Called from the close-backport-issue.yml workflow. Can also be run +# locally: +# +# export PR_NUMBER=4750 +# export GH_TOKEN="ghp_..." +# export GITHUB_REPOSITORY="dotnet/SqlClient" +# bash .github/scripts/close-backport-issue.sh +# +################################################################################# +set -euo pipefail + +# -- Runtime help ------------------------------------------------------------- +if [[ "${1:-}" == "--help" || "${1:-}" == "-h" ]]; then + # Print the header comment block (between the license banner and the + # closing banner), stripping the leading '# ' prefix. + awk '/^#{2,}$/ { n++; next } n == 2 { sub(/^# ?/, ""); print }' "$0" + exit 0 +fi + +# -- Input validation --------------------------------------------------------- +: "${PR_NUMBER:?PR_NUMBER environment variable is required}" +: "${GITHUB_REPOSITORY:?GITHUB_REPOSITORY environment variable is required}" + +echo "Pull request: #${PR_NUMBER}" + +# -- Step 1: Extract backport issue numbers from the PR body's marker -------- +PR_BODY=$(gh pr view "${PR_NUMBER}" --repo "${GITHUB_REPOSITORY}" \ + --json body --jq '.body') + +# The marker line looks like: +MARKER_LINE=$(grep -o '' <<< "${PR_BODY}" || true) + +if [[ -z "${MARKER_LINE}" ]]; then + echo "No backport-issue-numbers marker found on #${PR_NUMBER}. Nothing to close." + exit 0 +fi + +CLOSING_ISSUES=$(grep -o '[0-9]\+' <<< "${MARKER_LINE}") + +echo "Backport issue numbers: ${CLOSING_ISSUES}" + +# -- Step 2: Close each referenced issue that is still open ------------------- +CLOSED_ANY=0 +while IFS= read -r issue_number; do + [[ -z "${issue_number}" ]] && continue + + # A real API/permission failure here must not be swallowed and mistaken for + # "issue doesn't exist" — surface it loudly instead of silently skipping. + if ! issue_state=$(gh issue view "${issue_number}" --repo "${GITHUB_REPOSITORY}" \ + --json state --jq '.state'); then + echo "::error::Failed to look up state for issue #${issue_number}." >&2 + exit 1 + fi + + if [[ "${issue_state}" != "OPEN" ]]; then + echo "Issue #${issue_number} is already $(tr '[:upper:]' '[:lower:]' <<< "${issue_state}"). Skipping." + continue + fi + + echo "Closing issue #${issue_number} (referenced by merged PR #${PR_NUMBER})." + gh issue close "${issue_number}" --repo "${GITHUB_REPOSITORY}" \ + --reason completed \ + --comment "Closed by #${PR_NUMBER}, which merged into a non-default branch. GitHub only auto-closes issues for PRs merged into the default branch, so this was closed explicitly." + CLOSED_ANY=1 +done <<< "${CLOSING_ISSUES}" + +if [[ "${CLOSED_ANY}" -eq 0 ]]; then + echo "All referenced issues were already closed." +fi diff --git a/.github/scripts/create-backport-issue.sh b/.github/scripts/create-backport-issue.sh new file mode 100755 index 0000000000..033794679c --- /dev/null +++ b/.github/scripts/create-backport-issue.sh @@ -0,0 +1,215 @@ +#!/usr/bin/env bash +################################################################################# +# Licensed to the .NET Foundation under one or more agreements. # +# The .NET Foundation licenses this file to you under the MIT license. # +# See the LICENSE file in the project root for more information. # +################################################################################# +# +# create-backport-issue.sh +# +# Creates a child "backport issue" targeting a hotfix milestone when a +# "Hotfix X.Y.Z" label is added to a parent issue, and links it as a native +# GitHub sub-issue of the parent. +# +# OVERVIEW +# -------- +# This mirrors, on the issue side, what extract-hotfix-versions.sh / +# cherry-pick-to-release.sh already do on the PR side: +# +# 1. Validate that the newly added label matches "Hotfix X.Y.Z". Any other +# label is ignored. +# +# 2. Guard against duplicates: if the parent issue already has a sub-issue +# titled with the "[X.Y.Z] " prefix, do nothing (handles labels being +# removed/re-added, or the workflow re-running). Milestone is +# deliberately not part of this match; see Step 2 below for why. +# +# 3. Look up the X.Y.Z milestone (best-effort, like cherry-pick-to-release.sh's +# milestone lookup — if it doesn't exist yet, the child issue is created +# without one and a note is appended to its body). +# +# 4. Create the child issue titled "[X.Y.Z] ", body +# referencing the parent, carrying the parent's labels minus any +# "Hotfix *" labels (those stay on the parent only, so this workflow +# doesn't recurse on the child). +# +# 5. Link the child issue to the parent as a native GitHub sub-issue via the +# REST "add sub-issue" endpoint (same relationship used for #4737 under +# #4714). +# +# REQUIRED ENVIRONMENT VARIABLES +# ------------------------------ +# EVENT_LABEL The label that was just added (e.g. "Hotfix 7.1.1"). +# PARENT_ISSUE_NUMBER The parent issue's number. +# GH_TOKEN GitHub token for 'gh' CLI authentication. +# GITHUB_REPOSITORY Owner/repo (e.g. "dotnet/SqlClient"). Set by Actions. +# +# OUTPUTS +# ------- +# Creates a new issue and links it as a sub-issue of the parent, unless the +# label doesn't match "Hotfix X.Y.Z" or a matching backport issue already +# exists, in which case the script exits 0 having done nothing. +# +# USAGE +# Called from the hotfix-label-issue.yml workflow. Can also be run locally: +# +# export EVENT_LABEL="Hotfix 7.1.1" +# export PARENT_ISSUE_NUMBER=4714 +# export GH_TOKEN="ghp_..." +# export GITHUB_REPOSITORY="dotnet/SqlClient" +# bash .github/scripts/create-backport-issue.sh +# +################################################################################# +set -euo pipefail + +# -- Runtime help ------------------------------------------------------------- +if [[ "${1:-}" == "--help" || "${1:-}" == "-h" ]]; then + # Print the header comment block (between the license banner and the + # closing banner), stripping the leading '# ' prefix. + awk '/^#{2,}$/ { n++; next } n == 2 { sub(/^# ?/, ""); print }' "$0" + exit 0 +fi + +# -- Input validation --------------------------------------------------------- +: "${EVENT_LABEL:?EVENT_LABEL environment variable is required}" +: "${PARENT_ISSUE_NUMBER:?PARENT_ISSUE_NUMBER environment variable is required}" +: "${GITHUB_REPOSITORY:?GITHUB_REPOSITORY environment variable is required}" + +# -- Step 1: Validate the label matches "Hotfix X.Y.Z" ------------------------ +if [[ "${EVENT_LABEL}" =~ ^Hotfix\ ([0-9]+\.[0-9]+\.[0-9]+)$ ]]; then + VERSION="${BASH_REMATCH[1]}" +else + echo "Label '${EVENT_LABEL}' is not a valid 'Hotfix X.Y.Z' label. Skipping." + exit 0 +fi + +CHILD_TITLE_PREFIX="[${VERSION}] " + +echo "Parent issue: #${PARENT_ISSUE_NUMBER}" +echo "Hotfix label: ${EVENT_LABEL}" +echo "Version: ${VERSION}" + +# -- Step 2: Guard against duplicates ----------------------------------------- +# Look at the parent's existing sub-issues. If one already carries the child +# title prefix for VERSION, a backport issue for this version already +# exists — nothing to do. Matching is on title prefix only, never milestone +# alone (see the loop below for why). +# +# NOTE: the milestone column uses "NONE" rather than "" for issues without a +# milestone. Tab is IFS whitespace, so 'read' silently collapses/skips a +# leading empty field, which would otherwise shift every column left. +# +# A failed lookup (network/permission error) must NOT be treated the same as +# "no sub-issues exist" — that would defeat the duplicate guard and create a +# second backport issue on a rerun. Do not suppress stderr here so a real +# failure is both visible in the log and distinguishable (via exit code) from +# a legitimately empty (but successful) call. +if ! EXISTING_SUB_ISSUES=$(gh api "repos/${GITHUB_REPOSITORY}/issues/${PARENT_ISSUE_NUMBER}/sub_issues" \ + --paginate --jq '.[] | [(.milestone.title // "NONE"), .title, (.number|tostring)] | @tsv'); then + echo "::error::Failed to look up existing sub-issues for #${PARENT_ISSUE_NUMBER};" \ + "cannot verify a backport issue doesn't already exist. Aborting to avoid creating a duplicate." >&2 + exit 1 +fi + +if [[ -n "${EXISTING_SUB_ISSUES}" ]]; then + while IFS=$'\t' read -r sub_milestone sub_title sub_number; do + # Match on the deterministic "[VERSION] " title prefix only — matching on + # milestone alone would also catch an unrelated sub-issue that just + # happens to be milestoned to the same release (e.g. a separate follow-up + # task), causing this guard to wrongly skip creating the real backport + # issue. The title prefix alone is sufficient: it's set unconditionally + # in Step 5 below regardless of whether the milestone was found yet, so + # it still detects a previously-created (possibly milestone-less) + # backport issue on a rerun. + if [[ "${sub_title}" == "${CHILD_TITLE_PREFIX}"* ]]; then + echo "::notice::Backport issue #${sub_number} for '${VERSION}' already exists under parent #${PARENT_ISSUE_NUMBER}" \ + "(milestone: ${sub_milestone}). Skipping." + exit 0 + fi + done <<< "${EXISTING_SUB_ISSUES}" +fi + + + +# -- Step 3: Look up the parent issue's title/labels -------------------------- +PARENT_JSON=$(gh issue view "${PARENT_ISSUE_NUMBER}" --repo "${GITHUB_REPOSITORY}" \ + --json title,labels) +PARENT_TITLE=$(jq -r '.title' <<< "${PARENT_JSON}") + +# Copy the parent's labels onto the child, excluding any "Hotfix *" labels — +# those are only meaningful (and only drive automation) on the parent issue. +CHILD_LABELS=$(jq -r '[.labels[].name | select(startswith("Hotfix ") | not)] | join(",")' \ + <<< "${PARENT_JSON}") + +# -- Step 4: Recover a child issue created by an earlier incomplete run ------ +# Issue creation and sub-issue linking are separate API operations. If the +# issue was created but the link failed, a rerun cannot find it among the +# parent's sub-issues. Search for the exact title prefix and body identity, +# and only adopt issues authored by the Actions bot. +ORPHAN_SEARCH="in:title \"${CHILD_TITLE_PREFIX% }\" in:body \"Backport of #${PARENT_ISSUE_NUMBER}\"" +if ! ORPHAN_ISSUE_NUMBER=$(gh issue list --repo "${GITHUB_REPOSITORY}" \ + --state all --limit 1000 --search "${ORPHAN_SEARCH}" \ + --json number,title,body,author \ + | jq -r --arg title_prefix "${CHILD_TITLE_PREFIX}" \ + --arg body_prefix "Backport of #${PARENT_ISSUE_NUMBER} for the \`${VERSION}\` hotfix." \ + '[.[] | select(.title | startswith($title_prefix)) | select(.body | startswith($body_prefix)) | select(.author.login == "github-actions" or .author.login == "github-actions[bot]")] | sort_by(.number) | .[0].number // empty'); then + echo "::error::Failed to search for an unlinked backport issue for #${PARENT_ISSUE_NUMBER};" \ + "cannot safely create another issue. Aborting." >&2 + exit 1 +fi + +if [[ -n "${ORPHAN_ISSUE_NUMBER}" ]]; then + CHILD_NUMBER="${ORPHAN_ISSUE_NUMBER}" + echo "Found previously created, unlinked backport issue #${CHILD_NUMBER}; reusing it." +else + # -- Step 5: Look up the milestone (best-effort) ---------------------------- + MILESTONE_FOUND="" + MILESTONE_NOTE="" + if gh api "repos/${GITHUB_REPOSITORY}/milestones" --method GET --paginate \ + --field state=open --jq '.[].title' | grep -qx "${VERSION}"; then + MILESTONE_FOUND="${VERSION}" + echo "Milestone '${VERSION}' found." + else + echo "::warning::Milestone '${VERSION}' does not exist." \ + "Backport issue will be created without a milestone." + MILESTONE_NOTE=$'\n\n> **Note:** Milestone `'"${VERSION}"'` does not exist yet. Please create it and assign this issue manually.' + fi + + # -- Step 6: Create the child issue ----------------------------------------- + CHILD_BODY="Backport of #${PARENT_ISSUE_NUMBER} for the \`${VERSION}\` hotfix.${MILESTONE_NOTE}" + + # Built as an array (not an unquoted string) because label names in this repo + # can contain spaces (e.g. "Regression :boom:"), which would otherwise be + # word-split incorrectly. The "${ARGS[@]+...}" guard keeps this portable to + # bash 3.2 (macOS default), where referencing an empty array under 'set -u' + # is treated as an unbound variable. + ARGS=() + if [[ -n "${CHILD_LABELS}" ]]; then + ARGS+=(--label "${CHILD_LABELS}") + fi + if [[ -n "${MILESTONE_FOUND}" ]]; then + ARGS+=(--milestone "${MILESTONE_FOUND}") + fi + + CHILD_URL=$(gh issue create \ + --repo "${GITHUB_REPOSITORY}" \ + --title "${CHILD_TITLE_PREFIX}${PARENT_TITLE}" \ + --body "${CHILD_BODY}" \ + "${ARGS[@]+"${ARGS[@]}"}") + + CHILD_NUMBER="${CHILD_URL##*/}" + echo "Created backport issue #${CHILD_NUMBER}: ${CHILD_URL}" +fi + +# -- Step 7: Link the child as a native GitHub sub-issue of the parent -------- +# The sub-issues REST API takes the child issue's numeric database *id* (not +# its user-facing number, and not its node_id), so resolve it first. +CHILD_ID=$(gh api "repos/${GITHUB_REPOSITORY}/issues/${CHILD_NUMBER}" --jq '.id') + +gh api "repos/${GITHUB_REPOSITORY}/issues/${PARENT_ISSUE_NUMBER}/sub_issues" \ + --method POST \ + --header "Accept: application/vnd.github+json" \ + -F "sub_issue_id=${CHILD_ID}" \ + >/dev/null + +echo "Linked #${CHILD_NUMBER} as a sub-issue of #${PARENT_ISSUE_NUMBER}." diff --git a/.github/scripts/extract-hotfix-versions.sh b/.github/scripts/extract-hotfix-versions.sh index b7c702a8f8..a189ca3b6d 100755 --- a/.github/scripts/extract-hotfix-versions.sh +++ b/.github/scripts/extract-hotfix-versions.sh @@ -12,14 +12,28 @@ # # OVERVIEW # -------- -# This script handles two distinct trigger scenarios: +# This script handles three distinct trigger scenarios: # -# 1. 'closed' event — The PR was just merged. ALL "Hotfix X.Y.Z" labels on -# the PR are processed, emitting one version per valid label. +# 1. 'closed' event — The PR was just merged. ALL "Hotfix X.Y.Z" labels +# on the PR are processed, emitting one version per valid label. No +# duplicate check is needed: the PR has never been processed before. # -# 2. 'labeled' event — A label was added to an already-merged PR. Only the -# NEWLY ADDED label is considered, and only if a cherry-pick for that -# version hasn't already been created (branch or PR exists). +# 2. 'labeled' event — A label was added to an already-merged PR (the +# real GitHub webhook fired). ALL current labels are reconciled, and only +# versions without an existing cherry-pick (branch or PR) are processed. +# This makes replacement of a pending workflow run safe: the latest +# labeled event includes the full set of current PR labels. +# +# 3. 'reconcile' event — Used for a workflow_dispatch re-run (see +# cherry-pick-hotfix.yml): sync-hotfix-label-from-issue.sh adds a +# "Hotfix X.Y.Z" label to an already-merged PR using GITHUB_TOKEN, which +# does not fire a new "labeled" webhook event (GitHub does not trigger +# further workflow runs for events caused by the repository's own +# GITHUB_TOKEN), so nothing would otherwise process that label. This mode +# re-derives ALL "Hotfix X.Y.Z" labels currently on the PR — like +# 'closed' — but, like 'labeled', skips any version that already has a +# cherry-pick branch or PR, since some of the PR's other labels may have +# already been processed by an earlier event. # # Label names must match the exact pattern "Hotfix .." # (e.g. "Hotfix 7.0.1"). All other labels are silently ignored. @@ -27,9 +41,10 @@ # REQUIRED ENVIRONMENT VARIABLES # ------------------------------ # LABELS Comma-separated list of all label names on the PR. -# EVENT_ACTION The GitHub event action: "closed" or "labeled". +# EVENT_ACTION The GitHub event action: "closed", "labeled", or +# "reconcile". # EVENT_LABEL For 'labeled' events, the name of the label that was added. -# Empty or unset for 'closed' events. +# Not needed for processing; labels are reconciled from LABELS. # PR_NUMBER The pull request number (used to derive cherry-pick branch names). # GH_TOKEN GitHub token for API calls (gh CLI auth). # GITHUB_REPOSITORY Owner/repo (e.g. "dotnet/SqlClient"). Set automatically by Actions. @@ -71,46 +86,67 @@ fi : "${PR_NUMBER:?PR_NUMBER environment variable is required}" : "${GITHUB_REPOSITORY:?GITHUB_REPOSITORY environment variable is required}" -# -- 'labeled' event: process only the newly added label ---------------------- -if [[ "${EVENT_ACTION}" == "labeled" ]]; then - # Extract version from the new label. If it doesn't match "Hotfix X.Y.Z", - # this is a non-hotfix label — emit empty matrix and exit cleanly. - if [[ "${EVENT_LABEL:-}" =~ ^Hotfix\ ([0-9]+\.[0-9]+\.[0-9]+)$ ]]; then - CANDIDATE="${BASH_REMATCH[1]}" - else - CANDIDATE="" +# -- Shared helper: has a cherry-pick for VERSION already been created? ------ +# Used by both the 'labeled' and 'reconcile' paths below. +# +# NOTE: We use the GitHub API rather than 'git ls-remote' because the +# detect-versions job does not check out the repository (no .git directory). +cherry_pick_already_exists() { + local version="$1" + local branch="dev/automation/pr-${PR_NUMBER}-to-${version}" + + if gh api "repos/${GITHUB_REPOSITORY}/git/ref/heads/${branch}" --silent 2>/dev/null; then + echo "Cherry-pick branch '${branch}' already exists. Skipping." + return 0 fi - if [[ -z "${CANDIDATE}" ]]; then - echo "Label '${EVENT_LABEL:-}' is not a valid 'Hotfix X.Y.Z' label. Skipping." - echo "versions=[]" >> "${GITHUB_OUTPUT}" - exit 0 + local existing_pr + existing_pr=$(gh pr list --repo "${GITHUB_REPOSITORY}" --head "${branch}" --state all \ + --json number --jq 'length') + if [[ "${existing_pr}" -gt 0 ]]; then + echo "A cherry-pick PR from '${branch}' already exists. Skipping." + return 0 fi - # Guard against duplicate cherry-picks. If the cherry-pick branch already - # exists on the remote, or a PR (open, closed, or merged) was already created - # from it, there is nothing left to do. - # - # NOTE: We use the GitHub API rather than 'git ls-remote' because the - # detect-versions job does not check out the repository (no .git directory). - CHERRY_PICK_BRANCH="dev/automation/pr-${PR_NUMBER}-to-${CANDIDATE}" + return 1 +} - if gh api "repos/${GITHUB_REPOSITORY}/git/ref/heads/${CHERRY_PICK_BRANCH}" \ - --silent 2>/dev/null; then - echo "Cherry-pick branch '${CHERRY_PICK_BRANCH}' already exists. Skipping." - echo "versions=[]" >> "${GITHUB_OUTPUT}" - exit 0 - fi +if [[ "${EVENT_ACTION}" == "labeled" || "${EVENT_ACTION}" == "reconcile" ]]; then + # -- 'labeled'/'reconcile' event: process all current Hotfix labels, but + # still skip any version that's already been cherry-picked. A label event + # carries the complete PR label snapshot, so this also safely coalesces + # pending runs in the workflow's concurrency group. + ALL_VERSIONS=$(echo "${LABELS}" | tr ',' '\n' \ + | sed -nE 's/^Hotfix ([0-9]+\.[0-9]+\.[0-9]+)$/\1/p') - EXISTING_PR=$(gh pr list --repo "${GITHUB_REPOSITORY}" --head "${CHERRY_PICK_BRANCH}" --state all \ - --json number --jq 'length') - if [[ "${EXISTING_PR}" -gt 0 ]]; then - echo "A cherry-pick PR from '${CHERRY_PICK_BRANCH}' already exists. Skipping." - echo "versions=[]" >> "${GITHUB_OUTPUT}" - exit 0 - fi + # No valid "Hotfix X.Y.Z" label at all is the same caller error as the + # 'closed' event hitting the check below — fall through to it. + if [[ -n "${ALL_VERSIONS}" ]]; then + VERSIONS="" + while IFS= read -r candidate; do + [[ -z "${candidate}" ]] && continue + if cherry_pick_already_exists "${candidate}"; then + continue + fi + VERSIONS+="${candidate}"$'\n' + done <<< "${ALL_VERSIONS}" + VERSIONS="${VERSIONS%$'\n'}" - VERSIONS="${CANDIDATE}" + # Every valid label already had a cherry-pick (all duplicates): this is a + # legitimate no-op, unlike "no valid label found" below, so exit early + # rather than falling into the shared error check. + if [[ -z "${VERSIONS}" ]]; then + echo "versions=[]" >> "${GITHUB_OUTPUT}" + exit 0 + fi + else + VERSIONS="" + if [[ "${EVENT_ACTION}" == "labeled" ]]; then + echo "No valid 'Hotfix X.Y.Z' labels remain on the PR. Skipping." + echo "versions=[]" >> "${GITHUB_OUTPUT}" + exit 0 + fi + fi else # -- 'closed' event: process all hotfix labels on the PR -------------------- # Split by comma, keep only labels matching "Hotfix X.Y.Z", extract the version. diff --git a/.github/scripts/resolve-hotfix-dispatch-context.sh b/.github/scripts/resolve-hotfix-dispatch-context.sh new file mode 100644 index 0000000000..8e04954cf3 --- /dev/null +++ b/.github/scripts/resolve-hotfix-dispatch-context.sh @@ -0,0 +1,29 @@ +#!/usr/bin/env bash +################################################################################# +# Licensed to the .NET Foundation under one or more agreements. # +# The .NET Foundation licenses this file to you under the MIT license. # +# See the LICENSE file in the project root for more information. # +################################################################################# +# +# Resolves the pull request context for a cherry-pick workflow_dispatch run. +# +################################################################################# + +set -euo pipefail + +: "${PR_NUMBER:?PR_NUMBER is required}" +: "${GITHUB_REPOSITORY:?GITHUB_REPOSITORY is required}" +: "${GITHUB_OUTPUT:?GITHUB_OUTPUT is required}" + +gh pr view "${PR_NUMBER}" --repo "${GITHUB_REPOSITORY}" \ + --json number,state,baseRefName,labels,mergeCommit,title \ + --jq ' + "pr_number=\(.number)", + "event_action=reconcile", + "event_label=", + "merged=\(.state == "MERGED")", + "base_ref=\(.baseRefName)", + "labels=\([.labels[].name] | join(","))", + "merge_commit_sha=\(.mergeCommit.oid // "")", + "pr_title=\(.title)" + ' >> "${GITHUB_OUTPUT}" diff --git a/.github/scripts/sync-hotfix-label-from-issue.sh b/.github/scripts/sync-hotfix-label-from-issue.sh new file mode 100755 index 0000000000..ed1c1bed9e --- /dev/null +++ b/.github/scripts/sync-hotfix-label-from-issue.sh @@ -0,0 +1,135 @@ +#!/usr/bin/env bash +################################################################################# +# Licensed to the .NET Foundation under one or more agreements. # +# The .NET Foundation licenses this file to you under the MIT license. # +# See the LICENSE file in the project root for more information. # +################################################################################# +# +# sync-hotfix-label-from-issue.sh +# +# Companion to sync-hotfix-label-to-pr.sh, covering the timing gap it misses: +# sync-hotfix-label-to-pr.sh only runs on PR events (opened/reopened/edited/ +# synchronize), so if an issue is labeled "Hotfix X.Y.Z" *after* its closing +# PR is already open, and that PR never receives another qualifying event, +# the label never gets copied over and cherry-pick-hotfix.yml never fires on +# merge. This script runs the sync from the other direction: given an issue +# that was just labeled, find the PR(s) that will close/have closed it and +# re-run sync-hotfix-label-to-pr.sh for each. +# +# OVERVIEW +# -------- +# 1. Ask the GitHub API which pull request(s) will close (or have already +# closed) this issue (via the 'closedByPullRequestsReferences' +# connection), including both OPEN and MERGED PRs. A merged PR is +# included because the issue may not get labeled until after its fixing +# PR has already merged (e.g. #4737/#4738): at that point there's no +# later PR event left to pick up the label naturally. +# +# 2. For each such PR, invoke sync-hotfix-label-to-pr.sh with PR_NUMBER set, +# which does the actual label-copying work. +# +# 3. For any PR that is already MERGED, also dispatch cherry-pick-hotfix.yml +# directly (workflow_dispatch, "reconcile" mode — see +# extract-hotfix-versions.sh). Adding a label via 'gh pr edit' uses this +# workflow's own GITHUB_TOKEN, and GitHub does not trigger further +# workflow runs (including cherry-pick-hotfix.yml's own 'labeled' +# trigger) for events caused by the repository's own GITHUB_TOKEN, so +# without this explicit dispatch the cherry-pick would silently never +# run for a retroactively-labeled, already-merged PR. +# +# This is idempotent and safe to re-run on every issue 'labeled' event: a PR +# that already has the label is left alone (handled by the delegated script), +# a duplicate workflow_dispatch is a no-op (extract-hotfix-versions.sh's +# "reconcile" mode skips versions that already have a cherry-pick branch/PR), +# and an issue with no closing PR is a silent no-op. +# +# REQUIRED ENVIRONMENT VARIABLES +# ------------------------------ +# ISSUE_NUMBER The issue number that was just labeled. +# GH_TOKEN GitHub token for 'gh' CLI authentication. +# GITHUB_REPOSITORY Owner/repo (e.g. "dotnet/SqlClient"). Set by Actions. +# +# OUTPUTS +# ------- +# Adds zero or more "Hotfix X.Y.Z" labels to pull request(s) that close (or +# closed) this issue, and dispatches cherry-pick-hotfix.yml for any of them +# that are already merged. +# +# USAGE +# Called from the sync-hotfix-label-to-pr.yml workflow. Can also be run +# locally: +# +# export ISSUE_NUMBER=4715 +# export GH_TOKEN="ghp_..." +# export GITHUB_REPOSITORY="dotnet/SqlClient" +# bash .github/scripts/sync-hotfix-label-from-issue.sh +# +################################################################################# +set -euo pipefail + +# -- Runtime help ------------------------------------------------------------- +if [[ "${1:-}" == "--help" || "${1:-}" == "-h" ]]; then + # Print the header comment block (between the license banner and the + # closing banner), stripping the leading '# ' prefix. + awk '/^#{2,}$/ { n++; next } n == 2 { sub(/^# ?/, ""); print }' "$0" + exit 0 +fi + +# -- Input validation --------------------------------------------------------- +: "${ISSUE_NUMBER:?ISSUE_NUMBER environment variable is required}" +: "${GITHUB_REPOSITORY:?GITHUB_REPOSITORY environment variable is required}" + +echo "Issue: #${ISSUE_NUMBER}" + +REPO_OWNER="${GITHUB_REPOSITORY%%/*}" +REPO_NAME="${GITHUB_REPOSITORY#*/}" + +# -- Step 1: Find PR(s) that will close (or have closed) this issue ----------- +# 'closedByPullRequestsReferences' is the reverse of 'closingIssuesReferences' +# on a PR: it lists the PR(s) whose closing keywords reference this issue. +# Unlike closingIssuesReferences on a *release-branch* PR, this is reliable +# here because the referencing PR (the one fixing the original issue) always +# targets the default branch. +# +# Both OPEN and MERGED PRs are considered: a CLOSED-but-not-merged PR (e.g. +# abandoned) is intentionally excluded, since there's nothing to cherry-pick. +CLOSING_PRS=$(gh api graphql \ + -f query=' + query($owner: String!, $repo: String!, $issueNumber: Int!) { + repository(owner: $owner, name: $repo) { + issue(number: $issueNumber) { + closedByPullRequestsReferences(first: 50) { + nodes { number state repository { nameWithOwner } } + } + } + } + }' \ + -F owner="${REPO_OWNER}" \ + -F repo="${REPO_NAME}" \ + -F issueNumber="${ISSUE_NUMBER}" \ + | jq -r --arg repository "${GITHUB_REPOSITORY}" \ + '.data.repository.issue.closedByPullRequestsReferences.nodes[] | select(.repository.nameWithOwner == $repository) | select(.state == "OPEN" or .state == "MERGED") | "\(.number) \(.state)"') + +if [[ -z "${CLOSING_PRS}" ]]; then + echo "No open or merged pull requests found that close #${ISSUE_NUMBER}. Nothing to sync." + exit 0 +fi + +echo "Pull requests referencing #${ISSUE_NUMBER}:" +echo "${CLOSING_PRS}" + +# -- Step 2: Re-run the PR-side sync for each referencing PR ------------------ +# For any PR that's already merged, also explicitly dispatch +# cherry-pick-hotfix.yml (see OVERVIEW above for why this is necessary). +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" + +while IFS=' ' read -r pr_number pr_state; do + [[ -z "${pr_number}" ]] && continue + echo "Syncing Hotfix labels onto PR #${pr_number} (closes #${ISSUE_NUMBER})." + PR_NUMBER="${pr_number}" bash "${SCRIPT_DIR}/sync-hotfix-label-to-pr.sh" + + if [[ "${pr_state}" == "MERGED" ]]; then + echo "PR #${pr_number} is already merged; dispatching cherry-pick-hotfix.yml to reconcile its Hotfix labels." + gh workflow run cherry-pick-hotfix.yml --repo "${GITHUB_REPOSITORY}" -f "pr_number=${pr_number}" + fi +done <<< "${CLOSING_PRS}" diff --git a/.github/scripts/sync-hotfix-label-to-pr.sh b/.github/scripts/sync-hotfix-label-to-pr.sh new file mode 100755 index 0000000000..b7e02b5c80 --- /dev/null +++ b/.github/scripts/sync-hotfix-label-to-pr.sh @@ -0,0 +1,137 @@ +#!/usr/bin/env bash +################################################################################# +# Licensed to the .NET Foundation under one or more agreements. # +# The .NET Foundation licenses this file to you under the MIT license. # +# See the LICENSE file in the project root for more information. # +################################################################################# +# +# sync-hotfix-label-to-pr.sh +# +# Copies "Hotfix X.Y.Z" labels from an issue onto any pull request that will +# close it, so the existing cherry-pick-hotfix.yml automation (which reacts to +# "Hotfix X.Y.Z" labels on merged PRs) fires without the label having to be +# applied to the PR by hand. +# +# OVERVIEW +# -------- +# 1. Ask the GitHub API which issues this PR's closing keywords (Fixes, +# Closes, Resolves, etc.) will close when it's merged. +# +# 2. For each such issue, collect any "Hotfix X.Y.Z" labels it carries. +# +# 3. Add any of those labels to the PR that it doesn't already have. +# +# This is idempotent and safe to re-run on every 'opened'/'edited'/'reopened'/ +# 'synchronize' event: labels already present are left alone, and a PR with no +# closing references or no Hotfix-labeled referenced issues is a silent no-op. +# +# REQUIRED ENVIRONMENT VARIABLES +# ------------------------------ +# PR_NUMBER The pull request number. +# GH_TOKEN GitHub token for 'gh' CLI authentication. +# GITHUB_REPOSITORY Owner/repo (e.g. "dotnet/SqlClient"). Set by Actions. +# +# OUTPUTS +# ------- +# Adds zero or more "Hotfix X.Y.Z" labels to the pull request. +# +# USAGE +# Called from the sync-hotfix-label-to-pr.yml workflow. Can also be run +# locally: +# +# export PR_NUMBER=4750 +# export GH_TOKEN="ghp_..." +# export GITHUB_REPOSITORY="dotnet/SqlClient" +# bash .github/scripts/sync-hotfix-label-to-pr.sh +# +################################################################################# +set -euo pipefail + +# -- Runtime help ------------------------------------------------------------- +if [[ "${1:-}" == "--help" || "${1:-}" == "-h" ]]; then + # Print the header comment block (between the license banner and the + # closing banner), stripping the leading '# ' prefix. + awk '/^#{2,}$/ { n++; next } n == 2 { sub(/^# ?/, ""); print }' "$0" + exit 0 +fi + +# -- Input validation --------------------------------------------------------- +: "${PR_NUMBER:?PR_NUMBER environment variable is required}" +: "${GITHUB_REPOSITORY:?GITHUB_REPOSITORY environment variable is required}" + +echo "Pull request: #${PR_NUMBER}" + +# -- Step 1: Find issues this PR will close ----------------------------------- +# closingIssuesReferences can include issues from other repositories (e.g. +# "Fixes owner/other#123"). Only consider references in this repository — a +# bare '.number' would otherwise let a cross-repo reference collide with an +# unrelated local issue of the same number and copy its label. 'gh ... --jq' +# takes a single query string (no jq '--arg' passthrough), so the repo is +# escaped and interpolated directly. +REPO_ESCAPED=$(printf '%s' "${GITHUB_REPOSITORY}" | sed 's/["\\]/\\&/g') + +CLOSING_ISSUES=$(gh pr view "${PR_NUMBER}" --repo "${GITHUB_REPOSITORY}" \ + --json closingIssuesReferences \ + --jq ".closingIssuesReferences[] | select((.repository.owner.login + \"/\" + .repository.name) == \"${REPO_ESCAPED}\") | .number") + +if [[ -z "${CLOSING_ISSUES}" ]]; then + echo "No closing issue references found on #${PR_NUMBER}. Nothing to sync." + exit 0 +fi + +echo "Closing issue references: ${CLOSING_ISSUES}" + +# -- Step 2: Collect "Hotfix X.Y.Z" labels from each referenced issue --------- +# Match the exact "Hotfix X.Y.Z" grammar (same regex used by +# create-backport-issue.sh / cherry-pick-to-release.sh's version extraction), +# not merely a "Hotfix " prefix — otherwise a label like "Hotfix Candidate" +# would be copied to the PR even though it's rejected everywhere downstream. +HOTFIX_LABELS="" +while IFS= read -r issue_number; do + [[ -z "${issue_number}" ]] && continue + + # Capture 'gh issue view' separately from the 'grep' filter below: a real + # API/permission failure here must not be swallowed and mistaken for "no + # Hotfix labels on this issue" (which would silently skip labeling the PR). + # Only grep's no-match exit status (when an issue has no Hotfix label at + # all) should be tolerated via '|| true'. + if ! all_labels=$(gh issue view "${issue_number}" --repo "${GITHUB_REPOSITORY}" \ + --json labels --jq '.labels[].name'); then + echo "::error::Failed to look up labels for issue #${issue_number}." >&2 + exit 1 + fi + issue_labels=$(grep -E '^Hotfix [0-9]+\.[0-9]+\.[0-9]+$' <<< "${all_labels}" || true) + + while IFS= read -r label; do + [[ -z "${label}" ]] && continue + if ! grep -qxF "${label}" <<< "${HOTFIX_LABELS}"; then + HOTFIX_LABELS+="${label}"$'\n' + fi + done <<< "${issue_labels}" +done <<< "${CLOSING_ISSUES}" + +if [[ -z "${HOTFIX_LABELS}" ]]; then + echo "No 'Hotfix X.Y.Z' labels found on referenced issues. Nothing to sync." + exit 0 +fi + +# -- Step 3: Add any missing labels to the PR --------------------------------- +EXISTING_PR_LABELS=$(gh pr view "${PR_NUMBER}" --repo "${GITHUB_REPOSITORY}" \ + --json labels --jq '.labels[].name') + +ADDED_ANY=0 +while IFS= read -r label; do + [[ -z "${label}" ]] && continue + if grep -qxF "${label}" <<< "${EXISTING_PR_LABELS}"; then + echo "PR #${PR_NUMBER} already has label '${label}'. Skipping." + continue + fi + + echo "Adding label '${label}' to #${PR_NUMBER} (from issue Hotfix label)." + gh pr edit "${PR_NUMBER}" --repo "${GITHUB_REPOSITORY}" --add-label "${label}" + ADDED_ANY=1 +done <<< "${HOTFIX_LABELS}" + +if [[ "${ADDED_ANY}" -eq 0 ]]; then + echo "All Hotfix labels from referenced issues are already present on #${PR_NUMBER}." +fi diff --git a/.github/scripts/tests/README.md b/.github/scripts/tests/README.md index 2fe2592701..9720aac79c 100644 --- a/.github/scripts/tests/README.md +++ b/.github/scripts/tests/README.md @@ -2,6 +2,9 @@ This directory contains tests for the shell scripts used by the [cherry-pick-hotfix](./../../../.github/workflows/cherry-pick-hotfix.yml), +[hotfix-label-issue](./../../../.github/workflows/hotfix-label-issue.yml), +[sync-hotfix-label-to-pr](./../../../.github/workflows/sync-hotfix-label-to-pr.yml), +[close-backport-issue](./../../../.github/workflows/close-backport-issue.yml), [check-milestone](./../../../.github/workflows/check-milestone.yml) and [recheck-milestones](./../../../.github/workflows/recheck-milestones.yml) GitHub Actions workflows. These tests are intended to be run manually by developers when they are changing the associated @@ -90,6 +93,10 @@ bats .github/scripts/tests/cherry-pick-to-release.bats bats .github/scripts/tests/check-milestone-branch.bats bats .github/scripts/tests/check-milestone-version.bats bats .github/scripts/tests/recheck-milestones-for-release-branch.bats +bats .github/scripts/tests/create-backport-issue.bats +bats .github/scripts/tests/sync-hotfix-label-to-pr.bats +bats .github/scripts/tests/sync-hotfix-label-from-issue.bats +bats .github/scripts/tests/close-backport-issue.bats ``` ### Run a specific test by name @@ -120,6 +127,10 @@ bats --formatter pretty .github/scripts/tests/ | `check-milestone-branch.bats` | Tests milestone validation against the pull request target branch. | | `check-milestone-version.bats` | Tests milestone validation against the canonical SqlClient version. | | `recheck-milestones-for-release-branch.bats` | Tests milestone rechecks when a release branch is created. | +| `create-backport-issue.bats` | Tests Hotfix label validation, duplicate backport-issue detection, milestone lookup, child issue creation, and native sub-issue linking. | +| `sync-hotfix-label-to-pr.bats` | Tests collecting Hotfix labels from a PR's closing issues and idempotently syncing them onto the PR. | +| `sync-hotfix-label-from-issue.bats` | Tests finding PRs that close a labeled issue, syncing labels, and dispatching reconciliation for already-merged PRs. | +| `close-backport-issue.bats` | Tests closing open backport issues referenced by a merged release-branch PR. | ## How the Tests Work diff --git a/.github/scripts/tests/cherry-pick-to-release.bats b/.github/scripts/tests/cherry-pick-to-release.bats index 3484b48ea9..11a60dfdb0 100644 --- a/.github/scripts/tests/cherry-pick-to-release.bats +++ b/.github/scripts/tests/cherry-pick-to-release.bats @@ -26,6 +26,14 @@ setup() { STUB_DIR="$(mktemp -d)" export PATH="${STUB_DIR}:${PATH}" + # Stub 'sleep' as a no-op so the backport-issue retry loop's delay (see + # lookup_backport_issue) doesn't slow down tests that exercise it. + cat > "${STUB_DIR}/sleep" <<'STUB' +#!/usr/bin/env bash +exit 0 +STUB + chmod +x "${STUB_DIR}/sleep" + # Defaults — individual tests override as needed. export VERSION="7.0.1" export MERGE_COMMIT_SHA="abc123def456" @@ -297,6 +305,287 @@ STUB grep -q "GIT: commit --allow-empty" "${STUB_DIR}/git.log" } +# ── Backport issue lookup ──────────────────────────────────────────────────── + +@test "appends Fixes line when a backport issue is found" { + write_git_mock ' + if [[ "$1" == "fetch" ]]; then exit 0; fi + if [[ "$1" == "cherry" ]]; then echo "+ abc123"; exit 0; fi + if [[ "$1" == "checkout" ]]; then exit 0; fi + if [[ "$1" == "rev-list" ]]; then echo "abc123def456 parent1"; exit 0; fi + if [[ "$1" == "cherry-pick" ]]; then exit 0; fi + if [[ "$1" == "push" ]]; then exit 0; fi + exit 0 + ' + write_gh_mock ' + if [[ "$1" == "api" && "$2" == repos/*/milestones ]]; then echo "7.0.1"; exit 0; fi + if [[ "$1" == "pr" && "$2" == "view" ]]; then echo "4714"; exit 0; fi + if [[ "$1" == "api" && "$2" == repos/*/issues/*/sub_issues ]]; then echo "4900"; exit 0; fi + if [[ "$1" == "pr" && "$2" == "create" ]]; then + while [[ $# -gt 0 ]]; do + if [[ "$1" == "--body" ]]; then + printf "%s" "$2" > "'"${STUB_DIR}"'/pr-body.txt" + break + fi + shift + done + exit 0 + fi + exit 0 + ' + + run bash "${SCRIPT}" + [ "$status" -eq 0 ] + [[ "$output" == *"Found backport issue #4900"* ]] + [ -f "${STUB_DIR}/pr-body.txt" ] + [[ "$(cat "${STUB_DIR}/pr-body.txt")" == *"Fixes #4900"* ]] + [[ "$(cat "${STUB_DIR}/pr-body.txt")" == *""* ]] +} + +@test "appends Fixes lines for every closing issue with a matching backport issue" { + write_git_mock ' + if [[ "$1" == "fetch" ]]; then exit 0; fi + if [[ "$1" == "cherry" ]]; then echo "+ abc123"; exit 0; fi + if [[ "$1" == "checkout" ]]; then exit 0; fi + if [[ "$1" == "rev-list" ]]; then echo "abc123def456 parent1"; exit 0; fi + if [[ "$1" == "cherry-pick" ]]; then exit 0; fi + if [[ "$1" == "push" ]]; then exit 0; fi + exit 0 + ' + write_gh_mock ' + if [[ "$1" == "api" && "$2" == repos/*/milestones ]]; then echo "7.0.1"; exit 0; fi + if [[ "$1" == "pr" && "$2" == "view" ]]; then printf "4714\n4715\n"; exit 0; fi + if [[ "$1" == "api" && "$2" == repos/*/issues/4714/sub_issues ]]; then echo "4900"; exit 0; fi + if [[ "$1" == "api" && "$2" == repos/*/issues/4715/sub_issues ]]; then echo "4901"; exit 0; fi + if [[ "$1" == "pr" && "$2" == "create" ]]; then + while [[ $# -gt 0 ]]; do + if [[ "$1" == "--body" ]]; then + printf "%s" "$2" > "'"${STUB_DIR}"'/pr-body.txt" + break + fi + shift + done + exit 0 + fi + exit 0 + ' + + run bash "${SCRIPT}" + [ "$status" -eq 0 ] + [[ "$output" == *"Found backport issue #4900"* ]] + [[ "$output" == *"Found backport issue #4901"* ]] + [ -f "${STUB_DIR}/pr-body.txt" ] + [[ "$(cat "${STUB_DIR}/pr-body.txt")" == *"Fixes #4900"* ]] + [[ "$(cat "${STUB_DIR}/pr-body.txt")" == *"Fixes #4901"* ]] + [[ "$(cat "${STUB_DIR}/pr-body.txt")" == *""* ]] +} + +@test "picks the sub-issue with the [VERSION] title prefix, not just any milestone match" { + # The parent issue has two sub-issues milestoned 7.0.1: an unrelated + # follow-up task (created independently of this automation) and the real + # backport issue created by create-backport-issue.sh, which is always + # titled "[VERSION] ". Matching on milestone alone would + # nondeterministically pick either one; the title prefix must disambiguate. + write_git_mock ' + if [[ "$1" == "fetch" ]]; then exit 0; fi + if [[ "$1" == "cherry" ]]; then echo "+ abc123"; exit 0; fi + if [[ "$1" == "checkout" ]]; then exit 0; fi + if [[ "$1" == "rev-list" ]]; then echo "abc123def456 parent1"; exit 0; fi + if [[ "$1" == "cherry-pick" ]]; then exit 0; fi + if [[ "$1" == "push" ]]; then exit 0; fi + exit 0 + ' + write_gh_mock ' + if [[ "$1" == "api" && "$2" == repos/*/milestones ]]; then echo "7.0.1"; exit 0; fi + if [[ "$1" == "pr" && "$2" == "view" ]]; then echo "4714"; exit 0; fi + if [[ "$1" == "api" && "$2" == repos/*/issues/4714/sub_issues ]]; then + jq_expr="" + args=("$@") + for ((i = 0; i < ${#args[@]}; i++)); do + if [[ "${args[$i]}" == "--jq" ]]; then + jq_expr="${args[$((i + 1))]}" + fi + done + printf "%s" "[{\"number\":4899,\"title\":\"Unrelated follow-up task\",\"milestone\":{\"title\":\"7.0.1\"}},{\"number\":4900,\"title\":\"[7.0.1] Fix connection timeout\",\"milestone\":{\"title\":\"7.0.1\"}}]" | jq -r "${jq_expr}" + exit 0 + fi + if [[ "$1" == "pr" && "$2" == "create" ]]; then + while [[ $# -gt 0 ]]; do + if [[ "$1" == "--body" ]]; then + printf "%s" "$2" > "'"${STUB_DIR}"'/pr-body.txt" + break + fi + shift + done + exit 0 + fi + exit 0 + ' + + run bash "${SCRIPT}" + [ "$status" -eq 0 ] + [[ "$output" == *"Found backport issue #4900"* ]] + [ -f "${STUB_DIR}/pr-body.txt" ] + [[ "$(cat "${STUB_DIR}/pr-body.txt")" == *"Fixes #4900"* ]] + [[ "$(cat "${STUB_DIR}/pr-body.txt")" != *"Fixes #4899"* ]] + [[ "$(cat "${STUB_DIR}/pr-body.txt")" == *""* ]] + [[ "$(cat "${STUB_DIR}/pr-body.txt")" != *"4899 -->"* ]] +} + +@test "omits Fixes line when the PR has no closing issue references" { + write_git_mock ' + if [[ "$1" == "fetch" ]]; then exit 0; fi + if [[ "$1" == "cherry" ]]; then echo "+ abc123"; exit 0; fi + if [[ "$1" == "checkout" ]]; then exit 0; fi + if [[ "$1" == "rev-list" ]]; then echo "abc123def456 parent1"; exit 0; fi + if [[ "$1" == "cherry-pick" ]]; then exit 0; fi + if [[ "$1" == "push" ]]; then exit 0; fi + exit 0 + ' + write_gh_mock ' + if [[ "$1" == "api" && "$2" == repos/*/milestones ]]; then echo "7.0.1"; exit 0; fi + if [[ "$1" == "pr" && "$2" == "view" ]]; then exit 0; fi + if [[ "$1" == "pr" && "$2" == "create" ]]; then + while [[ $# -gt 0 ]]; do + if [[ "$1" == "--body" ]]; then + printf "%s" "$2" > "'"${STUB_DIR}"'/pr-body.txt" + break + fi + shift + done + exit 0 + fi + exit 0 + ' + + run bash "${SCRIPT}" + [ "$status" -eq 0 ] + [ -f "${STUB_DIR}/pr-body.txt" ] + [[ "$(cat "${STUB_DIR}/pr-body.txt")" != *"Fixes #"* ]] + [[ "$(cat "${STUB_DIR}/pr-body.txt")" != *"backport-issue-numbers"* ]] +} + +@test "omits Fixes line when no sub-issue matches the version" { + write_git_mock ' + if [[ "$1" == "fetch" ]]; then exit 0; fi + if [[ "$1" == "cherry" ]]; then echo "+ abc123"; exit 0; fi + if [[ "$1" == "checkout" ]]; then exit 0; fi + if [[ "$1" == "rev-list" ]]; then echo "abc123def456 parent1"; exit 0; fi + if [[ "$1" == "cherry-pick" ]]; then exit 0; fi + if [[ "$1" == "push" ]]; then exit 0; fi + exit 0 + ' + write_gh_mock ' + if [[ "$1" == "api" && "$2" == repos/*/milestones ]]; then echo "7.0.1"; exit 0; fi + if [[ "$1" == "pr" && "$2" == "view" ]]; then echo "4714"; exit 0; fi + if [[ "$1" == "api" && "$2" == repos/*/issues/*/sub_issues ]]; then exit 0; fi + if [[ "$1" == "pr" && "$2" == "create" ]]; then + while [[ $# -gt 0 ]]; do + if [[ "$1" == "--body" ]]; then + printf "%s" "$2" > "'"${STUB_DIR}"'/pr-body.txt" + break + fi + shift + done + exit 0 + fi + exit 0 + ' + + run bash "${SCRIPT}" + [ "$status" -eq 0 ] + [ -f "${STUB_DIR}/pr-body.txt" ] + [[ "$(cat "${STUB_DIR}/pr-body.txt")" != *"Fixes #"* ]] + [[ "$(cat "${STUB_DIR}/pr-body.txt")" != *"backport-issue-numbers"* ]] +} + +@test "retries sub-issue lookup when the parent issue still carries the Hotfix label" { + # Simulates the race between create-backport-issue.sh (creating the + # backport sub-issue) and this script (looking it up), both triggered by + # the same "Hotfix " label event: the sub-issue doesn't exist on + # the first lookup, but does by the second. + local call_count_file="${STUB_DIR}/sub_issues_calls" + echo 0 > "${call_count_file}" + + write_git_mock ' + if [[ "$1" == "fetch" ]]; then exit 0; fi + if [[ "$1" == "cherry" ]]; then echo "+ abc123"; exit 0; fi + if [[ "$1" == "checkout" ]]; then exit 0; fi + if [[ "$1" == "rev-list" ]]; then echo "abc123def456 parent1"; exit 0; fi + if [[ "$1" == "cherry-pick" ]]; then exit 0; fi + if [[ "$1" == "push" ]]; then exit 0; fi + exit 0 + ' + write_gh_mock ' + if [[ "$1" == "api" && "$2" == repos/*/milestones ]]; then echo "7.0.1"; exit 0; fi + if [[ "$1" == "pr" && "$2" == "view" ]]; then echo "4714"; exit 0; fi + if [[ "$1" == "api" && "$2" == repos/*/issues/*/sub_issues ]]; then + n=$(< "'"${call_count_file}"'") + n=$((n + 1)) + echo "$n" > "'"${call_count_file}"'" + if [[ "$n" -ge 2 ]]; then echo "4900"; fi + exit 0 + fi + if [[ "$1" == "api" && "$2" == repos/*/issues/4714 ]]; then echo "Hotfix 7.0.1"; exit 0; fi + if [[ "$1" == "pr" && "$2" == "create" ]]; then + while [[ $# -gt 0 ]]; do + if [[ "$1" == "--body" ]]; then + printf "%s" "$2" > "'"${STUB_DIR}"'/pr-body.txt" + break + fi + shift + done + exit 0 + fi + exit 0 + ' + + run bash "${SCRIPT}" + [ "$status" -eq 0 ] + [[ "$output" == *"retrying"* ]] + [[ "$output" == *"Found backport issue #4900"* ]] + [[ "$(cat "${STUB_DIR}/pr-body.txt")" == *"Fixes #4900"* ]] + [[ "$(cat "${STUB_DIR}/pr-body.txt")" == *""* ]] +} + +@test "gives up after exhausting retries when the backport issue never appears" { + # The Hotfix label is present (so retries are attempted) but the backport + # sub-issue never shows up — e.g. create-backport-issue.sh failed. The + # script must still finish cleanly without a Fixes line, not hang or fail. + write_git_mock ' + if [[ "$1" == "fetch" ]]; then exit 0; fi + if [[ "$1" == "cherry" ]]; then echo "+ abc123"; exit 0; fi + if [[ "$1" == "checkout" ]]; then exit 0; fi + if [[ "$1" == "rev-list" ]]; then echo "abc123def456 parent1"; exit 0; fi + if [[ "$1" == "cherry-pick" ]]; then exit 0; fi + if [[ "$1" == "push" ]]; then exit 0; fi + exit 0 + ' + write_gh_mock ' + if [[ "$1" == "api" && "$2" == repos/*/milestones ]]; then echo "7.0.1"; exit 0; fi + if [[ "$1" == "pr" && "$2" == "view" ]]; then echo "4714"; exit 0; fi + if [[ "$1" == "api" && "$2" == repos/*/issues/*/sub_issues ]]; then exit 0; fi + if [[ "$1" == "api" && "$2" == repos/*/issues/4714 ]]; then echo "Hotfix 7.0.1"; exit 0; fi + if [[ "$1" == "pr" && "$2" == "create" ]]; then + while [[ $# -gt 0 ]]; do + if [[ "$1" == "--body" ]]; then + printf "%s" "$2" > "'"${STUB_DIR}"'/pr-body.txt" + break + fi + shift + done + exit 0 + fi + exit 0 + ' + + run bash "${SCRIPT}" + [ "$status" -eq 0 ] + [ -f "${STUB_DIR}/pr-body.txt" ] + [[ "$(cat "${STUB_DIR}/pr-body.txt")" != *"Fixes #"* ]] + [[ "$(cat "${STUB_DIR}/pr-body.txt")" != *"backport-issue-numbers"* ]] +} + @test "conflict PR body contains real newlines, not literal backslash-n" { write_git_mock ' if [[ "$1" == "fetch" ]]; then exit 0; fi diff --git a/.github/scripts/tests/close-backport-issue.bats b/.github/scripts/tests/close-backport-issue.bats new file mode 100644 index 0000000000..57d18277e5 --- /dev/null +++ b/.github/scripts/tests/close-backport-issue.bats @@ -0,0 +1,175 @@ +#!/usr/bin/env bats +################################################################################# +# Licensed to the .NET Foundation under one or more agreements. # +# The .NET Foundation licenses this file to you under the MIT license. # +# See the LICENSE file in the project root for more information. # +################################################################################# +# +# Tests for close-backport-issue.sh +# +# Run with: bats .github/scripts/tests/close-backport-issue.bats +# +# Dependencies: bats-core (https://github.com/bats-core/bats-core) +# +################################################################################# + +SCRIPT=".github/scripts/close-backport-issue.sh" + +setup() { + export PR_NUMBER="4750" + export GH_TOKEN="fake-token" + export GITHUB_REPOSITORY="dotnet/SqlClient" + + STUB_DIR="$(mktemp -d)" + export PATH="${STUB_DIR}:${PATH}" +} + +teardown() { + rm -rf "${STUB_DIR}" +} + +# Writes a 'gh' stub that dispatches based on argv. +# +# $1: the merged PR's body (from 'pr view --json body'), possibly +# containing a "" marker +# $2: newline-separated "issue_number:STATE" pairs (STATE is OPEN or CLOSED) +stub_gh() { + local pr_body="$1" + local issue_state_map="$2" + + printf '%s' "${pr_body}" > "${STUB_DIR}/pr_body.txt" + printf '%s' "${issue_state_map}" > "${STUB_DIR}/issue_states.txt" + : > "${STUB_DIR}/close_calls.log" + + cat > "${STUB_DIR}/gh" < --json body --jq '.body' +if [[ "\$1" == "pr" && "\$2" == "view" && "\${*}" == *"--json body"* ]]; then + cat "${STUB_DIR}/pr_body.txt" + exit 0 +fi + +# gh issue view --json state --jq '.state' +if [[ "\$1" == "issue" && "\$2" == "view" ]]; then + issue_number="\$3" + awk -F':' -v n="\${issue_number}" '\$1 == n { print \$2 }' "${STUB_DIR}/issue_states.txt" + exit 0 +fi + +# gh issue close --repo --reason completed --comment "..." +if [[ "\$1" == "issue" && "\$2" == "close" ]]; then + echo "\$3" >> "${STUB_DIR}/close_calls.log" + exit 0 +fi + +echo "unhandled gh invocation: \$*" >&2 +exit 1 +STUB + chmod +x "${STUB_DIR}/gh" +} + +closed_issues() { + cat "${STUB_DIR}/close_calls.log" +} + +# ── --help flag ────────────────────────────────────────────────────────────── + +@test "prints help text with --help" { + run bash "${SCRIPT}" --help + [ "$status" -eq 0 ] + [[ "$output" == *"REQUIRED ENVIRONMENT VARIABLES"* ]] +} + +# ── Input validation ───────────────────────────────────────────────────────── + +@test "fails when PR_NUMBER is unset" { + unset PR_NUMBER + run bash "${SCRIPT}" + [ "$status" -ne 0 ] + [[ "$output" == *"PR_NUMBER"* ]] +} + +# ── No-op cases ─────────────────────────────────────────────────────────────── + +@test "no-ops when the PR body has no backport-issue-numbers marker" { + stub_gh "Cherry-pick of #123 (abc123) into \`release/7.0\`." "" + run bash "${SCRIPT}" + [ "$status" -eq 0 ] + [[ "$output" == *"Nothing to close"* ]] + [ -z "$(closed_issues)" ] +} + +@test "no-ops when the marker's referenced issue is already closed" { + stub_gh "$(printf 'Cherry-pick.\n\n\n\nFixes #4714')" \ + "$(printf '4714:CLOSED')" + run bash "${SCRIPT}" + [ "$status" -eq 0 ] + [[ "$output" == *"already closed"* ]] + [ -z "$(closed_issues)" ] +} + +@test "aborts instead of proceeding when an issue state lookup fails" { + # A failed 'gh issue view' must not be swallowed and mistaken for "issue + # doesn't need closing" — surface it loudly instead of silently skipping. + printf 'Cherry-pick.\n\n\n\nFixes #4714' \ + > "${STUB_DIR}/pr_body.txt" + cat > "${STUB_DIR}/gh" <&2 + exit 1 +fi +echo "unhandled gh invocation: \$*" >&2 +exit 1 +STUB + chmod +x "${STUB_DIR}/gh" + + run bash "${SCRIPT}" + [ "$status" -ne 0 ] + [[ "$output" == *"Failed to look up state for issue #4714"* ]] +} + +@test "ignores a 'Fixes #N' line in the body that has no marker (manual release PR)" { + # A manually-authored release-branch PR containing "Fixes #" + # must not have that issue closed: only issues named in our own + # backport-issue-numbers marker are ever closed. + stub_gh "Manual backport. Fixes #4715." "" + run bash "${SCRIPT}" + [ "$status" -eq 0 ] + [[ "$output" == *"Nothing to close"* ]] + [ -z "$(closed_issues)" ] +} + +# ── Happy path ──────────────────────────────────────────────────────────────── + +@test "closes a single open backport issue named in the marker" { + stub_gh "$(printf 'Cherry-pick.\n\n\n\nFixes #4714')" \ + "$(printf '4714:OPEN')" + run bash "${SCRIPT}" + [ "$status" -eq 0 ] + [ "$(closed_issues)" = "4714" ] +} + +@test "closes multiple open backport issues named in the marker" { + stub_gh "$(printf 'Cherry-pick.\n\n\n\nFixes #4714\n\nFixes #4715')" \ + "$(printf '4714:OPEN\n4715:OPEN')" + run bash "${SCRIPT}" + [ "$status" -eq 0 ] + [ "$(closed_issues | sort)" = "$(printf '4714\n4715' | sort)" ] +} + +@test "closes only the open issue among a mix of open and closed marker entries" { + stub_gh "$(printf 'Cherry-pick.\n\n\n\nFixes #4714\n\nFixes #4715')" \ + "$(printf '4714:OPEN\n4715:CLOSED')" + run bash "${SCRIPT}" + [ "$status" -eq 0 ] + [ "$(closed_issues)" = "4714" ] + [[ "$output" == *"Issue #4715 is already closed"* ]] +} diff --git a/.github/scripts/tests/create-backport-issue.bats b/.github/scripts/tests/create-backport-issue.bats new file mode 100644 index 0000000000..2d69c8d729 --- /dev/null +++ b/.github/scripts/tests/create-backport-issue.bats @@ -0,0 +1,277 @@ +#!/usr/bin/env bats +################################################################################# +# Licensed to the .NET Foundation under one or more agreements. # +# The .NET Foundation licenses this file to you under the MIT license. # +# See the LICENSE file in the project root for more information. # +################################################################################# +# +# Tests for create-backport-issue.sh +# +# Run with: bats .github/scripts/tests/create-backport-issue.bats +# +# Dependencies: bats-core (https://github.com/bats-core/bats-core) +# +################################################################################# + +SCRIPT=".github/scripts/create-backport-issue.sh" + +setup() { + export EVENT_LABEL="Hotfix 7.1.1" + export PARENT_ISSUE_NUMBER="4714" + export GH_TOKEN="fake-token" + export GITHUB_REPOSITORY="dotnet/SqlClient" + + STUB_DIR="$(mktemp -d)" + export PATH="${STUB_DIR}:${PATH}" +} + +teardown() { + rm -rf "${STUB_DIR}" +} + +# Writes a 'gh' stub into STUB_DIR that dispatches based on argv, so each test +# only needs to describe the handful of calls it cares about. The real script +# always reads these responses through a '--jq' filter, so the fixtures below +# are given already in the *post-jq* shape the script expects, not raw API JSON. +# +# $1: sub_issues TSV rows (one per line: "\t\t<number>") +# $2: milestone titles, one per line (as if from --jq '.[].title') +# $3: parent issue view JSON ({title,labels}) +# $4: 'gh issue create' output (the created issue URL) +# $5: issue GET response for the child (JSON with .id) +# $6: issues returned by the orphan recovery search (JSON array) +stub_gh() { + local sub_issues_tsv="$1" + local milestone_titles="$2" + local parent_json="$3" + local created_url="$4" + local child_issue_json="$5" + local orphan_issues_json="${6:-[]}" + + printf '%s' "${sub_issues_tsv}" > "${STUB_DIR}/sub_issues.tsv" + printf '%s' "${milestone_titles}" > "${STUB_DIR}/milestones.txt" + printf '%s' "${orphan_issues_json}" > "${STUB_DIR}/orphan_issues.json" + + cat > "${STUB_DIR}/gh" <<STUB +#!/usr/bin/env bash +set -euo pipefail + +if [[ "\$1" == "api" && "\$2" == repos/*/issues/*/sub_issues && "\${*}" != *"--method POST"* ]]; then + cat "${STUB_DIR}/sub_issues.tsv" + exit 0 +fi + +if [[ "\$1" == "api" && "\$2" == repos/*/milestones ]]; then + cat "${STUB_DIR}/milestones.txt" + exit 0 +fi + +if [[ "\$1" == "issue" && "\$2" == "view" ]]; then + echo '${parent_json}' + exit 0 +fi + +if [[ "\$1" == "issue" && "\$2" == "list" ]]; then + cat "${STUB_DIR}/orphan_issues.json" + exit 0 +fi + +if [[ "\$1" == "issue" && "\$2" == "create" ]]; then + echo "CREATE_CALLED" >> "${STUB_DIR}/issue_create_calls.log" + echo '${created_url}' + exit 0 +fi + +if [[ "\$1" == "api" && "\$2" == repos/*/issues/* && "\${*}" != *"sub_issues"* ]]; then + echo '${child_issue_json}' + exit 0 +fi + +if [[ "\$1" == "api" && "\$2" == repos/*/issues/*/sub_issues && "\${*}" == *"--method POST"* ]]; then + echo "SUB_ISSUE_LINK_CALLED" >> "${STUB_DIR}/sub_issue_calls.log" + exit 0 +fi + +echo "unhandled gh invocation: \$*" >&2 +exit 1 +STUB + chmod +x "${STUB_DIR}/gh" +} + +# ── --help flag ────────────────────────────────────────────────────────────── + +@test "prints help text with --help" { + run bash "${SCRIPT}" --help + [ "$status" -eq 0 ] + [[ "$output" == *"REQUIRED ENVIRONMENT VARIABLES"* ]] +} + +# ── Input validation ───────────────────────────────────────────────────────── + +@test "fails when EVENT_LABEL is unset" { + unset EVENT_LABEL + run bash "${SCRIPT}" + [ "$status" -ne 0 ] + [[ "$output" == *"EVENT_LABEL"* ]] +} + +@test "fails when PARENT_ISSUE_NUMBER is unset" { + unset PARENT_ISSUE_NUMBER + run bash "${SCRIPT}" + [ "$status" -ne 0 ] + [[ "$output" == *"PARENT_ISSUE_NUMBER"* ]] +} + +# ── Label validation ───────────────────────────────────────────────────────── + +@test "skips non-hotfix labels" { + export EVENT_LABEL="bug" + run bash "${SCRIPT}" + [ "$status" -eq 0 ] + [[ "$output" == *"not a valid"* ]] +} + +@test "skips malformed hotfix labels" { + export EVENT_LABEL="Hotfix 7.1" + run bash "${SCRIPT}" + [ "$status" -eq 0 ] + [[ "$output" == *"not a valid"* ]] +} + +# ── Duplicate detection ────────────────────────────────────────────────────── + +@test "skips when a sub-issue is already milestoned and has the child title prefix" { + stub_gh "$(printf '7.1.1\t[7.1.1] something\t4900')" "" "" "" "" + run bash "${SCRIPT}" + [ "$status" -eq 0 ] + [[ "$output" == *"already exists"* ]] +} + +@test "does not skip a similarly named child without the title-prefix space" { + stub_gh "$(printf '7.1.1\t[7.1.1]-follow-up\t4899')" \ + "$(printf '7.1.1')" \ + '{"title":"Parent title","labels":[]}' \ + "https://github.com/dotnet/SqlClient/issues/4901" \ + '{"id":123456789}' + run bash "${SCRIPT}" + [ "$status" -eq 0 ] + [[ "$output" == *"Created backport issue #4901"* ]] + [ -f "${STUB_DIR}/issue_create_calls.log" ] +} + +@test "skips when a sub-issue already has the child title prefix but no milestone yet" { + stub_gh "$(printf 'NONE\t[7.1.1] something\t4900')" "" "" "" "" + run bash "${SCRIPT}" + [ "$status" -eq 0 ] + [[ "$output" == *"already exists"* ]] +} + +@test "does not skip on a milestone match alone when the title lacks the prefix" { + # An unrelated sub-issue can be milestoned to the same release (e.g. a + # separate follow-up task) without being the real backport issue. Matching + # on milestone alone would wrongly skip creating the actual backport issue. + stub_gh "$(printf '7.1.1\tUnrelated follow-up task\t4899')" \ + "$(printf '7.1.1')" \ + '{"title":"Parent title","labels":[{"name":"bug"},{"name":"Hotfix 7.1.1"}]}' \ + "https://github.com/dotnet/SqlClient/issues/4901" \ + '{"id":123456789}' + run bash "${SCRIPT}" + [ "$status" -eq 0 ] + [[ "$output" != *"already exists"* ]] + [[ "$output" == *"Created backport issue #4901"* ]] +} + +@test "aborts instead of proceeding when the sub-issues lookup fails" { + # A failed lookup must not be treated the same as "no sub-issues exist" — + # that would defeat the duplicate guard and create a second backport issue + # on a rerun after a transient API/permission error. + cat > "${STUB_DIR}/gh" <<'STUB' +#!/usr/bin/env bash +if [[ "$1" == "api" && "$2" == repos/*/issues/*/sub_issues && "${*}" != *"--method POST"* ]]; then + echo "gh: permission denied" >&2 + exit 1 +fi +echo "unhandled gh invocation: $*" >&2 +exit 1 +STUB + chmod +x "${STUB_DIR}/gh" + + run bash "${SCRIPT}" + [ "$status" -ne 0 ] + [[ "$output" == *"Failed to look up existing sub-issues"* ]] +} + +@test "does not skip when existing sub-issues are for a different version" { + stub_gh "$(printf '7.0.5\t[7.0.5] other\t4800')" \ + "$(printf '7.1.1')" \ + '{"title":"Parent title","labels":[{"name":"bug"},{"name":"Hotfix 7.1.1"}]}' \ + "https://github.com/dotnet/SqlClient/issues/4901" \ + '{"id":123456789}' + run bash "${SCRIPT}" + [ "$status" -eq 0 ] + [[ "$output" == *"Created backport issue #4901"* ]] + [[ "$output" == *"Linked #4901 as a sub-issue of #4714"* ]] + [ -f "${STUB_DIR}/sub_issue_calls.log" ] +} + +# ── Happy path ──────────────────────────────────────────────────────────────── + +@test "creates a backport issue and links it as a sub-issue" { + stub_gh "" \ + "$(printf '7.1.1')" \ + '{"title":"Parent title","labels":[{"name":"bug"},{"name":"Hotfix 7.1.1"}]}' \ + "https://github.com/dotnet/SqlClient/issues/4901" \ + '{"id":123456789}' + + run bash "${SCRIPT}" + [ "$status" -eq 0 ] + [[ "$output" == *"Milestone '7.1.1' found."* ]] + [[ "$output" == *"Created backport issue #4901"* ]] + [[ "$output" == *"Linked #4901 as a sub-issue of #4714"* ]] + [ -f "${STUB_DIR}/sub_issue_calls.log" ] +} + +@test "reuses an unlinked issue created by an earlier incomplete run" { + stub_gh "" \ + "$(printf '7.1.1')" \ + '{"title":"Parent title","labels":[]}' \ + "https://github.com/dotnet/SqlClient/issues/4901" \ + '{"id":123456789}' \ + '[{"number":4903,"title":"[7.1.1] Parent title","body":"Backport of #4714 for the `7.1.1` hotfix.","author":{"login":"github-actions[bot]"}}]' + + run bash "${SCRIPT}" + [ "$status" -eq 0 ] + [[ "$output" == *"Found previously created, unlinked backport issue #4903"* ]] + [[ "$output" == *"Linked #4903 as a sub-issue of #4714"* ]] + [ ! -f "${STUB_DIR}/issue_create_calls.log" ] + [ -f "${STUB_DIR}/sub_issue_calls.log" ] +} + +@test "reuses an unlinked issue when the CLI formats the Actions bot login without the suffix" { + stub_gh "" \ + "$(printf '7.1.1')" \ + '{"title":"Parent title","labels":[]}' \ + "https://github.com/dotnet/SqlClient/issues/4901" \ + '{"id":123456789}' \ + '[{"number":4904,"title":"[7.1.1] Parent title","body":"Backport of #4714 for the `7.1.1` hotfix.","author":{"login":"github-actions"}}]' + + run bash "${SCRIPT}" + [ "$status" -eq 0 ] + [[ "$output" == *"Found previously created, unlinked backport issue #4904"* ]] + [[ "$output" == *"Linked #4904 as a sub-issue of #4714"* ]] + [ ! -f "${STUB_DIR}/issue_create_calls.log" ] + [ -f "${STUB_DIR}/sub_issue_calls.log" ] +} + +@test "creates a backport issue without a milestone when it does not exist" { + stub_gh "" \ + "" \ + '{"title":"Parent title","labels":[]}' \ + "https://github.com/dotnet/SqlClient/issues/4902" \ + '{"id":987654321}' + + run bash "${SCRIPT}" + [ "$status" -eq 0 ] + [[ "$output" == *"does not exist"* ]] + [[ "$output" == *"Created backport issue #4902"* ]] +} diff --git a/.github/scripts/tests/extract-hotfix-versions.bats b/.github/scripts/tests/extract-hotfix-versions.bats index e0767ffd04..8f13a84608 100644 --- a/.github/scripts/tests/extract-hotfix-versions.bats +++ b/.github/scripts/tests/extract-hotfix-versions.bats @@ -143,7 +143,7 @@ get_versions() { # ── Labeled event: basic behavior ─────────────────────────────────────────── -@test "labeled event: processes valid newly added label" { +@test "labeled event: reconciles all current Hotfix labels" { export EVENT_ACTION="labeled" export EVENT_LABEL="Hotfix 7.0.1" export LABELS="Hotfix 7.0.1,Hotfix 8.0.0" @@ -168,19 +168,19 @@ STUB rm -rf "${stub_dir}" [ "$status" -eq 0 ] - [ "$(get_versions)" = '["7.0.1"]' ] + [ "$(get_versions)" = '["7.0.1","8.0.0"]' ] } -@test "labeled event: skips non-hotfix label" { +@test "labeled event: reconciles current Hotfix labels after a non-hotfix label is added" { export EVENT_ACTION="labeled" export EVENT_LABEL="bug" export LABELS="bug,Hotfix 7.0.1" run bash "${SCRIPT}" [ "$status" -eq 0 ] - [ "$(get_versions)" = '[]' ] + [ "$(get_versions)" = '["7.0.1"]' ] } -@test "labeled event: skips malformed hotfix label" { +@test "labeled event: ignores malformed Hotfix labels while reconciling current labels" { export EVENT_ACTION="labeled" export EVENT_LABEL="Hotfix 7.0" export LABELS="Hotfix 7.0" @@ -242,3 +242,109 @@ STUB [ "$(get_versions)" = '[]' ] [[ "$output" == *"already exists"* ]] } + +# ── Reconcile event (workflow_dispatch re-run) ────────────────────────────── + +@test "reconcile event: processes all current Hotfix labels when none exist yet" { + export EVENT_ACTION="reconcile" + export LABELS="Hotfix 7.0.1,Hotfix 8.0.0" + + local stub_dir + stub_dir="$(mktemp -d)" + cat > "${stub_dir}/gh" <<'STUB' +#!/usr/bin/env bash +if [[ "$1" == "api" && "$2" == repos/*/git/ref/heads/* ]]; then + exit 1 +fi +echo "0" +STUB + chmod +x "${stub_dir}/gh" + export PATH="${stub_dir}:${PATH}" + + run bash "${SCRIPT}" + rm -rf "${stub_dir}" + + [ "$status" -eq 0 ] + [ "$(get_versions)" = '["7.0.1","8.0.0"]' ] +} + +@test "reconcile event: ignores non-hotfix labels" { + export EVENT_ACTION="reconcile" + export LABELS="bug,Hotfix 7.0.1,enhancement" + + local stub_dir + stub_dir="$(mktemp -d)" + cat > "${stub_dir}/gh" <<'STUB' +#!/usr/bin/env bash +if [[ "$1" == "api" && "$2" == repos/*/git/ref/heads/* ]]; then + exit 1 +fi +echo "0" +STUB + chmod +x "${stub_dir}/gh" + export PATH="${stub_dir}:${PATH}" + + run bash "${SCRIPT}" + rm -rf "${stub_dir}" + + [ "$status" -eq 0 ] + [ "$(get_versions)" = '["7.0.1"]' ] +} + +@test "reconcile event: skips versions that already have a cherry-pick branch, keeps the rest" { + export EVENT_ACTION="reconcile" + export LABELS="Hotfix 7.0.1,Hotfix 8.0.0" + + local stub_dir + stub_dir="$(mktemp -d)" + # Branch exists for 7.0.1 only; 8.0.0 has neither a branch nor a PR. + cat > "${stub_dir}/gh" <<'STUB' +#!/usr/bin/env bash +if [[ "$1" == "api" && "$2" == *"pr-42-to-7.0.1" ]]; then + exit 0 +fi +if [[ "$1" == "api" && "$2" == repos/*/git/ref/heads/* ]]; then + exit 1 +fi +echo "0" +STUB + chmod +x "${stub_dir}/gh" + export PATH="${stub_dir}:${PATH}" + + run bash "${SCRIPT}" + rm -rf "${stub_dir}" + + [ "$status" -eq 0 ] + [ "$(get_versions)" = '["8.0.0"]' ] +} + +@test "reconcile event: emits an empty (not failing) result when every valid label is a duplicate" { + export EVENT_ACTION="reconcile" + export LABELS="Hotfix 7.0.1" + + local stub_dir + stub_dir="$(mktemp -d)" + cat > "${stub_dir}/gh" <<'STUB' +#!/usr/bin/env bash +if [[ "$1" == "api" && "$2" == repos/*/git/ref/heads/* ]]; then + exit 0 +fi +echo "0" +STUB + chmod +x "${stub_dir}/gh" + export PATH="${stub_dir}:${PATH}" + + run bash "${SCRIPT}" + rm -rf "${stub_dir}" + + [ "$status" -eq 0 ] + [ "$(get_versions)" = '[]' ] +} + +@test "reconcile event: still fails when no valid Hotfix label is present" { + export EVENT_ACTION="reconcile" + export LABELS="bug,enhancement" + run bash "${SCRIPT}" + [ "$status" -eq 1 ] + [[ "$output" == *"No valid"* ]] +} diff --git a/.github/scripts/tests/resolve-hotfix-dispatch-context.bats b/.github/scripts/tests/resolve-hotfix-dispatch-context.bats new file mode 100644 index 0000000000..9c5a82f1cf --- /dev/null +++ b/.github/scripts/tests/resolve-hotfix-dispatch-context.bats @@ -0,0 +1,94 @@ +#!/usr/bin/env bats +################################################################################# +# Licensed to the .NET Foundation under one or more agreements. # +# The .NET Foundation licenses this file to you under the MIT license. # +# See the LICENSE file in the project root for more information. # +################################################################################# +# +# Tests for resolve-hotfix-dispatch-context.sh +# +# Run with: bats .github/scripts/tests/resolve-hotfix-dispatch-context.bats +# +# Dependencies: bats-core (https://github.com/bats-core/bats-core) +# +################################################################################# + +SCRIPT=".github/scripts/resolve-hotfix-dispatch-context.sh" + +setup() { + export PR_NUMBER="4721" + export GITHUB_REPOSITORY="dotnet/SqlClient" + export GITHUB_OUTPUT + GITHUB_OUTPUT="$(mktemp)" + + STUB_DIR="$(mktemp -d)" + export STUB_DIR + export PATH="${STUB_DIR}:${PATH}" + + cat > "${STUB_DIR}/gh" <<'STUB' +#!/usr/bin/env bash +set -euo pipefail + +printf '%s\n' "$*" > "${STUB_DIR}/gh_args.txt" +for ((i = 1; i <= $#; i++)); do + if [[ "${!i}" == "--jq" ]]; then + j=$((i + 1)) + jq -r "${!j}" "${STUB_DIR}/pr.json" + exit 0 + fi +done + +echo "missing --jq argument" >&2 +exit 1 +STUB + chmod +x "${STUB_DIR}/gh" +} + +teardown() { + rm -rf "${STUB_DIR}" + rm -f "${GITHUB_OUTPUT}" +} + +stub_pr_state() { + jq -n --arg state "$1" '{ + number: 4721, + state: $state, + baseRefName: "main", + labels: [{name: "Hotfix 7.1.1"}], + mergeCommit: {oid: "0123456789abcdef"}, + title: "Fix issue" + }' > "${STUB_DIR}/pr.json" +} + +@test "workflow_dispatch context marks a merged PR for reconciliation" { + stub_pr_state "MERGED" + + run bash "${SCRIPT}" + + [ "$status" -eq 0 ] + grep -Fxq "merged=true" "${GITHUB_OUTPUT}" + grep -Fxq "event_action=reconcile" "${GITHUB_OUTPUT}" + grep -Fxq "pr_number=4721" "${GITHUB_OUTPUT}" + grep -Fxq "base_ref=main" "${GITHUB_OUTPUT}" + grep -Fxq "labels=Hotfix 7.1.1" "${GITHUB_OUTPUT}" + grep -Fxq "merge_commit_sha=0123456789abcdef" "${GITHUB_OUTPUT}" + grep -Fq 'pr view 4721 --repo dotnet/SqlClient --json number,state,baseRefName,labels,mergeCommit,title --jq' "${STUB_DIR}/gh_args.txt" +} + +@test "workflow_dispatch context does not mark an unmerged closed PR as merged" { + stub_pr_state "CLOSED" + + run bash "${SCRIPT}" + + [ "$status" -eq 0 ] + grep -Fxq "merged=false" "${GITHUB_OUTPUT}" +} + +@test "workflow_dispatch context does not mark an open PR as merged" { + stub_pr_state "OPEN" + + run bash "${SCRIPT}" + + [ "$status" -eq 0 ] + grep -Fxq "merged=false" "${GITHUB_OUTPUT}" +} diff --git a/.github/scripts/tests/sync-hotfix-label-from-issue.bats b/.github/scripts/tests/sync-hotfix-label-from-issue.bats new file mode 100644 index 0000000000..3d7c8ad4be --- /dev/null +++ b/.github/scripts/tests/sync-hotfix-label-from-issue.bats @@ -0,0 +1,256 @@ +#!/usr/bin/env bats +################################################################################# +# Licensed to the .NET Foundation under one or more agreements. # +# The .NET Foundation licenses this file to you under the MIT license. # +# See the LICENSE file in the project root for more information. # +################################################################################# +# +# Tests for sync-hotfix-label-from-issue.sh +# +# Run with: bats .github/scripts/tests/sync-hotfix-label-from-issue.bats +# +# Dependencies: bats-core (https://github.com/bats-core/bats-core) +# +################################################################################# + +SCRIPT=".github/scripts/sync-hotfix-label-from-issue.sh" + +setup() { + export ISSUE_NUMBER="4715" + export GH_TOKEN="fake-token" + export GITHUB_REPOSITORY="dotnet/SqlClient" + + STUB_DIR="$(mktemp -d)" + export PATH="${STUB_DIR}:${PATH}" +} + +teardown() { + rm -rf "${STUB_DIR}" +} + +# Writes a 'gh' stub that dispatches based on argv, covering both this +# script's own GraphQL lookup and the calls its delegate, +# sync-hotfix-label-to-pr.sh, makes for each PR it's re-run against. +# +# $1: newline-separated "pr_number:STATE[:repository]" pairs returned by the +# closedByPullRequestsReferences GraphQL query (STATE is OPEN, MERGED, +# or CLOSED; repository defaults to GITHUB_REPOSITORY) +# $2: newline-separated "pr_number:closing_issue_numbers,..." describing +# each PR's own closing issue references (delegate's Step 1) +# $3: newline-separated "issue_number:label1,label2" pairs describing each +# referenced issue's Hotfix labels (delegate's Step 2) +# $4: newline-separated "pr_number:label1,label2" pairs describing each PR's +# existing labels (delegate's Step 3) +stub_gh() { + local closing_prs="$1" + local pr_closing_issues="$2" + local issue_label_map="$3" + local pr_label_map="$4" + + printf '%s' "${closing_prs}" > "${STUB_DIR}/closing_prs.txt" + printf '%s' "${pr_closing_issues}" > "${STUB_DIR}/pr_closing_issues.txt" + printf '%s' "${issue_label_map}" > "${STUB_DIR}/issue_labels.txt" + printf '%s' "${pr_label_map}" > "${STUB_DIR}/pr_labels.txt" + : > "${STUB_DIR}/add_label_calls.log" + : > "${STUB_DIR}/workflow_run_calls.log" + + cat > "${STUB_DIR}/gh" <<STUB +#!/usr/bin/env bash +set -euo pipefail + +# gh api graphql (closedByPullRequestsReferences lookup) +if [[ "\$1" == "api" && "\$2" == "graphql" ]]; then + jq -Rn --arg repository "${GITHUB_REPOSITORY}" ' + [inputs | split(":") | { + number: (.[0] | tonumber), + state: .[1], + repository: {nameWithOwner: (.[2] // \$repository)} + }] | + {data: {repository: {issue: {closedByPullRequestsReferences: {nodes: .}}}}} + ' "${STUB_DIR}/closing_prs.txt" + exit 0 +fi + +# gh pr view <n> --json closingIssuesReferences ... (delegate Step 1) +if [[ "\$1" == "pr" && "\$2" == "view" && "\${*}" == *"closingIssuesReferences"* ]]; then + pr_number="\$3" + awk -F':' -v n="\${pr_number}" '\$1 == n { gsub(",", "\\n", \$2); print \$2 }' "${STUB_DIR}/pr_closing_issues.txt" + exit 0 +fi + +# gh issue view <n> --json labels ... (delegate Step 2) +if [[ "\$1" == "issue" && "\$2" == "view" ]]; then + issue_number="\$3" + awk -F':' -v n="\${issue_number}" '\$1 == n { gsub(",", "\\n", \$2); print \$2 }' "${STUB_DIR}/issue_labels.txt" + exit 0 +fi + +# gh pr view <n> --json labels ... (delegate Step 3, existing PR labels) +if [[ "\$1" == "pr" && "\$2" == "view" && "\${*}" == *"--json labels"* ]]; then + pr_number="\$3" + awk -F':' -v n="\${pr_number}" '\$1 == n { gsub(",", "\\n", \$2); print \$2 }' "${STUB_DIR}/pr_labels.txt" + exit 0 +fi + +# gh pr edit <n> --repo <repo> --add-label <label> (delegate Step 3) +if [[ "\$1" == "pr" && "\$2" == "edit" ]]; then + echo "\$3 \$*" | awk '{ print \$1 }' >> "${STUB_DIR}/add_label_calls.log" + for ((i = 1; i <= \$#; i++)); do + if [[ "\${!i}" == "--add-label" ]]; then + j=\$((i + 1)) + echo "\${!j}" >> "${STUB_DIR}/add_label_calls_labels.log" + fi + done + exit 0 +fi + +# gh workflow run cherry-pick-hotfix.yml --repo <repo> -f pr_number=<n> +if [[ "\$1" == "workflow" && "\$2" == "run" ]]; then + for ((i = 1; i <= \$#; i++)); do + if [[ "\${!i}" == -f ]]; then + j=\$((i + 1)) + echo "\${!j}" >> "${STUB_DIR}/workflow_run_calls.log" + fi + done + exit 0 +fi + +echo "unhandled gh invocation: \$*" >&2 +exit 1 +STUB + chmod +x "${STUB_DIR}/gh" +} + +added_labels() { + cat "${STUB_DIR}/add_label_calls_labels.log" 2>/dev/null +} + +added_prs() { + cat "${STUB_DIR}/add_label_calls.log" 2>/dev/null +} + +dispatched_prs() { + cat "${STUB_DIR}/workflow_run_calls.log" 2>/dev/null +} + +# ── --help flag ────────────────────────────────────────────────────────────── + +@test "prints help text with --help" { + run bash "${SCRIPT}" --help + [ "$status" -eq 0 ] + [[ "$output" == *"REQUIRED ENVIRONMENT VARIABLES"* ]] +} + +# ── Input validation ───────────────────────────────────────────────────────── + +@test "fails when ISSUE_NUMBER is unset" { + unset ISSUE_NUMBER + run bash "${SCRIPT}" + [ "$status" -ne 0 ] + [[ "$output" == *"ISSUE_NUMBER"* ]] +} + +# ── No-op cases ─────────────────────────────────────────────────────────────── + +@test "no-ops when no open PR closes the issue" { + stub_gh "" "" "" "" + run bash "${SCRIPT}" + [ "$status" -eq 0 ] + [[ "$output" == *"Nothing to sync"* ]] + [ -z "$(added_labels)" ] +} + +@test "ignores a closed PR that references the issue" { + stub_gh "$(printf '4721:CLOSED')" "" "" "" + run bash "${SCRIPT}" + [ "$status" -eq 0 ] + [[ "$output" == *"Nothing to sync"* ]] + [ -z "$(added_labels)" ] +} + +# ── Happy path ──────────────────────────────────────────────────────────────── + +@test "syncs the Hotfix label onto the open PR that closes the issue" { + stub_gh \ + "$(printf '4721:OPEN')" \ + "$(printf '4721:4715')" \ + "$(printf '4715:Hotfix 7.1.1')" \ + "$(printf '4721:')" + run bash "${SCRIPT}" + [ "$status" -eq 0 ] + [[ "$output" == *"Syncing Hotfix labels onto PR #4721"* ]] + [ "$(added_labels)" = "Hotfix 7.1.1" ] + [ "$(added_prs)" = "4721" ] +} + +@test "syncs onto every open PR when more than one references the issue" { + stub_gh \ + "$(printf '4721:OPEN\n4722:OPEN')" \ + "$(printf '4721:4715\n4722:4715')" \ + "$(printf '4715:Hotfix 7.1.1')" \ + "$(printf '4721:\n4722:')" + run bash "${SCRIPT}" + [ "$status" -eq 0 ] + [ "$(added_prs | sort)" = "$(printf '4721\n4722' | sort)" ] +} + +@test "is a no-op via the delegate when the PR already has the label" { + stub_gh \ + "$(printf '4721:OPEN')" \ + "$(printf '4721:4715')" \ + "$(printf '4715:Hotfix 7.1.1')" \ + "$(printf '4721:Hotfix 7.1.1')" + run bash "${SCRIPT}" + [ "$status" -eq 0 ] + [[ "$output" == *"already has label 'Hotfix 7.1.1'"* ]] + [ -z "$(added_labels)" ] +} + +# ── Merged PR handling (retroactive labeling; see PR #4737/#4738) ─────────── + +@test "syncs the label onto an already-merged PR and dispatches the reconcile workflow" { + stub_gh \ + "$(printf '4721:MERGED')" \ + "$(printf '4721:4715')" \ + "$(printf '4715:Hotfix 7.1.1')" \ + "$(printf '4721:')" + run bash "${SCRIPT}" + [ "$status" -eq 0 ] + [[ "$output" == *"already merged"* ]] + [ "$(added_labels)" = "Hotfix 7.1.1" ] + [ "$(dispatched_prs)" = "pr_number=4721" ] +} + +@test "does not dispatch the reconcile workflow for an open PR" { + stub_gh \ + "$(printf '4721:OPEN')" \ + "$(printf '4721:4715')" \ + "$(printf '4715:Hotfix 7.1.1')" \ + "$(printf '4721:')" + run bash "${SCRIPT}" + [ "$status" -eq 0 ] + [ -z "$(dispatched_prs)" ] +} + +@test "dispatches the reconcile workflow only for the merged PR when both open and merged PRs reference the issue" { + stub_gh \ + "$(printf '4721:OPEN\n4722:MERGED')" \ + "$(printf '4721:4715\n4722:4715')" \ + "$(printf '4715:Hotfix 7.1.1')" \ + "$(printf '4721:\n4722:')" + run bash "${SCRIPT}" + [ "$status" -eq 0 ] + [ "$(dispatched_prs)" = "pr_number=4722" ] +} + +@test "ignores a cross-repository PR even when its number collides with a local PR" { + stub_gh \ + "$(printf '4721:MERGED:other/SqlClient\n4721:OPEN:dotnet/SqlClient')" \ + "$(printf '4721:4715')" \ + "$(printf '4715:Hotfix 7.1.1')" \ + "$(printf '4721:')" + run bash "${SCRIPT}" + [ "$status" -eq 0 ] + [ "$(added_prs)" = "4721" ] + [ -z "$(dispatched_prs)" ] +} diff --git a/.github/scripts/tests/sync-hotfix-label-to-pr.bats b/.github/scripts/tests/sync-hotfix-label-to-pr.bats new file mode 100644 index 0000000000..ecdcdd24ac --- /dev/null +++ b/.github/scripts/tests/sync-hotfix-label-to-pr.bats @@ -0,0 +1,180 @@ +#!/usr/bin/env bats +################################################################################# +# Licensed to the .NET Foundation under one or more agreements. # +# The .NET Foundation licenses this file to you under the MIT license. # +# See the LICENSE file in the project root for more information. # +################################################################################# +# +# Tests for sync-hotfix-label-to-pr.sh +# +# Run with: bats .github/scripts/tests/sync-hotfix-label-to-pr.bats +# +# Dependencies: bats-core (https://github.com/bats-core/bats-core) +# +################################################################################# + +SCRIPT=".github/scripts/sync-hotfix-label-to-pr.sh" + +setup() { + export PR_NUMBER="4750" + export GH_TOKEN="fake-token" + export GITHUB_REPOSITORY="dotnet/SqlClient" + + STUB_DIR="$(mktemp -d)" + export PATH="${STUB_DIR}:${PATH}" +} + +teardown() { + rm -rf "${STUB_DIR}" +} + +# Writes a 'gh' stub that dispatches based on argv. +# +# $1: closing issue numbers, one per line (from 'pr view --json closingIssuesReferences') +# $2: newline-separated "issue_number:label1,label2" pairs describing each +# referenced issue's Hotfix labels (label list may be empty) +# $3: existing PR labels, one per line +stub_gh() { + local closing_issues="$1" + local issue_label_map="$2" + local existing_pr_labels="$3" + + printf '%s' "${closing_issues}" > "${STUB_DIR}/closing_issues.txt" + printf '%s' "${issue_label_map}" > "${STUB_DIR}/issue_labels.txt" + printf '%s' "${existing_pr_labels}" > "${STUB_DIR}/pr_labels.txt" + : > "${STUB_DIR}/add_label_calls.log" + + cat > "${STUB_DIR}/gh" <<STUB +#!/usr/bin/env bash +set -euo pipefail + +# gh pr view <n> --json closingIssuesReferences ... +if [[ "\$1" == "pr" && "\$2" == "view" && "\${*}" == *"closingIssuesReferences"* ]]; then + cat "${STUB_DIR}/closing_issues.txt" + exit 0 +fi + +# gh pr view <n> --json labels ... +if [[ "\$1" == "pr" && "\$2" == "view" && "\${*}" == *"--json labels"* ]]; then + cat "${STUB_DIR}/pr_labels.txt" + exit 0 +fi + +# gh issue view <n> --json labels ... (already filtered to "Hotfix " labels, +# matching the real script's '--jq select(startswith("Hotfix "))' filter) +if [[ "\$1" == "issue" && "\$2" == "view" ]]; then + issue_number="\$3" + awk -F':' -v n="\${issue_number}" '\$1 == n { print \$2 }' "${STUB_DIR}/issue_labels.txt" \ + | tr ',' '\n' | grep '^Hotfix ' || true + exit 0 +fi + +# gh pr edit <n> --repo <repo> --add-label <label> +if [[ "\$1" == "pr" && "\$2" == "edit" ]]; then + args=("\$@") + for i in "\${!args[@]}"; do + if [[ "\${args[\$i]}" == "--add-label" ]]; then + next=\$((i + 1)) + echo "\${args[\$next]}" >> "${STUB_DIR}/add_label_calls.log" + fi + done + exit 0 +fi + +echo "unhandled gh invocation: \$*" >&2 +exit 1 +STUB + chmod +x "${STUB_DIR}/gh" +} + +added_labels() { + cat "${STUB_DIR}/add_label_calls.log" +} + +# ── --help flag ────────────────────────────────────────────────────────────── + +@test "prints help text with --help" { + run bash "${SCRIPT}" --help + [ "$status" -eq 0 ] + [[ "$output" == *"REQUIRED ENVIRONMENT VARIABLES"* ]] +} + +# ── Input validation ───────────────────────────────────────────────────────── + +@test "fails when PR_NUMBER is unset" { + unset PR_NUMBER + run bash "${SCRIPT}" + [ "$status" -ne 0 ] + [[ "$output" == *"PR_NUMBER"* ]] +} + +# ── No-op cases ─────────────────────────────────────────────────────────────── + +@test "no-ops when the PR has no closing issue references" { + stub_gh "" "" "" + run bash "${SCRIPT}" + [ "$status" -eq 0 ] + [[ "$output" == *"Nothing to sync"* ]] + [ -z "$(added_labels)" ] +} + +@test "no-ops when referenced issues have no Hotfix labels" { + stub_gh "$(printf '4714')" "$(printf '4714:bug')" "" + run bash "${SCRIPT}" + [ "$status" -eq 0 ] + [[ "$output" == *"No 'Hotfix X.Y.Z' labels found"* ]] + [ -z "$(added_labels)" ] +} + +@test "aborts instead of proceeding when an issue label lookup fails" { + # A failed 'gh issue view' must not be swallowed by the grep '|| true' + # tolerance and treated the same as "issue has no Hotfix labels" — that + # would silently skip labeling the PR after a transient API/permission + # error instead of surfacing a retryable failure. + printf '4714' > "${STUB_DIR}/closing_issues.txt" + cat > "${STUB_DIR}/gh" <<STUB +#!/usr/bin/env bash +set -euo pipefail +if [[ "\$1" == "pr" && "\$2" == "view" && "\${*}" == *"closingIssuesReferences"* ]]; then + cat "${STUB_DIR}/closing_issues.txt" + exit 0 +fi +if [[ "\$1" == "issue" && "\$2" == "view" ]]; then + echo "gh: permission denied" >&2 + exit 1 +fi +echo "unhandled gh invocation: \$*" >&2 +exit 1 +STUB + chmod +x "${STUB_DIR}/gh" + + run bash "${SCRIPT}" + [ "$status" -ne 0 ] + [[ "$output" == *"Failed to look up labels for issue #4714"* ]] +} + +# ── Happy path ──────────────────────────────────────────────────────────────── + +@test "adds a Hotfix label from a single referenced issue" { + stub_gh "$(printf '4714')" "$(printf '4714:bug,Hotfix 7.1.1')" "" + run bash "${SCRIPT}" + [ "$status" -eq 0 ] + [ "$(added_labels)" = "Hotfix 7.1.1" ] +} + +@test "adds Hotfix labels from multiple referenced issues without duplicates" { + stub_gh "$(printf '4714\n4715')" \ + "$(printf '4714:Hotfix 7.1.1\n4715:Hotfix 7.1.1,Hotfix 8.0.0')" \ + "" + run bash "${SCRIPT}" + [ "$status" -eq 0 ] + [ "$(added_labels | sort)" = "$(printf 'Hotfix 7.1.1\nHotfix 8.0.0' | sort)" ] +} + +@test "does not re-add a Hotfix label the PR already has" { + stub_gh "$(printf '4714')" "$(printf '4714:Hotfix 7.1.1')" "$(printf 'Hotfix 7.1.1')" + run bash "${SCRIPT}" + [ "$status" -eq 0 ] + [[ "$output" == *"already has label 'Hotfix 7.1.1'"* ]] + [ -z "$(added_labels)" ] +} diff --git a/.github/workflows/cherry-pick-hotfix.yml b/.github/workflows/cherry-pick-hotfix.yml index 678a6b20b3..170024b37f 100644 --- a/.github/workflows/cherry-pick-hotfix.yml +++ b/.github/workflows/cherry-pick-hotfix.yml @@ -11,6 +11,10 @@ # a single PR — each one produces an independent cherry-pick PR targeting # the corresponding release/<version> branch. # +# Companion to hotfix-label-issue.yml, sync-hotfix-label-to-pr.yml, and +# close-backport-issue.yml. Works together to automate backporting a fix from +# an issue through to a merged cherry-pick PR. +# # Usage: # 1. Merge a PR to the default branch. # 2. Add a "Hotfix <version>" label (e.g. "Hotfix 7.0.1") either before @@ -30,29 +34,141 @@ name: Cherry-pick Hotfix to release branch # the cherry-pick runs immediately. # - 'labeled': fires when a label is added after merge — allows retroactive cherry-picks # by adding the label to an already-merged PR. +# - 'workflow_dispatch': fires when sync-hotfix-label-from-issue.sh adds a +# "Hotfix <version>" label to an already-merged PR. That label-add uses the +# workflow's own GITHUB_TOKEN, and GitHub does not trigger further workflow +# runs (including this workflow's own 'labeled' trigger) for events caused +# by the repository's own GITHUB_TOKEN, so the script explicitly dispatches +# this workflow instead. Runs in "reconcile" mode (see extract-hotfix-versions.sh): +# re-derives all current Hotfix labels on the PR, skipping any that already +# have a cherry-pick branch or PR from an earlier event. on: pull_request_target: types: [closed, labeled] + workflow_dispatch: + inputs: + pr_number: + description: "Number of the already-merged PR to reconcile Hotfix labels for." + required: true + type: number + +# Serialize all runs of this workflow for the same PR. A PR can carry several +# "Hotfix <version>" labels, and each labeling event -- plus the 'closed' +# event and any 'workflow_dispatch' reconcile run from +# sync-hotfix-label-from-issue.sh -- triggers an independent run. Without +# this, concurrent runs for the same PR can race on the shared +# branch/PR-existence check in cherry-pick-to-release.sh: one run's push or +# 'gh pr create' can fail because another run created the branch/PR first, +# or a run that checks existence just before the first run creates it can +# skip a version permanently. GitHub retains only one pending run per +# concurrency group, so each labeled-event run reconciles all current Hotfix +# labels; replacing a pending run therefore cannot lose a version. +concurrency: + group: cherry-pick-hotfix-${{ github.event.pull_request.number || inputs.pr_number }} + cancel-in-progress: false # 'contents: write' is needed to push the cherry-pick branch. # 'pull-requests: write' is needed to create the new PR via the GitHub CLI. +# 'issues: read' is needed to look up the backport issue (a sub-issue of the +# original PR's closing-issue reference) via the sub-issues API. permissions: contents: write pull-requests: write + issues: read jobs: - # First job: extract all hotfix versions from the PR labels and emit them as + # First job: resolve PR context (merged status, base ref, labels, merge + # commit SHA, title) from whichever trigger fired, since 'workflow_dispatch' + # has no 'pull_request_target' event payload to read it from. + resolve-pr: + runs-on: ubuntu-latest + outputs: + pr_number: ${{ steps.resolve.outputs.pr_number }} + event_action: ${{ steps.resolve.outputs.event_action }} + event_label: ${{ steps.resolve.outputs.event_label }} + merged: ${{ steps.resolve.outputs.merged }} + base_ref: ${{ steps.resolve.outputs.base_ref }} + labels: ${{ steps.resolve.outputs.labels }} + merge_commit_sha: ${{ steps.resolve.outputs.merge_commit_sha }} + pr_title: ${{ steps.resolve.outputs.pr_title }} + steps: + - name: Resolve PR context (pull_request_target) + if: github.event_name == 'pull_request_target' + id: resolve_event + env: + PR_TITLE: ${{ github.event.pull_request.title }} + EVENT_LABEL: ${{ github.event.label.name || '' }} + PR_LABELS: ${{ join(github.event.pull_request.labels.*.name, ',') }} + run: | + { + echo "pr_number=${{ github.event.pull_request.number }}" + echo "event_action=${{ github.event.action }}" + echo "event_label=${EVENT_LABEL}" + echo "merged=${{ github.event.pull_request.merged }}" + echo "base_ref=${{ github.event.pull_request.base.ref }}" + echo "labels=${PR_LABELS}" + echo "merge_commit_sha=${{ github.event.pull_request.merge_commit_sha }}" + } >> "${GITHUB_OUTPUT}" + echo "pr_title=${PR_TITLE}" >> "${GITHUB_OUTPUT}" + + - name: Checkout dispatch helper + if: github.event_name == 'workflow_dispatch' + uses: actions/checkout@v6 + with: + sparse-checkout: .github/scripts/resolve-hotfix-dispatch-context.sh + sparse-checkout-cone-mode: false + + - name: Resolve PR context (workflow_dispatch) + if: github.event_name == 'workflow_dispatch' + id: resolve_dispatch + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + PR_NUMBER: ${{ inputs.pr_number }} + run: | + bash "${GITHUB_WORKSPACE}/.github/scripts/resolve-hotfix-dispatch-context.sh" + + - name: Merge resolved outputs + id: resolve + env: + # PR title may contain characters unsafe for direct expression + # interpolation into the script below; pass it via env instead. + RESOLVED_PR_TITLE: ${{ steps.resolve_event.outputs.pr_title || steps.resolve_dispatch.outputs.pr_title }} + RESOLVED_EVENT_LABEL: ${{ steps.resolve_event.outputs.event_label || steps.resolve_dispatch.outputs.event_label }} + RESOLVED_LABELS: ${{ steps.resolve_event.outputs.labels || steps.resolve_dispatch.outputs.labels }} + run: | + # Whichever of the two prior steps ran populated its outputs; the + # other was skipped and contributes empty strings. Pick whichever + # one actually ran. + if [[ "${{ github.event_name }}" == "pull_request_target" ]]; then + SRC="event" + else + SRC="dispatch" + fi + { + echo "pr_number=${{ steps.resolve_event.outputs.pr_number || steps.resolve_dispatch.outputs.pr_number }}" + echo "event_action=${{ steps.resolve_event.outputs.event_action || steps.resolve_dispatch.outputs.event_action }}" + echo "event_label=${RESOLVED_EVENT_LABEL}" + echo "merged=${{ steps.resolve_event.outputs.merged || steps.resolve_dispatch.outputs.merged }}" + echo "base_ref=${{ steps.resolve_event.outputs.base_ref || steps.resolve_dispatch.outputs.base_ref }}" + echo "labels=${RESOLVED_LABELS}" + echo "merge_commit_sha=${{ steps.resolve_event.outputs.merge_commit_sha || steps.resolve_dispatch.outputs.merge_commit_sha }}" + echo "pr_title=${RESOLVED_PR_TITLE}" + } >> "${GITHUB_OUTPUT}" + echo "Resolved PR context from: ${SRC}" + + # Second job: extract all hotfix versions from the PR labels and emit them as # a JSON array so the matrix strategy can fan out one job per version. detect-versions: + needs: resolve-pr runs-on: ubuntu-latest # Only fire for merged PRs targeting the default branch that have at least # one "Hotfix *" label. The default-branch guard prevents recursive # cherry-picks when a cherry-pick PR is merged into a release branch. if: >- - github.event.pull_request.merged == true && - github.event.pull_request.base.ref == github.event.repository.default_branch && - join(github.event.pull_request.labels.*.name, ' ') != '' && - contains(join(github.event.pull_request.labels.*.name, ','), 'Hotfix ') + needs.resolve-pr.outputs.merged == 'true' && + needs.resolve-pr.outputs.base_ref == github.event.repository.default_branch && + needs.resolve-pr.outputs.labels != '' && + contains(needs.resolve-pr.outputs.labels, 'Hotfix ') outputs: versions: ${{ steps.extract.outputs.versions }} steps: @@ -67,19 +183,20 @@ jobs: id: extract env: # Pass label names via env to avoid script injection from label text. - LABELS: ${{ join(github.event.pull_request.labels.*.name, ',') }} + LABELS: ${{ needs.resolve-pr.outputs.labels }} # For the 'labeled' event, this is the single label that was just added. - # For the 'closed' event this is empty, meaning all labels are processed. - EVENT_LABEL: ${{ github.event.label.name || '' }} - EVENT_ACTION: ${{ github.event.action }} + # For the 'closed'/'reconcile' events this is empty, meaning all + # labels are processed (see extract-hotfix-versions.sh OVERVIEW). + EVENT_LABEL: ${{ needs.resolve-pr.outputs.event_label }} + EVENT_ACTION: ${{ needs.resolve-pr.outputs.event_action }} GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} - PR_NUMBER: ${{ github.event.pull_request.number }} + PR_NUMBER: ${{ needs.resolve-pr.outputs.pr_number }} run: bash "${GITHUB_WORKSPACE}/.github/scripts/extract-hotfix-versions.sh" - # Second job: runs once per detected version, cherry-picking the merge commit + # Third job: runs once per detected version, cherry-picking the merge commit # into each target release branch. cherry-pick: - needs: detect-versions + needs: [resolve-pr, detect-versions] if: needs.detect-versions.outputs.versions != '[]' runs-on: ubuntu-latest strategy: @@ -106,8 +223,8 @@ jobs: - name: Cherry-pick and create PR env: GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} - MERGE_COMMIT_SHA: ${{ github.event.pull_request.merge_commit_sha }} - PR_NUMBER: ${{ github.event.pull_request.number }} - PR_TITLE: ${{ github.event.pull_request.title }} + MERGE_COMMIT_SHA: ${{ needs.resolve-pr.outputs.merge_commit_sha }} + PR_NUMBER: ${{ needs.resolve-pr.outputs.pr_number }} + PR_TITLE: ${{ needs.resolve-pr.outputs.pr_title }} VERSION: ${{ matrix.version }} run: bash "${GITHUB_WORKSPACE}/.github/scripts/cherry-pick-to-release.sh" diff --git a/.github/workflows/close-backport-issue.yml b/.github/workflows/close-backport-issue.yml new file mode 100644 index 0000000000..9115f3d8c5 --- /dev/null +++ b/.github/workflows/close-backport-issue.yml @@ -0,0 +1,68 @@ +################################################################################# +# Licensed to the .NET Foundation under one or more agreements. # +# The .NET Foundation licenses this file to you under the MIT license. # +# See the LICENSE file in the project root for more information. # +################################################################################# +# +# Close Backport Issue on Release-Branch Merge +# +# Companion to hotfix-label-issue.yml, sync-hotfix-label-to-pr.yml, and +# cherry-pick-hotfix.yml. Works together to automate backporting a fix from +# an issue through to a merged cherry-pick PR. +# +# GitHub only auto-closes an issue referenced by a PR's closing keywords +# (Fixes/Closes/Resolves #N) when that PR merges into the repository's +# default branch, and doesn't even populate the issue's cross-reference for +# non-default-branch PRs. The cherry-pick PRs opened by cherry-pick-hotfix.yml +# always target a release/X.Y branch, so this workflow closes that gap by +# reading the backport issue number(s) that cherry-pick-to-release.sh records +# in the PR body and closing each one explicitly once the PR merges. +# +################################################################################# + +name: Close Backport Issue on Release-Branch Merge + +# 'pull_request_target' (rather than 'pull_request') is required so the +# workflow has write access to close issues. The job's 'if' condition below +# restricts execution to same-repository automation branches, so this write +# access is never exercised for a fork PR despite the trigger supporting them. +on: + pull_request_target: + types: [closed] + +permissions: + contents: read + pull-requests: read + issues: write + +jobs: + close-backport-issue: + # Only fire for merged PRs targeting a release branch, opened from this + # same repository (never a fork), on a branch matching the naming + # convention cherry-pick-to-release.sh always uses for the branches it + # creates and pushes ("dev/automation/pr-<N>-to-<version>"). The + # "backport-issue-numbers" marker in the PR body is otherwise just text + # any PR author could include, and this job runs as 'pull_request_target' + # with 'issues: write' -- without this restriction, a merged fork PR + # carrying a forged marker could close arbitrary issues. Requiring both + # a same-repo head and the automation's exact branch prefix ensures this + # only ever fires for PRs our own automation created. + if: >- + github.event.pull_request.merged == true && + startsWith(github.event.pull_request.base.ref, 'release/') && + github.event.pull_request.head.repo.full_name == github.repository && + startsWith(github.event.pull_request.head.ref, 'dev/automation/pr-') + runs-on: ubuntu-latest + steps: + - name: Checkout repository + uses: actions/checkout@v6 + with: + # Only the scripts directory is needed; skip full history. + sparse-checkout: .github/scripts + sparse-checkout-cone-mode: false + + - name: Close referenced issue(s) + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + PR_NUMBER: ${{ github.event.pull_request.number }} + run: bash "${GITHUB_WORKSPACE}/.github/scripts/close-backport-issue.sh" diff --git a/.github/workflows/hotfix-label-issue.yml b/.github/workflows/hotfix-label-issue.yml new file mode 100644 index 0000000000..4a86f13512 --- /dev/null +++ b/.github/workflows/hotfix-label-issue.yml @@ -0,0 +1,68 @@ +################################################################################# +# Licensed to the .NET Foundation under one or more agreements. # +# The .NET Foundation licenses this file to you under the MIT license. # +# See the LICENSE file in the project root for more information. # +################################################################################# +# +# Create Backport Issue for Hotfix Label +# +# Companion to cherry-pick-hotfix.yml, but for issues instead of PRs. Works +# together with sync-hotfix-label-to-pr.yml, cherry-pick-hotfix.yml, and +# close-backport-issue.yml to automate backporting a fix from an issue +# through to a merged cherry-pick PR. +# +# When an issue is labeled "Hotfix <version>", this workflow creates a child +# issue targeting the <version> milestone and links it as a native GitHub +# sub-issue of the parent. That child issue is the "backport issue": +# +# 1. Label a bug issue "Hotfix 7.1.1". +# 2. This workflow creates "[7.1.1] <original title>", milestoned 7.1.1, as +# a sub-issue of the original. +# 3. sync-hotfix-label-to-pr.yml copies the "Hotfix 7.1.1" label onto any PR +# that closes the original issue. +# 4. cherry-pick-hotfix.yml auto-cherry-picks that merged PR to release/7.1 +# and links the resulting PR to the backport issue created here. +# 5. close-backport-issue.yml explicitly closes the backport issue once +# that cherry-pick PR merges into release/7.1, since GitHub's closing +# keywords only auto-close issues for merges into the default branch. +# +################################################################################# + +name: Create Backport Issue for Hotfix Label + +on: + issues: + types: [labeled] + +permissions: + contents: read + issues: write + +jobs: + create-backport-issue: + # Only run for a label that looks like "Hotfix X.Y.Z" — the script itself + # re-validates this, but the guard avoids spinning up a job for every + # unrelated label (bug, enhancement, etc.). + if: startsWith(github.event.label.name, 'Hotfix ') + runs-on: ubuntu-latest + # Duplicate detection (Step 2 of create-backport-issue.sh) is a + # check-then-create sequence with no atomic guard of its own. Serialize + # runs per issue+label so a second delivery/re-run for the same pair + # always re-checks after the first has finished creating and linking its + # child, instead of racing past the still-empty duplicate check. + concurrency: + group: hotfix-label-issue-${{ github.event.issue.number }}-${{ github.event.label.name }} + steps: + - name: Checkout repository + uses: actions/checkout@v6 + with: + # Only the scripts directory is needed; skip full history. + sparse-checkout: .github/scripts + sparse-checkout-cone-mode: false + + - name: Create backport issue + env: + EVENT_LABEL: ${{ github.event.label.name }} + PARENT_ISSUE_NUMBER: ${{ github.event.issue.number }} + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: bash "${GITHUB_WORKSPACE}/.github/scripts/create-backport-issue.sh" diff --git a/.github/workflows/sync-hotfix-label-to-pr.yml b/.github/workflows/sync-hotfix-label-to-pr.yml new file mode 100644 index 0000000000..61dc7dd9bc --- /dev/null +++ b/.github/workflows/sync-hotfix-label-to-pr.yml @@ -0,0 +1,88 @@ +################################################################################# +# Licensed to the .NET Foundation under one or more agreements. # +# The .NET Foundation licenses this file to you under the MIT license. # +# See the LICENSE file in the project root for more information. # +################################################################################# +# +# Sync Hotfix Label from Issue to PR +# +# Companion to hotfix-label-issue.yml, cherry-pick-hotfix.yml, and +# close-backport-issue.yml. Works together to automate backporting a fix from +# an issue through to a merged cherry-pick PR. +# +# When a pull request's closing keywords (Fixes/Closes/Resolves #N) reference +# an issue that carries a "Hotfix X.Y.Z" label, this workflow copies that +# label onto the PR. That's the label cherry-pick-hotfix.yml watches for, so +# a PR fixing a hotfix-tagged issue is automatically cherry-picked once merged +# without anyone having to remember to label the PR by hand. +# +# Runs both directions so ordering doesn't matter: +# - PR opened/edited/synced: sync-hotfix-label-to-pr.sh copies Hotfix +# label(s) from the issue(s) it closes onto the PR. +# - Issue labeled "Hotfix X.Y.Z" (possibly after its closing PR is already +# open): sync-hotfix-label-from-issue.sh finds that PR via +# 'closedByPullRequestsReferences' and re-runs the same sync. +# +################################################################################# + +name: Sync Hotfix Label from Issue to PR + +# 'pull_request_target' (rather than 'pull_request') is required so the +# workflow has write access to add labels, including for PRs from forks. +# +# 'issues: [labeled]' covers the timing gap the PR events alone miss: if an +# issue is labeled "Hotfix X.Y.Z" after its closing PR is already open, and +# that PR doesn't receive another opened/edited/synchronize event, the +# pull_request_target trigger never fires again to copy the label. +on: + pull_request_target: + types: [opened, reopened, edited, synchronize] + issues: + types: [labeled] + +permissions: + contents: read + pull-requests: write + issues: write + # 'actions: write' is needed by sync-hotfix-label-from-issue.sh to dispatch + # cherry-pick-hotfix.yml (workflow_dispatch) for already-merged PRs, since + # adding a label via this workflow's own GITHUB_TOKEN doesn't fire a new + # 'labeled' webhook event for that workflow to react to on its own. + actions: write + +jobs: + sync-hotfix-label-from-pr: + if: github.event_name == 'pull_request_target' && github.event.pull_request.state == 'open' + runs-on: ubuntu-latest + steps: + - name: Checkout repository + uses: actions/checkout@v6 + with: + # Only the scripts directory is needed; skip full history. + sparse-checkout: .github/scripts + sparse-checkout-cone-mode: false + + - name: Sync Hotfix label from referenced issue(s) + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + PR_NUMBER: ${{ github.event.pull_request.number }} + run: bash "${GITHUB_WORKSPACE}/.github/scripts/sync-hotfix-label-to-pr.sh" + + sync-hotfix-label-from-issue: + if: >- + github.event_name == 'issues' && + startsWith(github.event.label.name, 'Hotfix ') + runs-on: ubuntu-latest + steps: + - name: Checkout repository + uses: actions/checkout@v6 + with: + # Only the scripts directory is needed; skip full history. + sparse-checkout: .github/scripts + sparse-checkout-cone-mode: false + + - name: Sync Hotfix label onto PR(s) closing this issue + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + ISSUE_NUMBER: ${{ github.event.issue.number }} + run: bash "${GITHUB_WORKSPACE}/.github/scripts/sync-hotfix-label-from-issue.sh"