|
| 1 | +# This workflow automatically applies labels from issues to pull requests that reference them. |
| 2 | +name: Sync issue labels to PR |
| 3 | + |
| 4 | +on: |
| 5 | + pull_request: |
| 6 | + types: [opened, edited, reopened, synchronize, ready_for_review] |
| 7 | + |
| 8 | +permissions: |
| 9 | + pull-requests: write |
| 10 | + contents: read |
| 11 | + issues: read |
| 12 | + |
| 13 | +jobs: |
| 14 | + sync: |
| 15 | + runs-on: ubuntu-latest |
| 16 | + steps: |
| 17 | + - name: Apply issue labels to PR |
| 18 | + uses: actions/github-script@v7 |
| 19 | + with: |
| 20 | + script: | |
| 21 | + const {owner, repo} = context.repo; |
| 22 | + const prNumber = context.payload.pull_request.number; |
| 23 | +
|
| 24 | + // 1) Find issues linked to this PR (those it will close) |
| 25 | + const query = ` |
| 26 | + query($owner:String!, $repo:String!, $number:Int!) { |
| 27 | + repository(owner:$owner, name:$repo) { |
| 28 | + pullRequest(number:$number) { |
| 29 | + closingIssuesReferences(first: 50) { |
| 30 | + nodes { |
| 31 | + number |
| 32 | + labels(first: 100) { nodes { name } } |
| 33 | + } |
| 34 | + } |
| 35 | + } |
| 36 | + } |
| 37 | + } |
| 38 | + `; |
| 39 | + const data = await github.graphql(query, { owner, repo, number: prNumber }); |
| 40 | + const issues = data.repository.pullRequest.closingIssuesReferences.nodes; |
| 41 | +
|
| 42 | + // 2) Collect unique label names from those issues |
| 43 | + const labelSet = new Set(); |
| 44 | + for (const is of issues) { |
| 45 | + for (const l of is.labels.nodes) labelSet.add(l.name); |
| 46 | + } |
| 47 | +
|
| 48 | + // Optional: ignore labels you don't want copied |
| 49 | + const IGNORE = new Set(["enhancement", "science", "bug", "documentation", "question", "good first issue", "help wanted"]); |
| 50 | + const labels = Array.from(labelSet).filter(x => !IGNORE.has(x)); |
| 51 | +
|
| 52 | + // 3) Apply to the PR (PRs are "issues" in the REST API) |
| 53 | + if (labels.length) { |
| 54 | + await github.rest.issues.addLabels({ |
| 55 | + owner, repo, |
| 56 | + issue_number: prNumber, |
| 57 | + labels |
| 58 | + }); |
| 59 | + core.info(`Applied labels to PR ${prNumber}: ${labels.join(", ")}`); |
| 60 | + } else { |
| 61 | + core.info("No labels to apply from linked issues."); |
| 62 | + } |
0 commit comments