3
0
Fork 0
mirror of https://gitea.com/docker/metadata-action.git synced 2024-11-21 19:49:32 +01:00

feat: add variable commit_date

Signed-off-by: Trim21 <trim21.me@gmail.com>
This commit is contained in:
Trim21 2024-11-13 23:39:24 +08:00
parent 44d81d6d2a
commit 526d40319b
No known key found for this signature in database
GPG key ID: 809F01CFB0A797FB
9 changed files with 246 additions and 27 deletions

View file

@ -889,6 +889,19 @@ Default `tz` is UTC.
| `{{date 'dddd, MMMM Do YYYY, h:mm:ss a'}}` | `Friday, January 10th 2020, 3:25:50 pm` |
| `{{date 'YYYYMMDD-HHmmss' tz='Asia/Tokyo'}}` | `20200110-093000` |
#### `{{commit_date '<format>' tz='<timezone>'}}`
Returns the date when current git commit is committed.
rendered by its [moment format](https://momentjs.com/docs/#/displaying/format/).
Default `tz` is UTC.
| Expression | Output example |
|----------------------------------------------|-----------------------------------------|
| `{{commit_date 'YYYYMMDD'}}` | `20200110` |
| `{{commit_date 'dddd, MMMM Do YYYY, h:mm:ss a'}}` | `Friday, January 10th 2020, 3:25:50 pm` |
| `{{commit_date 'YYYYMMDD-HHmmss' tz='Asia/Tokyo'}}` | `20200110-093000` |
### Major version zero
Major version zero (`0.y.z`) is for initial development and **may** change at

View file

@ -204,4 +204,6 @@ export const context = {
}
};
export const getOctokit = jest.fn();
export const getOctokit = jest.fn(() => ({
request: () => Promise.resolve({data: {committer: {date: '2024-11-13T13:42:28Z'}}})
}));

View file

@ -7,6 +7,9 @@ import {Git} from '@docker/actions-toolkit/lib/git';
import {GitHub} from '@docker/actions-toolkit/lib/github';
import {ContextSource, getContext, getInputs, Inputs} from '../src/context';
import {Toolkit} from '@docker/actions-toolkit/lib/toolkit';
const toolkit = new Toolkit({githubToken: 'fake-github-token'});
beforeEach(() => {
jest.clearAllMocks();
@ -113,9 +116,10 @@ describe('getContext', () => {
});
it('workflow', async () => {
const context = await getContext(ContextSource.workflow);
const context = await getContext(ContextSource.workflow, toolkit);
expect(context.ref).toEqual('refs/heads/dev');
expect(context.sha).toEqual('5f3331d7f7044c18ca9f12c77d961c4d7cf3276a');
expect(context.commitDate).toEqual(new Date('2024-11-13T13:42:28.000Z'));
});
it('git', async () => {
@ -125,9 +129,13 @@ describe('getContext', () => {
sha: 'git-test-sha'
} as Context);
});
const context = await getContext(ContextSource.git);
jest.spyOn(Git, 'commitDate').mockImplementation(async (): Promise<Date> => {
return new Date('2023-01-01T13:42:28.000Z');
});
const context = await getContext(ContextSource.git, toolkit);
expect(context.ref).toEqual('refs/heads/git-test');
expect(context.sha).toEqual('git-test-sha');
expect(context.commitDate).toEqual(new Date('2023-01-01T13:42:28.000Z'));
});
});

View file

@ -31,8 +31,16 @@ beforeEach(() => {
delete process.env[key];
}
});
jest.spyOn(GitHub, 'context', 'get').mockImplementation((): Context => {
return new Context();
//@ts-expect-error partial info
return {
...new Context(),
repo: {
owner: 'docker',
repo: 'repo'
}
};
});
});
@ -53,7 +61,7 @@ const tagsLabelsTest = async (name: string, envFile: string, inputs: Inputs, exV
process.env = dotenv.parse(fs.readFileSync(path.join(__dirname, 'fixtures', envFile)));
const toolkit = new Toolkit();
const repo = await toolkit.github.repoData();
const meta = new Meta({...getInputs(), ...inputs}, await getContext(ContextSource.workflow), repo);
const meta = new Meta({...getInputs(), ...inputs}, await getContext(ContextSource.workflow, toolkit), repo);
const version = meta.version;
expect(version).toEqual(exVersion);
@ -622,6 +630,7 @@ describe('push', () => {
tags: [
`type=raw,value=mytag-{{branch}}`,
`type=raw,value=mytag-{{date 'YYYYMMDD'}}`,
`type=raw,value=mytag-cd-{{commit_date 'YYYYMMDD'}}`,
`type=raw,value=mytag-{{date 'YYYYMMDD-HHmmss' tz='Asia/Tokyo'}}`,
`type=raw,value=mytag-tag-{{tag}}`,
`type=raw,value=mytag-baseref-{{base_ref}}`,
@ -632,6 +641,7 @@ describe('push', () => {
main: 'mytag-master',
partial: [
'mytag-20200110',
"mytag-cd-20200110",
'mytag-20200110-093000',
'mytag-tag-',
'mytag-baseref-',
@ -642,6 +652,7 @@ describe('push', () => {
[
'user/app:mytag-master',
'user/app:mytag-20200110',
'user/app:mytag-cd-20200110',
'user/app:mytag-20200110-093000',
'user/app:mytag-tag-',
'user/app:mytag-baseref-',
@ -768,6 +779,7 @@ describe('push', () => {
`type=raw,value=mytag-{{branch}}`,
`type=raw,value=mytag-{{date 'YYYYMMDD'}}`,
`type=raw,value=mytag-{{date 'YYYYMMDD-HHmmss' tz='Asia/Tokyo'}}`,
`type=raw,value=mytag-src-{{commit_date 'YYYYMMDD'}}`,
`type=raw,value=mytag-tag-{{tag}}`,
`type=raw,value=mytag-baseref-{{base_ref}}`,
`type=raw,value=mytag-defbranch,enable={{is_default_branch}}`
@ -778,6 +790,7 @@ describe('push', () => {
partial: [
'mytag-20200110',
'mytag-20200110-093000',
'mytag-src-20200110',
'mytag-tag-',
'mytag-baseref-',
'mytag-defbranch'
@ -788,6 +801,7 @@ describe('push', () => {
'mytag-master',
'mytag-20200110',
'mytag-20200110-093000',
'mytag-src-20200110',
'mytag-tag-',
'mytag-baseref-',
'mytag-defbranch'
@ -2621,6 +2635,35 @@ describe('pr', () => {
],
undefined
],
[
'pr12',
'event_pull_request.env',
{
images: ['org/app'],
tags: [
`type=raw,value={{commit_date YYYY-MM-DD-HHmmSS}}`,
]
} as Inputs,
{
main: "2020-01-10T00-30-00Z",
partial: [],
latest: false
} as Version,
[
'org/app:2020-01-10T00-30-00Z'
],
[
"org.opencontainers.image.created=2020-01-10T00:30:00.000Z",
"org.opencontainers.image.description=This your first repo!",
"org.opencontainers.image.licenses=MIT",
"org.opencontainers.image.revision=a9c8c5828b91be19d9728548b24759e352367ef1",
"org.opencontainers.image.source=https://github.com/octocat/Hello-World",
"org.opencontainers.image.title=Hello-World",
"org.opencontainers.image.url=https://github.com/octocat/Hello-World",
"org.opencontainers.image.version=2020-01-10T00-30-00Z"
],
undefined
],
])('given %p with %p event', tagsLabelsTest);
});
@ -2969,13 +3012,41 @@ describe('pr-head-sha', () => {
"org.opencontainers.image.version=mytag-master"
]
],
[
'pr12',
'event_pull_request.env',
{
images: ['org/app'],
tags: [
`type=raw,value=src-{{commit_date YYYY-MM-DD}}`,
]
} as Inputs,
{
main: "src-2020-01-10T00-30-00Z",
partial: [],
latest: false
} as Version,
[
"org/app:src-2020-01-10T00-30-00Z",
],
[
"org.opencontainers.image.created=2020-01-10T00:30:00.000Z",
"org.opencontainers.image.description=This your first repo!",
"org.opencontainers.image.licenses=MIT",
"org.opencontainers.image.revision=3370e228f2209994d57af4427fe64e71bb79ac96",
"org.opencontainers.image.source=https://github.com/octocat/Hello-World",
"org.opencontainers.image.title=Hello-World",
"org.opencontainers.image.url=https://github.com/octocat/Hello-World",
"org.opencontainers.image.version=src-2020-01-10T00-30-00Z",
]
],
])('given %p with %p event', async (name: string, envFile: string, inputs: Inputs, exVersion: Version, exTags: Array<string>, exLabelsAnnotations: Array<string>) => {
process.env = dotenv.parse(fs.readFileSync(path.join(__dirname, 'fixtures', envFile)));
process.env.DOCKER_METADATA_PR_HEAD_SHA = 'true';
const toolkit = new Toolkit();
const repo = await toolkit.github.repoData();
const meta = new Meta({...getInputs(), ...inputs}, await getContext(ContextSource.workflow), repo);
const meta = new Meta({...getInputs(), ...inputs}, await getContext(ContextSource.workflow, toolkit), repo);
const version = meta.version;
expect(version).toEqual(exVersion);
@ -3028,16 +3099,20 @@ describe('schedule', () => {
{
images: ['user/app'],
tags: [
`type=schedule,pattern={{date 'YYYYMMDD'}}`
`type=schedule,pattern={{date 'YYYYMMDD'}}`,
`type=schedule,pattern=source-date-{{commit_date 'YYYY-MM-DD'}}`
]
} as Inputs,
{
main: '20200110',
partial: [],
partial: [
"source-date-2020-01-10",
],
latest: false
} as Version,
[
'user/app:20200110'
'user/app:20200110',
'user/app:source-date-2020-01-10'
],
[
"org.opencontainers.image.created=2020-01-10T00:30:00.000Z",
@ -3221,16 +3296,20 @@ describe('schedule', () => {
{
images: ['user/app'],
tags: [
`type=schedule,pattern={{date 'YYYYMMDD-HHmmss' tz='Asia/Tokyo'}}`
`type=schedule,pattern={{date 'YYYYMMDD-HHmmss' tz='Asia/Tokyo'}}`,
`type=schedule,pattern=src-{{commit_date 'YYYYMMDD-HHmmss' tz='Asia/Tokyo'}}`,
]
} as Inputs,
{
main: '20200110-093000',
partial: [],
partial: [
"src-20200110-093000",
],
latest: false
} as Version,
[
'user/app:20200110-093000'
'user/app:20200110-093000',
'user/app:src-20200110-093000'
],
[
"org.opencontainers.image.created=2020-01-10T00:30:00.000Z",
@ -3312,6 +3391,39 @@ describe('release', () => {
"org.opencontainers.image.version=v1.1.1"
],
undefined
],
[
'release03',
'event_release_created.env',
{
images: ['user/app'],
tags: [
`type=raw,value=src-{{commit_date 'YYYYMMDD-HHmmss'}}`,
`type=raw,value={{date 'YYYYMMDD-HHmmss'}}`,
]
} as Inputs,
{
"main": "src-20200110-003000",
partial: [
"20200110-003000",
],
"latest": false,
} as Version,
[
"user/app:src-20200110-003000",
"user/app:20200110-003000",
],
[
"org.opencontainers.image.created=2020-01-10T00:30:00.000Z",
"org.opencontainers.image.description=This your first repo!",
"org.opencontainers.image.licenses=MIT",
"org.opencontainers.image.revision=860c1904a1ce19322e91ac35af1ab07466440c37",
"org.opencontainers.image.source=https://github.com/octocat/Hello-World",
"org.opencontainers.image.title=Hello-World",
"org.opencontainers.image.url=https://github.com/octocat/Hello-World",
"org.opencontainers.image.version=src-20200110-003000",
],
undefined
]
])('given %s with %p event', tagsLabelsTest);
});
@ -4012,7 +4124,7 @@ describe('json', () => {
const toolkit = new Toolkit();
const repo = await toolkit.github.repoData();
const meta = new Meta({...getInputs(), ...inputs}, await getContext(ContextSource.workflow), repo);
const meta = new Meta({...getInputs(), ...inputs}, await getContext(ContextSource.workflow,toolkit), repo);
const jsonOutput = meta.getJSON(['manifest']);
expect(jsonOutput).toEqual(exJSON);
@ -4528,7 +4640,7 @@ describe('bakeFile', () => {
const toolkit = new Toolkit();
const repo = await toolkit.github.repoData();
const meta = new Meta({...getInputs(), ...inputs}, await getContext(ContextSource.workflow), repo);
const meta = new Meta({...getInputs(), ...inputs}, await getContext(ContextSource.workflow,toolkit), repo);
const bakeFileTags = meta.getBakeFile('tags');
expect(JSON.parse(fs.readFileSync(bakeFileTags, 'utf8'))).toEqual(exBakeTags);
@ -4592,7 +4704,7 @@ describe('bakeFileTagsLabels', () => {
const toolkit = new Toolkit();
const repo = await toolkit.github.repoData();
const meta = new Meta({...getInputs(), ...inputs}, await getContext(ContextSource.workflow), repo);
const meta = new Meta({...getInputs(), ...inputs}, await getContext(ContextSource.workflow,toolkit), repo);
const bakeFile = meta.getBakeFileTagsLabels();
expect(JSON.parse(fs.readFileSync(bakeFile, 'utf8'))).toEqual(exBakeDefinition);
@ -4638,8 +4750,10 @@ describe('sepTags', () => {
process.env = dotenv.parse(fs.readFileSync(path.join(__dirname, 'fixtures', envFile)));
const toolkit = new Toolkit();
const repo = await toolkit.github.repoData();
const meta = new Meta({...getInputs(), ...inputs}, await getContext(ContextSource.workflow), repo);
const meta = new Meta({...getInputs(), ...inputs}, await getContext(ContextSource.workflow, toolkit), repo);
expect(meta.getTags().join(inputs.sepTags)).toEqual(expTags);
});

2
dist/index.js generated vendored

File diff suppressed because one or more lines are too long

2
dist/index.js.map generated vendored

File diff suppressed because one or more lines are too long

View file

@ -1,8 +1,13 @@
import * as core from '@actions/core';
import {Context} from '@actions/github/lib/context';
import {Context as GithubContext} from '@actions/github/lib/context';
import {Util} from '@docker/actions-toolkit/lib/util';
import {Git} from '@docker/actions-toolkit/lib/git';
import {GitHub} from '@docker/actions-toolkit/lib/github';
import {Toolkit} from '@docker/actions-toolkit/lib/toolkit';
export interface Context extends GithubContext {
commitDate: Date;
}
export interface Inputs {
context: ContextSource;
@ -39,10 +44,10 @@ export enum ContextSource {
git = 'git'
}
export async function getContext(source: ContextSource): Promise<Context> {
export async function getContext(source: ContextSource, toolkit: Toolkit): Promise<Context> {
switch (source) {
case ContextSource.workflow:
return getContextFromWorkflow();
return await getContextFromWorkflow(toolkit);
case ContextSource.git:
return await getContextFromGit();
default:
@ -50,7 +55,7 @@ export async function getContext(source: ContextSource): Promise<Context> {
}
}
function getContextFromWorkflow(): Context {
async function getContextFromWorkflow(toolkit: Toolkit): Promise<Context> {
const context = GitHub.context;
// Needs to override Git reference with pr ref instead of upstream branch ref
@ -69,9 +74,56 @@ function getContextFromWorkflow(): Context {
}
}
return context;
return {
commitDate: await getCommitDateFromWorkflow(context.sha, toolkit),
...context
} as Context;
}
async function getContextFromGit(): Promise<Context> {
return await Git.context();
const ctx = await Git.context();
return {
commitDate: await Git.commitDate(ctx.sha),
...ctx
} as Context;
}
async function getCommitDateFromWorkflow(sha: string, toolkit: Toolkit): Promise<Date> {
const event = GitHub.context.payload as unknown as {
// branch push
commits?: Array<{
timestamp: string;
// commit sha
id: string;
}>;
// tags
head_commit?: {
timestamp: string;
// commit sha
id: string;
};
};
if (event.commits) {
const commitDate = event.commits.find(x => x.id === sha)?.timestamp;
if (commitDate) {
return new Date(commitDate);
}
}
if (event.head_commit) {
if (event.head_commit.id === sha) {
return new Date(event.head_commit.timestamp);
}
}
// fallback to github api for commit date
const commit = await toolkit.github.octokit.request('GET /repos/{owner}/{repo}/commits/{commit_sha}', {
commit_sha: sha,
owner: GitHub.context.repo.owner,
repo: GitHub.context.repo.repo
});
return new Date(commit.data.committer.date);
}

View file

@ -11,7 +11,7 @@ actionsToolkit.run(
async () => {
const inputs: Inputs = getInputs();
const toolkit = new Toolkit({githubToken: inputs.githubToken});
const context = await getContext(inputs.context);
const context = await getContext(inputs.context, toolkit);
const repo = await toolkit.github.repoData();
await core.group(`Context info`, async () => {
@ -23,6 +23,7 @@ actionsToolkit.run(
core.info(`actor: ${context.actor}`);
core.info(`runNumber: ${context.runNumber}`);
core.info(`runId: ${context.runId}`);
core.info(`commitDate: ${context.commitDate}`);
});
if (core.isDebug()) {

View file

@ -5,11 +5,10 @@ import moment from 'moment-timezone';
import * as pep440 from '@renovate/pep440';
import * as semver from 'semver';
import * as core from '@actions/core';
import {Context} from '@actions/github/lib/context';
import {Context as ToolkitContext} from '@docker/actions-toolkit/lib/context';
import {GitHubRepo} from '@docker/actions-toolkit/lib/types/github';
import {Inputs} from './context';
import {Inputs, Context} from './context';
import * as icl from './image';
import * as tcl from './tag';
import * as fcl from './flavor';
@ -115,6 +114,7 @@ export class Meta {
}
const currentDate = this.date;
const commitDate = this.context.commitDate;
const vraw = this.setValue(
handlebars.compile(tag.attrs['pattern'])({
date: function (format, options) {
@ -130,6 +130,20 @@ export class Meta {
}
});
return m.tz(tz).format(format);
},
commit_date: function (format, options) {
const m = moment(commitDate);
let tz = 'UTC';
Object.keys(options.hash).forEach(key => {
switch (key) {
case 'tz':
tz = options.hash[key];
break;
default:
throw new Error(`Unknown ${key} attribute`);
}
});
return m.tz(tz).format(format);
}
}),
tag
@ -361,6 +375,7 @@ export class Meta {
private setGlobalExp(val): string {
const context = this.context;
const currentDate = this.date;
const commitDate = this.context.commitDate;
return handlebars.compile(val)({
branch: function () {
if (!/^refs\/heads\//.test(context.ref)) {
@ -388,6 +403,20 @@ export class Meta {
}
return '';
},
commit_date: function (format, options) {
const m = moment(commitDate);
let tz = 'UTC';
Object.keys(options.hash).forEach(key => {
switch (key) {
case 'tz':
tz = options.hash[key];
break;
default:
throw new Error(`Unknown ${key} attribute`);
}
});
return m.tz(tz).format(format);
},
is_default_branch: function () {
const branch = context.ref.replace(/^refs\/heads\//g, '');
// TODO: "base_ref" is available in the push payload but doesn't always seem to