blob: 073889238bd1ac6fa7504336d75d7c45e6445d66 [file]
# Copyright 2026 The Flutter Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
# Privileged half of the pull request labeler.
#
# Edit `.github/labeler.yml` to configure labels.
#
# Runs after `labeler-trigger.yml` completes. The artifact produced by that
# workflow is UNTRUSTED (a pull request can modify the trigger workflow), so the
# PR number is only used after binding it to the triggering run's head commit.
# The label configuration is read from the default branch, not the PR. Before
# applying labels, it waits for the `cla/google` check run to complete; if the
# CLA check fails, it skips labeling and moves the PR to a draft state.
#
# Pull requests from first-time contributors need a maintainer to approve their
# `pull_request` runs. Until then, the trigger run is created already concluded
# as `action_required`, without running anything or uploading an artifact. That
# run fires the `requested` event (but not `completed`), so on `requested` with
# `action_required` the PR is looked up from the run's head branch and SHA
# instead. Otherwise those PRs would not be labeled until approved, and would
# not show up in the triage queries where maintainers find runs to approve.
name: Pull Request Labeler
on:
# Safe because this only consumes an artifact from the triggering run as
# untrusted data (validated and bound to the PR's head SHA); no PR code is
# checked out or executed.
workflow_run: # zizmor: ignore[dangerous-triggers]
workflows: [Pull Request Labeler Trigger]
types: [requested, completed]
# Declare default permissions as read only.
permissions:
contents: read
jobs:
triage:
if: >-
github.repository == 'flutter/packages' &&
github.event.workflow_run.event == 'pull_request' &&
github.event.workflow_run.path == '.github/workflows/labeler-trigger.yml' &&
((github.event.action == 'completed' && github.event.workflow_run.conclusion == 'success') ||
(github.event.action == 'requested' && github.event.workflow_run.conclusion == 'action_required'))
permissions:
actions: read
checks: read
# Required by the convertPullRequestToDraft GraphQL mutation.
contents: write
pull-requests: write
runs-on: ubuntu-latest
steps:
- name: Download labeler metadata
if: github.event.action == 'completed'
uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
with:
name: labeler-metadata
path: ${{ runner.temp }}/labeler-metadata
run-id: ${{ github.event.workflow_run.id }}
github-token: ${{ github.token }}
- name: Validate PR
id: validate
env:
EVENT_ACTION: ${{ github.event.action }}
GH_TOKEN: ${{ github.token }}
REPO: ${{ github.repository }}
RUN_HEAD_BRANCH: ${{ github.event.workflow_run.head_branch }}
RUN_HEAD_OWNER: ${{ github.event.workflow_run.head_repository.owner.login }}
RUN_HEAD_REPO: ${{ github.event.workflow_run.head_repository.full_name }}
RUN_HEAD_SHA: ${{ github.event.workflow_run.head_sha }}
run: |
set -euo pipefail
if [ "$EVENT_ACTION" = "requested" ]; then
# Awaiting approval: no artifact, so find the open PR for the run's
# head branch. This only uses data from GitHub's event payload.
PR_NUMBER=$(gh api -X GET "repos/$REPO/pulls" \
-f state=open -f head="$RUN_HEAD_OWNER:$RUN_HEAD_BRANCH" |
jq -r --arg sha "$RUN_HEAD_SHA" '[.[] | select(.head.sha == $sha)] | .[0].number // empty')
if [ -z "$PR_NUMBER" ]; then
echo "::notice::No open PR found for $RUN_HEAD_OWNER:$RUN_HEAD_BRANCH at $RUN_HEAD_SHA; skipping."
exit 0
fi
else
PR_NUMBER=$(jq -r '.pr_number // empty' "$RUNNER_TEMP/labeler-metadata/metadata.json")
fi
if ! [[ "$PR_NUMBER" =~ ^[1-9][0-9]*$ ]]; then
echo "::error::Invalid PR number."
exit 1
fi
# Bind the PR number to the pull request that actually triggered the run.
gh api "repos/$REPO/pulls/$PR_NUMBER" > "$RUNNER_TEMP/pr.json"
if [ "$(jq -r '.head.sha' "$RUNNER_TEMP/pr.json")" != "$RUN_HEAD_SHA" ] ||
[ "$(jq -r '.head.repo.full_name // empty' "$RUNNER_TEMP/pr.json")" != "$RUN_HEAD_REPO" ]; then
# Most likely a newer push; its own run will label the PR.
echo "::notice::PR #$PR_NUMBER has changed since the trigger ran; skipping."
exit 0
fi
echo "pr_number=$PR_NUMBER" >> "$GITHUB_OUTPUT"
- name: Check CLA
id: cla
if: steps.validate.outputs.pr_number != ''
env:
GH_TOKEN: ${{ github.token }}
PR_NUMBER: ${{ steps.validate.outputs.pr_number }}
REPO: ${{ github.repository }}
RUN_HEAD_SHA: ${{ github.event.workflow_run.head_sha }}
run: |
set -euo pipefail
CLA_STATUS=""
CLA_CONCLUSION=""
for attempt in $(seq 1 12); do
CHECK_JSON=$(gh api -X GET "repos/$REPO/commits/$RUN_HEAD_SHA/check-runs" \
-f check_name="cla/google" -f filter="latest")
CLA_STATUS=$(echo "$CHECK_JSON" | jq -r '.check_runs[0].status // empty')
CLA_CONCLUSION=$(echo "$CHECK_JSON" | jq -r '.check_runs[0].conclusion // empty')
if [ "$CLA_STATUS" = "completed" ]; then
break
fi
echo "Waiting for cla/google check run to complete (attempt $attempt/12, status: ${CLA_STATUS:-not found})..."
sleep 5
done
if [ "$CLA_STATUS" != "completed" ]; then
echo "::warning::cla/google check run did not complete within 60 seconds (status: ${CLA_STATUS:-not found}); skipping labeling."
echo "cla_passed=false" >> "$GITHUB_OUTPUT"
exit 0
fi
if [ "$CLA_CONCLUSION" = "success" ]; then
echo "cla/google check passed."
echo "cla_passed=true" >> "$GITHUB_OUTPUT"
exit 0
fi
echo "::notice::cla/google check concluded with '$CLA_CONCLUSION' on PR #$PR_NUMBER; skipping labeling."
echo "cla_passed=false" >> "$GITHUB_OUTPUT"
# Re-fetch PR state in case it was closed or converted to draft while waiting.
PR_JSON=$(gh api "repos/$REPO/pulls/$PR_NUMBER")
if [ "$(echo "$PR_JSON" | jq -r '.state')" != "open" ] ||
[ "$(echo "$PR_JSON" | jq -r '.draft')" = "true" ]; then
exit 0
fi
echo "Converting PR #$PR_NUMBER to draft..."
gh pr ready "$PR_NUMBER" -R "$REPO" --undo
gh pr edit "$PR_NUMBER" -R "$REPO" --add-label "waiting for response"
COMMENT_BODY="This pull request has been moved to a draft state because the \`cla/google\` check failed. Once you have signed the CLA and the \`cla/google\` check is passing, please mark this pull request as **Ready for review**."
ALREADY_COMMENTED=$(gh api --paginate "repos/$REPO/issues/$PR_NUMBER/comments" |
jq -sr --arg body "$COMMENT_BODY" '[.[][] | select(.body == $body)] | length > 0')
if [ "$ALREADY_COMMENTED" != "true" ]; then
gh pr comment "$PR_NUMBER" -R "$REPO" --body "$COMMENT_BODY"
fi
# Source available at https://github.com/actions/labeler/blob/main/README.md
- uses: actions/labeler@b8dd2d9be0f68b860e7dae5dae7d772984eacd6d # v6.2.0
if: steps.validate.outputs.pr_number != '' && steps.cla.outputs.cla_passed == 'true'
with:
pr-number: ${{ steps.validate.outputs.pr_number }}
sync-labels: true
- name: Apply priority label from closing issues
if: steps.validate.outputs.pr_number != '' && steps.cla.outputs.cla_passed == 'true'
env:
GH_TOKEN: ${{ github.token }}
PR_NUMBER: ${{ steps.validate.outputs.pr_number }}
REPO: ${{ github.repository }}
run: |
set -euo pipefail
ISSUE_URLS=$(gh pr view "$PR_NUMBER" --repo "$REPO" --json closingIssuesReferences \
--jq '.closingIssuesReferences[].url')
if [ -z "$ISSUE_URLS" ]; then
exit 0
fi
PRIORITIES=""
for ISSUE_URL in $ISSUE_URLS; do
ISSUE_PRIORITIES=$(gh issue view "$ISSUE_URL" --json labels \
--jq '.labels[].name | select(test("^P[0-3]$"))' || true)
if [ -n "$ISSUE_PRIORITIES" ]; then
PRIORITIES=$(printf '%s\n%s' "$PRIORITIES" "$ISSUE_PRIORITIES")
fi
done
# P0..P3 sort lexicographically from highest (P0) to lowest (P3) priority.
HIGHEST_PRIORITY=$(printf '%s\n' "$PRIORITIES" | grep -E '^P[0-3]$' | sort | head -n 1 || true)
if [ -z "$HIGHEST_PRIORITY" ]; then
exit 0
fi
# Remove any other P0..P3 labels already on the PR before applying the highest priority.
EXISTING_PRIORITIES=$(jq -r '.labels[].name | select(test("^P[0-3]$"))' "$RUNNER_TEMP/pr.json")
for LABEL in $EXISTING_PRIORITIES; do
if [ "$LABEL" != "$HIGHEST_PRIORITY" ]; then
gh pr edit "$PR_NUMBER" --repo "$REPO" --remove-label "$LABEL"
fi
done
if ! printf '%s\n' "$EXISTING_PRIORITIES" | grep -qx "$HIGHEST_PRIORITY"; then
gh pr edit "$PR_NUMBER" --repo "$REPO" --add-label "$HIGHEST_PRIORITY"
fi
- name: Check PR template
if: steps.validate.outputs.pr_number != '' && steps.cla.outputs.cla_passed == 'true'
env:
GH_TOKEN: ${{ github.token }}
PR_NUMBER: ${{ steps.validate.outputs.pr_number }}
REPO: ${{ github.repository }}
run: |
set -euo pipefail
# 1. Skip if already a draft or closed.
IS_DRAFT=$(jq -r '.draft' "$RUNNER_TEMP/pr.json")
STATE=$(jq -r '.state' "$RUNNER_TEMP/pr.json")
if [ "$IS_DRAFT" = "true" ] || [ "$STATE" != "open" ]; then
echo "::notice::PR #$PR_NUMBER is already a draft or closed; skipping template check."
exit 0
fi
# 2. Skip bots and organization members / collaborators.
USER_TYPE=$(jq -r '.user.type' "$RUNNER_TEMP/pr.json")
AUTHOR=$(jq -r '.user.login' "$RUNNER_TEMP/pr.json")
ASSOC=$(jq -r '.author_association' "$RUNNER_TEMP/pr.json")
if [ "$USER_TYPE" = "Bot" ]; then
echo "::notice::Skipping bot author $AUTHOR."
exit 0
fi
if [[ "$ASSOC" == "MEMBER" || "$ASSOC" == "OWNER" || "$ASSOC" == "COLLABORATOR" ]]; then
echo "::notice::Author $AUTHOR is an org member/collaborator; skipping template check."
exit 0
fi
# GITHUB_TOKEN cannot see private org membership in author_association
# or team-granted access via /collaborators/{username}, so also check
# effective repository permissions across teams via /permission.
if ! PERM_JSON=$(gh api "repos/$REPO/collaborators/$AUTHOR/permission"); then
echo "::error::Failed to query repository permission for $AUTHOR."
exit 1
fi
PERMISSION=$(jq -r '.permission // empty' <<<"$PERM_JSON")
ROLE_NAME=$(jq -r '.role_name // empty' <<<"$PERM_JSON")
if [[ "$PERMISSION" == "admin" || "$PERMISSION" == "write" || "$ROLE_NAME" == "triage" ]]; then
echo "::notice::Author $AUTHOR has '$ROLE_NAME' ($PERMISSION) access; skipping template check."
exit 0
fi
# 3. Validate the PR description against .github/PULL_REQUEST_TEMPLATE.md.
TEMPLATE=$(gh api "repos/$REPO/contents/.github/PULL_REQUEST_TEMPLATE.md" \
-H "Accept: application/vnd.github.raw" | tr -d '\r')
CHECKLIST_MARKDOWN=$(sed -n '/^## Pre-Review Checklist/,$p' <<<"$TEMPLATE")
EXPECTED_ITEMS=()
while IFS= read -r line; do
EXPECTED_ITEMS+=("$line")
done < <(grep -E '^-[[:space:]]*\[ \][[:space:]]+' <<<"$TEMPLATE" |
sed -E 's/^-[[:space:]]*\[ \][[:space:]]+//; s/[[:space:]]*$//')
if [ "${#EXPECTED_ITEMS[@]}" -eq 0 ]; then
echo "::error::Failed to parse checklist items from .github/PULL_REQUEST_TEMPLATE.md."
exit 1
fi
# Normalize checklist text so minor formatting differences (e.g. resolved
# or struck-through "or" clauses, inlined links, removed footnote markers,
# or trailing punctuation differences) do not trigger false positives.
normalize_stream() {
sed -E '
s/,?[[:space:]]*or[[:space:]]+~~[^~]+~~//g;
s/~~[^~]+,[[:space:]]*or~~[[:space:]]*//g;
s/~~[^~]+~~,?[[:space:]]*or[[:space:]]+//g;
s/~~//g;
s/\]\([^)]*\)/]/g;
s/\[\^[0-9]+\]//g;
s/\[[0-9]+\]//g;
' | tr -d '[]' | tr '[:upper:]' '[:lower:]' | sed -E '
s/[[:space:]]+/ /g;
s/^[[:space:]]+//;
s/[.,;:[:space:]]+$//
'
}
matches_item() {
local haystack="$1"
local item="$2"
[ -z "$haystack" ] && return 1
local candidates=("$item")
if [[ "$item" == *", or "* ]]; then
candidates+=("${item%%, or *}" "${item#*, or }")
fi
local candidate norm_candidate
for candidate in "${candidates[@]}"; do
norm_candidate=$(normalize_stream <<<"$candidate")
if grep -Fxq -- "$norm_candidate" <<<"$haystack"; then
return 0
fi
done
return 1
}
BODY=$(jq -r '.body // ""' "$RUNNER_TEMP/pr.json" | tr -d '\r')
NORMALIZED_CHECKED=$(
sed -nE 's/^[[:space:]]*[-*+][[:space:]]*\[[[:space:]]*[xX][[:space:]]*\][[:space:]]+//p' <<<"$BODY" |
normalize_stream
)
NORMALIZED_UNCHECKED=$(
sed -nE 's/^[[:space:]]*[-*+][[:space:]]*\[[[:space:]]*\][[:space:]]+//p' <<<"$BODY" |
normalize_stream
)
TOTAL_COUNT="${#EXPECTED_ITEMS[@]}"
MISSING_ITEMS=()
UNCHECKED_ITEMS=()
for item in "${EXPECTED_ITEMS[@]}"; do
if matches_item "$NORMALIZED_CHECKED" "$item"; then
continue
elif matches_item "$NORMALIZED_UNCHECKED" "$item"; then
UNCHECKED_ITEMS+=("$item")
else
MISSING_ITEMS+=("$item")
fi
done
MISSING_COUNT="${#MISSING_ITEMS[@]}"
UNCHECKED_COUNT="${#UNCHECKED_ITEMS[@]}"
REASONS=()
if [ "$MISSING_COUNT" -eq "$TOTAL_COUNT" ]; then
REASONS+=("- **Missing Pre-Review Checklist:** The **Pre-Review Checklist** from the [PR template](https://github.com/flutter/packages/blob/main/.github/PULL_REQUEST_TEMPLATE.md) is missing from the PR description.")
elif [ "$MISSING_COUNT" -gt 0 ]; then
MISSING_LIST=$(printf ' - `` - [ ] %s ``\n' "${MISSING_ITEMS[@]}")
REASONS+=("$(printf -- '- **Missing or modified checklist items (%d of %d):** The following expected items were not found in the PR description (please keep the original checklist text without deleting or rewording items):\n%s' "$MISSING_COUNT" "$TOTAL_COUNT" "$MISSING_LIST")")
fi
if [ "$UNCHECKED_COUNT" -gt 0 ]; then
UNCHECKED_LIST=$(printf ' - `` - [ ] %s ``\n' "${UNCHECKED_ITEMS[@]}")
REASONS+=("$(printf -- '- **Unchecked checklist items (%d of %d):** All items in the **Pre-Review Checklist** must be completed and checked off (`- [x]`) before the PR can be reviewed:\n%s' "$UNCHECKED_COUNT" "$TOTAL_COUNT" "$UNCHECKED_LIST")")
fi
PLACEHOLDERS=()
if grep -Fq "*Replace this paragraph with a description of what this PR is changing or adding" <<<"$BODY"; then
PLACEHOLDERS+=("*Replace this paragraph with a description of what this PR is changing or adding, and why. Consider including before/after screenshots.*")
fi
if grep -Fq "*List which issues are fixed by this PR. You must list at least one issue.*" <<<"$BODY"; then
PLACEHOLDERS+=("*List which issues are fixed by this PR. You must list at least one issue.*")
fi
if [ "${#PLACEHOLDERS[@]}" -gt 0 ]; then
PLACEHOLDER_LIST=$(printf ' - `%s`\n' "${PLACEHOLDERS[@]}")
REASONS+=("$(printf -- '- **Unreplaced placeholder text:** Please replace the template placeholder text at the top of the PR description with your actual description and linked issue(s):\n%s' "$PLACEHOLDER_LIST")")
fi
if [ "${#REASONS[@]}" -eq 0 ]; then
echo "::notice::PR #$PR_NUMBER passed template validation."
exit 0
fi
# 4. Convert the PR to a draft via GraphQL and add the "waiting for response" label.
PR_NODE_ID=$(jq -r '.node_id' "$RUNNER_TEMP/pr.json")
gh api graphql -f query='
mutation($id: ID!) {
convertPullRequestToDraft(input: {pullRequestId: $id}) {
pullRequest { isDraft }
}
}
' -f id="$PR_NODE_ID"
gh pr edit "$PR_NUMBER" -R "$REPO" --add-label "waiting for response"
# 5. Post or update the nudge comment.
MARKER="<!-- pr-template-check -->"
REASONS_TEXT=$(printf '%s\n' "${REASONS[@]}")
COMMENT_BODY=$(printf '%s\n\nHi @%s, thank you for your contribution!\n\nThis pull request has been converted to a **draft** because it does not appear to follow our [pull request template](https://github.com/flutter/packages/blob/main/.github/PULL_REQUEST_TEMPLATE.md):\n\n%s\n\n### How to fix this\n\n1. Click the **`...`** menu in the top-right corner of your PR description above and select **Edit**.\n2. Address the issues listed above. Make sure every item in the **Pre-Review Checklist** is present without modifications and checked off (`- [x]`).\n3. Save your changes, then click the **"Ready for review"** button at the bottom of the PR.\n\n<details>\n<summary>Click here for the raw Markdown of the Pre-Review Checklist to copy and paste</summary>\n\n````markdown\n%s\n````\n\n</details>\n' \
"$MARKER" "$AUTHOR" "$REASONS_TEXT" "$CHECKLIST_MARKDOWN")
EXISTING_COMMENT_ID=$(gh api --paginate "repos/$REPO/issues/$PR_NUMBER/comments" |
jq -s -r --arg marker "$MARKER" '[add[] | select((.body // "") | contains($marker))][0].id // empty')
if [ -n "$EXISTING_COMMENT_ID" ]; then
gh api -X PATCH "repos/$REPO/issues/comments/$EXISTING_COMMENT_ID" \
-f body="$COMMENT_BODY"
else
gh api -X POST "repos/$REPO/issues/$PR_NUMBER/comments" \
-f body="$COMMENT_BODY"
fi