Skip to content

Commit fe546ac

Browse files
committed
github/workflow: Sync the new PR Labeling Workflow from NuttX Repo to NuttX Apps
This PR replicates the new PR Labeling Workflow from NuttX Repo to NuttX Apps Repo. For Future Syncing: - Copy from NuttX Repo to NuttX Apps: `.github/workflows/labeler.yml` and `.github/workflows/pr_labeler.yml` - Edit `.github/workflows/labeler.yml` and change `repository: apache/nuttx` to `repository: apache/nuttx-apps` - Don't overwrite `.github/labeler.yml` by NuttX Repo The new workflow reimplements PR Labeling with two triggers: pull_request and workflow_run. We no longer need pull_request_target, which is an unsafe trigger and may introduce security vulnerabilities. The New PR Labeler is explained here: - https://lupyuen.org/articles/prtarget - apache/nuttx#18359 Modified Files: `.github/workflows/labeler.yml`: Changed the (read-write) pull_request_target trigger to (read-only) pull_request trigger. Compute the Size Label (e.g. Size: XS) and Arch Labels (e.g. Area: Examples). Save the PR Labels into a PR Artifact. `.github/labeler.yml`: Added comment to clarify that NuttX PR Labeler only supports a subset of the `actions/labeler` syntax: `changed-files` and `any-glob-to-any-file`. Note: Don't overwrite this file by NuttX Repo. New Files: `.github/workflows/pr_labeler.yml`: Contains the workflow_run trigger, which is executed upon completion of the pull_request trigger. Download the PR Labels from the PR Artifact. Write the PR Labels into the PR. Signed-off-by: Lup Yuen Lee <luppy@appkaki.com>
1 parent 448b0bd commit fe546ac

3 files changed

Lines changed: 216 additions & 18 deletions

File tree

.github/labeler.yml

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,9 @@
1717
# specific language governing permissions and limitations
1818
# under the License.
1919
#
20+
# Note: NuttX PR Labeler only supports a subset of the
21+
# `actions/labeler` syntax: `changed-files` and
22+
# `any-glob-to-any-file`. See .github/workflows/labeler.yml
2023

2124
# add arch labels
2225

.github/workflows/labeler.yml

Lines changed: 123 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -12,34 +12,139 @@
1212
# See the License for the specific language governing permissions and
1313
# limitations under the License.
1414
#
15+
# This workflow will fetch the updated PR filenames, compute the Size Label
16+
# and Arch Labels, then save the PR Labels into a PR Artifact. The
17+
# PR Labels will be written to the PR inside the "workflow_run" trigger
18+
# (pr_labeler.yml), because this "pull_request" trigger has read-only
19+
# permission. Don't use "pull_request_target", it's unsafe.
20+
# See https://cwiki.apache.org/confluence/pages/viewpage.action?pageId=321719166#GitHubActionsSecurity-Buildstriggeredwithpull_request_target
1521
name: "Pull Request Labeler"
1622
on:
17-
- pull_request_target
23+
- pull_request
1824

1925
jobs:
2026
labeler:
2127
permissions:
2228
contents: read
23-
pull-requests: write
24-
issues: write
29+
pull-requests: read
30+
issues: read
2531
runs-on: ubuntu-latest
2632
steps:
27-
- name: Checkout repository
28-
uses: actions/checkout@v6
33+
# Checkout one file from our trusted source: .github/labeler.yml
34+
# Never checkout and execute any untrusted code from the PR.
35+
- name: Checkout labeler config
36+
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
37+
with:
38+
repository: apache/nuttx-apps
39+
ref: master
40+
path: labeler
41+
fetch-depth: 1
42+
persist-credentials: false
43+
sparse-checkout: .github/labeler.yml
44+
sparse-checkout-cone-mode: false
2945

30-
- name: Assign labels based on paths
31-
uses: actions/labeler@main
46+
# Fetch the updated PR filenames. Compute the Size Label and Arch Labels.
47+
- name: Compute PR labels
48+
uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0
3249
with:
33-
repo-token: "${{ secrets.GITHUB_TOKEN }}"
34-
sync-labels: true
50+
github-token: ${{ secrets.GITHUB_TOKEN }}
51+
script: |
52+
const owner = context.repo.owner;
53+
const repo = context.repo.repo;
54+
const pull_number = context.issue.number;
55+
56+
// Fetch the array of updated PR filenames:
57+
// { status: 'added', filename: 'arch/arm/test.txt', additions: 3, deletions: 0, changes: 3 }
58+
// { status: 'removed', filename: 'Documentation/legacy_README.md', additions: 0, deletions: 2531, changes: 2531 }
59+
// { status: 'modified', filename: 'Documentation/security.rst', additions: 1, deletions: 0, changes: 1 }
60+
const listFilesOptions = github.rest.pulls.listFiles
61+
.endpoint.merge({ owner, repo, pull_number });
62+
const listFilesResponse = await github.paginate(listFilesOptions);
63+
64+
// Sum up the number of lines changed
65+
const sizeFiles = listFilesResponse
66+
.filter(f => (f.status != 'removed')); // Ignore deleted files
67+
var linesChanged = 0;
68+
for (const file of sizeFiles) {
69+
linesChanged += file.changes;
70+
}
71+
console.log({ linesChanged });
72+
73+
// Compute the Size Label
74+
const sizeLabel =
75+
(linesChanged <= 10) ? 'Size: XS'
76+
: (linesChanged <= 100) ? 'Size: S'
77+
: (linesChanged <= 500) ? 'Size: M'
78+
: (linesChanged <= 1000) ? 'Size: L'
79+
: 'Size: XL';
80+
var prLabels = [ sizeLabel ];
81+
82+
// Parse the Arch Label Patterns in .github/labeler.yml. Condense into:
83+
// "Arch: arm":
84+
// - any-glob-to-any-file: 'arch/arm/**'
85+
// - any-glob-to-any-file: ...
86+
const fs = require('fs');
87+
const config = fs.readFileSync('labeler/.github/labeler.yml', 'utf8')
88+
.split('\n') // Split by newline
89+
.map(s => s.trim()) // Remove leading and trailing spaces
90+
.filter(s => (s != '')) // Remove empty lines
91+
.filter(s => !s.startsWith('#')) // Remove comments
92+
.filter(s => !s.startsWith('- changed-files:')); // Remove "changed-files"
93+
94+
// Convert the Arch Label Patterns from config to archLabels.
95+
// archLabels will contain the mappings for Arch Label and Filename Pattern:
96+
// { label: "Arch: arm", pattern: "arch/arm/.*" },
97+
// { label: "Arch: arm64", pattern: "arch/arm64/.*" }, ...
98+
var archLabels = [];
99+
var label = "";
100+
for (const c of config) {
101+
// Get the Arch Label
102+
if (c.startsWith('"')) { // "Arch: arm":
103+
label = c.split('"')[1]; // Arch: arm
104+
105+
} else if (c.startsWith('- any-glob-to-any-file:')) { // - any-glob-to-any-file: 'arch/arm/**'
106+
// Convert the Glob Pattern to Regex Pattern
107+
const pattern = c.split("'")[1] // arch/arm/**
108+
.split('.').join('\\.') // . becomes \.
109+
.split('*').join('[^/]*') // * becomes [^/]*
110+
.split('[^/]*[^/]*').join('.*'); // ** becomes .*
111+
archLabels.push({
112+
label, // Arch: arm
113+
pattern: '^' + pattern + '$' // Match the Line Start and Line End
114+
});
115+
116+
} else {
117+
// We don't support all rules of `actions/labeler`
118+
throw new Error('.github/labeler.yml should contain only changed-files and any-glob-to-any-file, not: ' + c);
119+
}
120+
}
121+
122+
// Search the filenames for matching Arch Labels
123+
for (const archLabel of archLabels) {
124+
if (prLabels.includes(archLabel.label)) {
125+
break;
126+
}
127+
for (const file of listFilesResponse) {
128+
const re = new RegExp(archLabel.pattern);
129+
const match = re.test(file.filename);
130+
if (match && !prLabels.includes(archLabel.label)) {
131+
prLabels.push(archLabel.label);
132+
break;
133+
}
134+
}
135+
}
136+
console.log({ prLabels });
137+
138+
// Save the PR Number and PR Labels into a PR Artifact
139+
// e.g. 'Size: XS\nArch: avr\n'
140+
const dir = 'pr';
141+
fs.mkdirSync(dir);
142+
fs.writeFileSync(dir + '/pr-id.txt', pull_number + '\n');
143+
fs.writeFileSync(dir + '/pr-labels.txt', prLabels.join('\n') + '\n');
35144
36-
- name: Assign labels based on the PR's size
37-
uses: codelytv/pr-size-labeler@v1.10.3
145+
# Upload the PR Artifact as pr.zip
146+
- name: Upload PR artifact
147+
uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6.0.0
38148
with:
39-
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
40-
ignore_file_deletions: true
41-
xs_label: 'Size: XS'
42-
s_label: 'Size: S'
43-
m_label: 'Size: M'
44-
l_label: 'Size: L'
45-
xl_label: 'Size: XL'
149+
name: pr
150+
path: pr/

.github/workflows/pr_labeler.yml

Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
# SPDX-License-Identifier: Apache-2.0
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# http://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
#
15+
# This workflow will fetch the PR Labels from the PR Artifact, and write
16+
# the PR Labels into the PR. The workflow is called after the
17+
# "pull_request" trigger (labeler.yml). This "workflow_run" trigger uses a
18+
# GitHub Token with Write Permission, so we must never run any untrusted
19+
# code from the PR, and we must always extract and use the PR Artifact
20+
# safely. See https://cwiki.apache.org/confluence/pages/viewpage.action?pageId=321719166#GitHubActionsSecurity-Buildstriggeredwithworkflow_run
21+
name: "Set Pull Request Labels"
22+
on:
23+
workflow_run:
24+
workflows: ["Pull Request Labeler"]
25+
types:
26+
- completed
27+
28+
jobs:
29+
pr_labeler:
30+
permissions:
31+
contents: read
32+
pull-requests: write
33+
issues: write
34+
runs-on: ubuntu-latest
35+
if: >
36+
github.event.workflow_run.event == 'pull_request' &&
37+
github.event.workflow_run.conclusion == 'success'
38+
steps:
39+
# Download the PR Artifact, containing PR Number and PR Labels
40+
- name: Download PR artifact
41+
uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0
42+
with:
43+
script: |
44+
const artifacts = await github.rest.actions.listWorkflowRunArtifacts({
45+
owner: context.repo.owner,
46+
repo: context.repo.repo,
47+
run_id: ${{ github.event.workflow_run.id }},
48+
});
49+
const matchArtifact = artifacts.data.artifacts.filter((artifact) => {
50+
return artifact.name == "pr"
51+
})[0];
52+
const download = await github.rest.actions.downloadArtifact({
53+
owner: context.repo.owner,
54+
repo: context.repo.repo,
55+
artifact_id: matchArtifact.id,
56+
archive_format: 'zip',
57+
});
58+
const fs = require('fs');
59+
fs.writeFileSync('${{github.workspace}}/pr.zip', Buffer.from(download.data));
60+
61+
# Unzip the PR Artifact
62+
- name: Unzip PR artifact
63+
run: unzip pr.zip
64+
65+
# Write the PR Labels into the PR
66+
- name: Write PR labels
67+
uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0
68+
with:
69+
github-token: ${{ secrets.GITHUB_TOKEN }}
70+
script: |
71+
const owner = context.repo.owner;
72+
const repo = context.repo.repo;
73+
const fs = require('fs');
74+
75+
// Read the PR Number and PR Labels from the PR Artifact
76+
// e.g. 'Size: XS\nArch: avr\n'
77+
const issue_number = Number(fs.readFileSync('pr-id.txt'));
78+
const labels = fs.readFileSync('pr-labels.txt', 'utf8')
79+
.split('\n') // Split by newline
80+
.filter(s => (s != '')); // Remove empty lines
81+
console.log({ issue_number, labels });
82+
83+
// Write the PR Labels into the PR
84+
// e.g. [ 'Size: XS', 'Arch: avr' ]
85+
await github.rest.issues.setLabels({
86+
owner,
87+
repo,
88+
issue_number,
89+
labels
90+
});

0 commit comments

Comments
 (0)