Skip to content

Commit 4e130b8

Browse files
committed
Make signature CI pull-request aware
1 parent aabe760 commit 4e130b8

2 files changed

Lines changed: 138 additions & 28 deletions

File tree

‎.github/workflows/pr-comment-git-signatures.yml‎

Lines changed: 26 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -33,14 +33,26 @@ jobs:
3333
const pullRequests = context.payload.workflow_run.pull_requests;
3434
let prNumber;
3535
if (pullRequests && pullRequests.length > 0) {
36+
const pullRequest = pullRequests[0];
37+
const currentRepo = process.env.GITHUB_REPOSITORY;
38+
const currentPullPrefix =
39+
`${process.env.GITHUB_API_URL}/repos/${currentRepo}/pulls/`;
40+
const baseRepo = pullRequest.base?.repo?.full_name;
41+
if ((pullRequest.url && !pullRequest.url.startsWith(currentPullPrefix)) ||
42+
(baseRepo && baseRepo !== currentRepo)) {
43+
console.log('Associated pull request belongs to another repository; skipping.');
44+
return;
45+
}
3646
prNumber = pullRequests[0].number;
3747
} else {
38-
try {
39-
prNumber = parseInt(fs.readFileSync('pr_number', 'utf8').trim());
40-
} catch (e) {
41-
console.log('No PR number found, skipping comment.');
48+
const mirror = context.payload.workflow_run.head_branch.match(
49+
/^pull-request\/([1-9]\d*)$/
50+
);
51+
if (!mirror) {
52+
console.log('Workflow run is not associated with a pull request; skipping.');
4253
return;
4354
}
55+
prNumber = Number(mirror[1]);
4456
}
4557
if (!prNumber || isNaN(prNumber)) {
4658
console.log('No valid PR number found, skipping comment.');
@@ -55,6 +67,14 @@ jobs:
5567
return;
5668
}
5769
70+
const { data: pullRequest } = await github.rest.pulls.get({
71+
owner: context.repo.owner,
72+
repo: context.repo.repo,
73+
pull_number: prNumber
74+
});
75+
const baseCloneUrl = pullRequest.base.repo.clone_url;
76+
const baseRef = pullRequest.base.ref;
77+
5878
const runUrl = `${process.env.GITHUB_SERVER_URL}/${process.env.GITHUB_REPOSITORY}/actions/runs/${{ github.event.workflow_run.id }}`;
5979
6080
const commentBody = `
@@ -85,7 +105,8 @@ jobs:
85105
86106
2. **Re-sign your commits:**
87107
\`\`\`bash
88-
git rebase -i origin/main --exec "git commit --amend --no-edit -S"
108+
git fetch ${baseCloneUrl} ${baseRef}
109+
git rebase -i FETCH_HEAD --exec "git commit --amend --no-edit -S"
89110
git push --force-with-lease
90111
\`\`\`
91112

‎.github/workflows/test-git-signatures.yml‎

Lines changed: 112 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ concurrency:
1414
# Minimal permissions - only read access needed for checks
1515
permissions:
1616
contents: read
17+
pull-requests: read
1718

1819
jobs:
1920
test-git-signatures:
@@ -23,40 +24,133 @@ jobs:
2324
- name: Checkout repository
2425
uses: actions/checkout@v4
2526
with:
26-
fetch-depth: 0 # Need full history to compare with main
27+
fetch-depth: 0 # Needed for merge-group commit ranges
2728

2829
- name: Check commit signatures
2930
id: signature-check
3031
uses: actions/github-script@v7
3132
with:
3233
script: |
33-
const { execSync } = require('child_process');
34-
const fs = require('fs');
34+
const { execFileSync } = require('child_process');
3535
36-
// Get current branch name
3736
const currentBranch = process.env.GITHUB_REF_NAME;
3837
console.log(`Current branch: ${currentBranch}`);
3938
40-
// Skip signature check on main branch to avoid failing on historical unsigned commits
39+
// Main contains historical unsigned commits. Feature and event
40+
// branches are checked when their commits are introduced.
4141
if (currentBranch === 'main') {
4242
console.log('On main branch - skipping signature check for historical commits.');
4343
console.log('Signature verification only runs on PR branches.');
4444
return;
4545
}
4646
47-
// Get commits that are on this branch but not on origin/main
48-
let commitShas;
49-
try {
50-
const output = execSync('git rev-list origin/main..HEAD', { encoding: 'utf-8' });
51-
commitShas = output.trim().split('\n').filter(sha => sha.length > 0);
52-
} catch (error) {
53-
console.log('Could not compare with origin/main, checking all commits on this branch.');
54-
// Fallback: just check the current commit
47+
const unique = values => [...new Set(values.filter(Boolean))];
48+
49+
const commitsForOpenPullRequests = async () => {
50+
try {
51+
const mirror = currentBranch.match(/^pull-request\/(\d+)$/);
52+
let pulls;
53+
if (mirror) {
54+
const pull = await github.rest.pulls.get({
55+
owner: context.repo.owner,
56+
repo: context.repo.repo,
57+
pull_number: Number(mirror[1])
58+
});
59+
pulls = [pull.data];
60+
} else {
61+
pulls = await github.paginate(
62+
github.rest.repos.listPullRequestsAssociatedWithCommit,
63+
{
64+
owner: context.repo.owner,
65+
repo: context.repo.repo,
66+
commit_sha: context.payload.after,
67+
per_page: 100
68+
}
69+
);
70+
pulls = pulls.filter(pull =>
71+
pull.state === 'open' && pull.head.sha === context.payload.after
72+
);
73+
}
74+
75+
if (pulls.length === 0) {
76+
return null;
77+
}
78+
79+
const shas = [];
80+
for (const pull of pulls) {
81+
const targetOwner = pull.base.repo.owner.login;
82+
const targetRepo = pull.base.repo.name;
83+
console.log(
84+
`Checking commits from ${targetOwner}/${targetRepo}#${pull.number} ` +
85+
`(base=${pull.base.ref}).`
86+
);
87+
const commits = await github.paginate(
88+
github.rest.repos.compareCommitsWithBasehead,
89+
{
90+
owner: targetOwner,
91+
repo: targetRepo,
92+
basehead: `${pull.base.sha}...${context.payload.after}`,
93+
per_page: 100
94+
},
95+
response => response.data.commits
96+
);
97+
shas.push(...commits.map(commit => commit.sha));
98+
}
99+
return unique(shas);
100+
} catch (error) {
101+
throw new Error(`Could not determine pull-request commits: ${error.message}`);
102+
}
103+
};
104+
105+
const commitsFromPush = () => {
106+
const pushed = context.payload.commits || [];
107+
if (pushed.length >= 2048) {
108+
throw new Error(
109+
'Push exposes 2048 commits, the event payload limit; ' +
110+
'refusing to skip signature checks.'
111+
);
112+
}
113+
return pushed.map(commit => commit.id);
114+
};
115+
116+
const commitsInRange = (base, head) => {
117+
const shaPattern = /^[0-9a-f]{40}$/;
118+
if (!shaPattern.test(base) || !shaPattern.test(head)) {
119+
throw new Error(`Invalid commit range: ${base}..${head}`);
120+
}
121+
const output = execFileSync(
122+
'git', ['rev-list', `${base}..${head}`], { encoding: 'utf-8' }
123+
);
124+
return output.trim().split('\n').filter(Boolean);
125+
};
126+
127+
let commitShas = null;
128+
if (context.eventName === 'push') {
129+
if (context.payload.deleted) {
130+
console.log('Branch deleted - no commits to check.');
131+
return;
132+
}
133+
134+
commitShas = await commitsForOpenPullRequests();
135+
if (commitShas === null) {
136+
if (context.payload.created) {
137+
console.log('New branch without an open PR - checking pushed commits.');
138+
} else {
139+
console.log('No open PR found - checking commits introduced by this push.');
140+
}
141+
commitShas = commitsFromPush();
142+
}
143+
} else if (context.eventName === 'merge_group') {
144+
const mergeGroup = context.payload.merge_group;
145+
commitShas = commitsInRange(mergeGroup.base_sha, mergeGroup.head_sha);
146+
} else {
55147
commitShas = [process.env.GITHUB_SHA];
56148
}
57149
150+
commitShas = unique(commitShas);
151+
58152
if (commitShas.length === 0) {
59-
console.log('No new commits to check (branch is up to date with main).');
153+
console.log('No new commits to check.');
60154
return;
61155
}
62156
@@ -90,8 +184,10 @@ jobs:
90184
});
91185
}
92186
} catch (error) {
93-
console.log(`⚠ ${sha.substring(0, 7)} - Could not verify (${error.message})`);
94-
// Don't fail on API errors for individual commits
187+
core.setFailed(
188+
`Could not verify ${sha.substring(0, 7)} via GitHub API: ${error.message}`
189+
);
190+
return;
95191
}
96192
}
97193
@@ -111,11 +207,6 @@ jobs:
111207
console.log(`\n✅ All ${commitShas.length} commit(s) are properly signed.`);
112208
}
113209
114-
- name: Get PR info
115-
id: get-pr-info
116-
if: always() && startsWith(github.ref_name, 'pull-request/')
117-
uses: nv-gha-runners/get-pr-info@main
118-
119210
- name: Save PR comment data
120211
if: always()
121212
run: |
@@ -124,8 +215,6 @@ jobs:
124215
cat << 'EOF' > ./pr-comment-data/unsigned_commits
125216
${{ steps.signature-check.outputs.unsigned_commits }}
126217
EOF
127-
PR_NUMBER='${{ startsWith(github.ref_name, 'pull-request/') && fromJSON(steps.get-pr-info.outputs.pr-info).number || '' }}'
128-
echo "${PR_NUMBER}" > ./pr-comment-data/pr_number
129218
130219
- name: Upload PR comment data
131220
if: always()

0 commit comments

Comments
 (0)