Files
nixpkgs/ci/github-script/get-pr-commit-details.ts
Ihar Hrachyshka 6f32aa7782 ci: use NUL separators for commit metadata
Tabs in metadata may shift fields, causing incorrect validation.

Assisted-by: Codex, GPT-6-Astra medium
(cherry picked from commit 3132f216ad)
2026-11-29 03:15:25 +00:00

130 lines
2.9 KiB
TypeScript

import { execFile as nodeExecFile } from 'node:child_process'
import { promisify } from 'node:util'
const execFile = promisify(nodeExecFile)
export type Commit = {
subject: string
sha: string
parents: string[]
author: { name: string; email: string }
committer: { name: string; email: string }
changedPaths: string[]
changedPathSegments: Set<string>
}
interface RunGitProps {
args: string[]
core: typeof import('@actions/core')
quiet?: boolean
repoPath?: string
}
async function runGit({ args, repoPath, core, quiet }: RunGitProps) {
if (repoPath) {
args = ['-C', repoPath, ...args]
}
if (!quiet) {
core.info(`About to run \`git ${args.map((s) => `'${s}'`).join(' ')}\``)
}
return await execFile('git', args)
}
interface GetCommitMessagesForPRProps {
core: typeof import('@actions/core')
pr: Awaited<
ReturnType<
InstanceType<
typeof import('@actions/github/lib/utils').GitHub
>['rest']['pulls']['get']
>
>['data']
repoPath?: string
}
/**
* Gets the SHA, subject and changed files for each commit in the given PR.
*
* Don't use GitHub API at all: the "list commits on PR" endpoint has a limit
* of 250 commits and doesn't return the changed files.
*/
export async function getCommitDetailsForPR({
core,
pr,
repoPath,
}: GetCommitMessagesForPRProps): Promise<Commit[]> {
await runGit({
args: ['fetch', `--depth=1`, 'origin', pr.base.sha],
repoPath,
core,
})
await runGit({
args: ['fetch', `--depth=${pr.commits + 1}`, 'origin', pr.head.sha],
repoPath,
core,
})
const shas = (
await runGit({
args: [
'rev-list',
`--max-count=${pr.commits}`,
`${pr.base.sha}..${pr.head.sha}`,
],
repoPath,
core,
})
).stdout
.split('\n')
.map((s) => s.trim())
.filter(Boolean)
return Promise.all(
shas.map(async (sha) => {
// Subject, author name, author email, committer name, committer email,
// parents (all NUL-separated), then a blank line, then filenames.
const result = (
await runGit({
args: [
'log',
'--format=%s%x00%aN%x00%aE%x00%cN%x00%cE%x00%P',
'--name-only',
'-1',
sha,
],
repoPath,
core,
quiet: true,
})
).stdout.split('\n')
const [
subject,
authorName,
authorEmail,
committerName,
committerEmail,
parents,
] = result[0].split('\0')
const changedPaths = result.slice(2, -1)
const changedPathSegments = new Set(
changedPaths.flatMap((path) => path.split('/')),
)
return {
sha,
parents: parents.split(' ').filter(Boolean),
subject,
author: { name: authorName, email: authorEmail },
committer: { name: committerName, email: committerEmail },
changedPaths,
changedPathSegments,
}
}),
)
}