diff --git a/src/extract.ts b/src/extract.ts index 18cfaecb9..d035d0fe9 100644 --- a/src/extract.ts +++ b/src/extract.ts @@ -1,6 +1,7 @@ /* eslint-disable @typescript-eslint/naming-convention */ import { promises as fs } from 'fs'; import * as github from '@actions/github'; +import { cmd } from './git'; import { Config, ToolType } from './config'; import { z } from 'zod'; @@ -239,21 +240,24 @@ function getHumanReadableUnitValue(seconds: number): [number, string] { } } -function getCommitFromPullRequestPayload(pr: PullRequest): Commit { - // On pull_request hook, head_commit is not available +async function getCommitFromPullRequestPayload(pr: PullRequest): Promise { + // On pull_request hook, head_commit is not available. + // HEAD is the merge commit GitHub creates for the PR, always accessible even with shallow clones. + // Its timestamp is within seconds of the actual commit time. const id: string = pr.head.sha; const username: string = pr.head.user.login; const user = { name: username, // XXX: Fallback, not correct username, }; + const timestamp = (await cmd([], 'log', '-1', '--format=%aI', 'HEAD')).trim(); return { author: user, committer: user, id, message: pr.title, - timestamp: pr.head.repo.updated_at, + timestamp, url: `${pr.html_url}/commits/${id}`, }; } @@ -299,7 +303,7 @@ async function getCommit(githubToken?: string, ref?: string): Promise { const pr = github.context.payload.pull_request; if (pr) { - return getCommitFromPullRequestPayload(pr); + return await getCommitFromPullRequestPayload(pr); } if (!githubToken) { diff --git a/test/extract.spec.ts b/test/extract.spec.ts index 631b64f43..9405b9f43 100644 --- a/test/extract.spec.ts +++ b/test/extract.spec.ts @@ -37,6 +37,10 @@ const dummyGitHubContext = { ref: 'abcd1234', }; +jest.mock('../src/git', () => ({ + cmd: jest.fn().mockResolvedValue('2024-01-15T10:30:00+00:00\n'), +})); + jest.mock('@actions/github', () => ({ get context() { return dummyGitHubContext; @@ -218,9 +222,7 @@ describe('extractResult()', function () { user: { login: 'user', }, - repo: { - updated_at: 'repo updated at timestamp', - }, + repo: {}, }, }, }; @@ -238,7 +240,7 @@ describe('extractResult()', function () { A.deepEqual(commit.committer, expectedUser); A.equal(commit.id, 'abcdef0123456789'); A.equal(commit.message, 'this is title'); - A.equal(commit.timestamp, 'repo updated at timestamp'); + A.equal(commit.timestamp, '2024-01-15T10:30:00+00:00'); A.equal(commit.url, 'https://github.com/dummy/repo/pull/1/commits/abcdef0123456789'); });