v2 first shot

This commit is contained in:
CrazyMax 2021-03-24 18:56:49 +01:00
parent 9be43f076d
commit 63a49e1ec3
No known key found for this signature in database
GPG Key ID: 3248E46B6BB8C7F7
9 changed files with 1704 additions and 353 deletions

View File

@ -5,10 +5,14 @@ on:
- cron: '0 */4 * * *' # every 4 hours
push:
branches:
- '**'
- 'master'
- 'releases/v*'
tags:
- 'v*.*.*'
pull_request:
branches:
- 'master'
- 'releases/v*'
env:
DOCKER_IMAGE: localhost:5000/name/app
@ -27,7 +31,12 @@ jobs:
images: |
${{ env.DOCKER_IMAGE }}
ghcr.io/name/app
tag-sha: true
tags: |
type=schedule
type=ref,event=branch
type=ref,event=tag
type=ref,event=pr
type=sha
tag-schedule:
runs-on: ubuntu-latest
@ -50,8 +59,12 @@ jobs:
images: |
${{ env.DOCKER_IMAGE }}
ghcr.io/name/app
tag-sha: true
tag-schedule: ${{ matrix.tag-schedule }}
tags: |
type=schedule,pattern=${{ matrix.tag-schedule }}
type=ref,event=branch
type=ref,event=tag
type=ref,event=pr
type=sha
tag-match:
runs-on: ubuntu-latest
@ -76,9 +89,13 @@ jobs:
images: |
${{ env.DOCKER_IMAGE }}
ghcr.io/name/app
tag-sha: true
tag-match: ${{ matrix.tag-match }}
tag-match-group: ${{ matrix.tag-match-group }}
tags: |
type=schedule
type=ref,event=branch
type=ref,event=tag
type=ref,event=pr
type=match,"pattern=${{ matrix.tag-match }}",group=${{ matrix.tag-match-group }}
type=sha
tag-semver:
runs-on: ubuntu-latest
@ -86,8 +103,9 @@ jobs:
fail-fast: false
matrix:
tag-latest:
- 'true'
- 'false'
- "auto"
- "true"
- "false"
steps:
-
name: Checkout
@ -99,11 +117,15 @@ jobs:
images: |
${{ env.DOCKER_IMAGE }}
ghcr.io/name/app
tag-semver: |
{{raw}}
{{version}}
{{major}}.{{minor}}.{{patch}}
tag-latest: ${{ matrix.tag-latest }}
tags: |
type=schedule
type=ref,event=branch
type=ref,event=tag
type=ref,event=pr
type=semver,latest=${{ matrix.tag-latest }},pattern={{raw}}
type=semver,latest=${{ matrix.tag-latest }},pattern={{version}}
type=semver,latest=${{ matrix.tag-latest }},pattern={{major}}.{{minor}}.{{patch}}
type=sha
label-custom:
runs-on: ubuntu-latest
@ -118,7 +140,7 @@ jobs:
images: |
${{ env.DOCKER_IMAGE }}
ghcr.io/name/app
label-custom: |
labels: |
maintainer=CrazyMax
org.opencontainers.image.title=MyCustomTitle
org.opencontainers.image.description=Another description
@ -141,11 +163,15 @@ jobs:
uses: ./
with:
images: ${{ env.DOCKER_IMAGE }}
tag-sha: true
tag-semver: |
v{{version}}
v{{major}}.{{minor}}
v{{major}}
tags: |
type=schedule
type=ref,event=branch
type=ref,event=tag
type=ref,event=pr
type=semver,pattern=v{{version}}
type=semver,pattern=v{{major}}.{{minor}}
type=semver,pattern=v{{major}}
type=sha
-
name: Set up QEMU
uses: docker/setup-qemu-action@v1
@ -192,11 +218,15 @@ jobs:
images: |
${{ env.DOCKER_IMAGE }}
ghcr.io/name/app
tag-sha: true
tag-semver: |
{{version}}
{{major}}.{{minor}}
{{major}}
tags: |
type=schedule
type=ref,event=branch
type=ref,event=tag
type=ref,event=pr
type=semver,pattern={{version}}
type=semver,pattern={{major}}.{{minor}}
type=semver,pattern={{major}}
type=sha
-
name: Set up QEMU
uses: docker/setup-qemu-action@v1

File diff suppressed because it is too large Load Diff

450
__tests__/tag.test.ts Normal file
View File

@ -0,0 +1,450 @@
import {Transform, Parse, Tag, Type, RefEvent, DefaultPriorities} from '../src/tag';
describe('transform', () => {
// prettier-ignore
test.each([
[
[
`type=ref,event=branch`,
`type=ref,event=tag`,
`type=ref,event=pr`,
`type=schedule`,
`type=sha`,
`type=raw,foo`,
`type=edge`,
`type=semver,pattern={{version}}`,
`type=match,"pattern=\\d{1,3}.\\d{1,3}.\\d{1,3}"`
],
[
{
type: Type.Schedule,
attrs: {
"priority": DefaultPriorities[Type.Schedule],
"enable": "true",
"latest": "auto",
"prefix": "",
"suffix": "",
"pattern": "nightly"
}
},
{
type: Type.Semver,
attrs: {
"priority": DefaultPriorities[Type.Semver],
"enable": "true",
"latest": "auto",
"prefix": "",
"suffix": "",
"pattern": "{{version}}"
}
},
{
type: Type.Match,
attrs: {
"priority": DefaultPriorities[Type.Match],
"enable": "true",
"latest": "auto",
"prefix": "",
"suffix": "",
"pattern": "\\d{1,3}.\\d{1,3}.\\d{1,3}",
"group": "0"
}
},
{
type: Type.Edge,
attrs: {
"priority": DefaultPriorities[Type.Edge],
"enable": "true",
"latest": "auto",
"prefix": "",
"suffix": "",
"branch": ""
}
},
{
type: Type.Ref,
attrs: {
"priority": DefaultPriorities[Type.Ref],
"enable": "true",
"latest": "auto",
"prefix": "",
"suffix": "",
"event": RefEvent.Branch
}
},
{
type: Type.Ref,
attrs: {
"priority": DefaultPriorities[Type.Ref],
"enable": "true",
"latest": "auto",
"prefix": "",
"suffix": "",
"event": RefEvent.Tag
}
},
{
type: Type.Ref,
attrs: {
"priority": DefaultPriorities[Type.Ref],
"enable": "true",
"latest": "auto",
"prefix": "pr-",
"suffix": "",
"event": RefEvent.PR
}
},
{
type: Type.Raw,
attrs: {
"priority": DefaultPriorities[Type.Raw],
"enable": "true",
"latest": "auto",
"prefix": "",
"suffix": "",
"value": "foo"
}
},
{
type: Type.Sha,
attrs: {
"priority": DefaultPriorities[Type.Sha],
"enable": "true",
"latest": "auto",
"prefix": "sha-",
"suffix": ""
}
}
] as Tag[],
false
]
])('given %p', async (l: string[], expected: Tag[], invalid: boolean) => {
try {
const tags = Transform(l);
console.log(tags);
expect(tags).toEqual(expected);
} catch (err) {
if (!invalid) {
console.error(err);
}
expect(true).toBe(invalid);
}
});
});
describe('parse', () => {
// prettier-ignore
test.each([
[
`type=schedule,enable=true,pattern={{date 'YYYYMMDD'}}`,
{
type: Type.Schedule,
attrs: {
"priority": DefaultPriorities[Type.Schedule],
"enable": "true",
"latest": "auto",
"prefix": "",
"suffix": "",
"pattern": "{{date 'YYYYMMDD'}}"
}
} as Tag,
false
],
[
`type=semver`,
{} as Tag,
true
],
[
`type=semver,enable=true,pattern={{version}}`,
{
type: Type.Semver,
attrs: {
"priority": DefaultPriorities[Type.Semver],
"enable": "true",
"latest": "auto",
"prefix": "",
"suffix": "",
"pattern": "{{version}}"
}
} as Tag,
false
],
[
`type=semver,priority=1,enable=true,pattern={{version}}`,
{
type: Type.Semver,
attrs: {
"priority": "1",
"enable": "true",
"latest": "auto",
"prefix": "",
"suffix": "",
"pattern": "{{version}}"
}
} as Tag,
false
],
[
`type=match`,
{} as Tag,
true
],
[
`type=match,enable=true,pattern=v(.*),group=1`,
{
type: Type.Match,
attrs: {
"priority": DefaultPriorities[Type.Match],
"enable": "true",
"latest": "auto",
"prefix": "",
"suffix": "",
"pattern": "v(.*)",
"group": "1"
}
} as Tag,
false
],
[
`type=match,enable=true,"pattern=^v(\\d{1,3}.\\d{1,3}.\\d{1,3})$",group=1`,
{
type: Type.Match,
attrs: {
"priority": DefaultPriorities[Type.Match],
"enable": "true",
"latest": "auto",
"prefix": "",
"suffix": "",
"pattern": "^v(\\d{1,3}.\\d{1,3}.\\d{1,3})$",
"group": "1"
}
} as Tag,
false
],
[
`type=match,priority=700,enable=true,pattern=v(.*),group=1`,
{
type: Type.Match,
attrs: {
"priority": "700",
"enable": "true",
"latest": "auto",
"prefix": "",
"suffix": "",
"pattern": "v(.*)",
"group": "1"
}
} as Tag,
false
],
[
`type=match,enable=true,pattern=v(.*),group=foo`,
{} as Tag,
true
],
[
`type=edge`,
{
type: Type.Edge,
attrs: {
"priority": DefaultPriorities[Type.Edge],
"enable": "true",
"latest": "auto",
"prefix": "",
"suffix": "",
"branch": ""
}
} as Tag,
false
],
[
`type=edge,enable=true,branch=master`,
{
type: Type.Edge,
attrs: {
"priority": DefaultPriorities[Type.Edge],
"enable": "true",
"latest": "auto",
"prefix": "",
"suffix": "",
"branch": "master"
}
} as Tag,
false
],
[
`type=ref,event=tag`,
{
type: Type.Ref,
attrs: {
"priority": DefaultPriorities[Type.Ref],
"enable": "true",
"latest": "auto",
"prefix": "",
"suffix": "",
"event": RefEvent.Tag
}
} as Tag,
false
],
[
`type=ref,event=branch`,
{
type: Type.Ref,
attrs: {
"priority": DefaultPriorities[Type.Ref],
"enable": "true",
"latest": "auto",
"prefix": "",
"suffix": "",
"event": RefEvent.Branch
}
} as Tag,
false
],
[
`type=ref,event=pr`,
{
type: Type.Ref,
attrs: {
"priority": DefaultPriorities[Type.Ref],
"enable": "true",
"latest": "auto",
"prefix": "pr-",
"suffix": "",
"event": RefEvent.PR
}
} as Tag,
false
],
[
`type=ref,event=foo`,
{} as Tag,
true
],
[
`type=ref`,
{} as Tag,
true
],
[
`acustomtag`,
{
type: Type.Raw,
attrs: {
"priority": DefaultPriorities[Type.Raw],
"enable": "true",
"latest": "auto",
"prefix": "",
"suffix": "",
"value": "acustomtag"
}
} as Tag,
false
],
[
`type=raw`,
{} as Tag,
true
],
[
`type=raw,value=acustomtag2`,
{
type: Type.Raw,
attrs: {
"priority": DefaultPriorities[Type.Raw],
"enable": "true",
"latest": "auto",
"prefix": "",
"suffix": "",
"value": "acustomtag2"
}
} as Tag,
false
],
[
`type=raw,enable=true,value=acustomtag4`,
{
type: Type.Raw,
attrs: {
"priority": DefaultPriorities[Type.Raw],
"enable": "true",
"latest": "auto",
"prefix": "",
"suffix": "",
"value": "acustomtag4"
}
} as Tag,
false
],
[
`type=raw,enable=false,value=acustomtag5`,
{
type: Type.Raw,
attrs: {
"priority": DefaultPriorities[Type.Raw],
"enable": "false",
"latest": "auto",
"prefix": "",
"suffix": "",
"value": "acustomtag5"
}
} as Tag,
false
],
[
`type=sha`,
{
type: Type.Sha,
attrs: {
"priority": DefaultPriorities[Type.Sha],
"enable": "true",
"latest": "auto",
"prefix": "sha-",
"suffix": ""
}
} as Tag,
false
],
[
`type=sha,prefix=`,
{
type: Type.Sha,
attrs: {
"priority": DefaultPriorities[Type.Sha],
"enable": "true",
"latest": "auto",
"prefix": "",
"suffix": ""
}
} as Tag,
false
],
[
`type=sha,enable=false`,
{
type: Type.Sha,
attrs: {
"priority": DefaultPriorities[Type.Sha],
"enable": "false",
"latest": "auto",
"prefix": "sha-",
"suffix": ""
}
} as Tag,
false
]
])('given %p event ', async (s: string, expected: Tag, invalid: boolean) => {
try {
const tag = Parse(s);
console.log(tag);
expect(tag).toEqual(expected);
} catch (err) {
if (!invalid) {
console.error(err);
}
expect(true).toBe(invalid);
}
});
});

View File

@ -10,47 +10,10 @@ inputs:
images:
description: 'List of Docker images to use as base name for tags'
required: true
tag-sha:
description: 'Add git short SHA as Docker tag'
default: 'false'
tags:
description: 'List of tags as key-value pair (format: type=ref,...)'
required: false
tag-edge:
description: 'Enable edge branch tagging'
default: 'false'
required: false
tag-edge-branch:
description: 'Branch that will be tagged as edge (default repo.default_branch)'
required: false
tag-semver:
description: 'Handle Git tag as semver template if possible'
required: false
tag-match:
description: 'RegExp to match against a Git tag and use match group as Docker tag'
required: false
tag-match-group:
description: 'Group to get if tag-match matches (default 0)'
default: '0'
required: false
tag-latest:
description: 'Set latest Docker tag if tag-semver, tag-match or Git tag event occurs'
default: 'true'
required: false
tag-match-latest:
deprecationMessage: 'tag-match-latest is deprecated. Use tag-latest instead'
description: '(DEPRECATED) Set latest Docker tag if tag-match matches or on Git tag event'
default: 'true'
required: false
tag-schedule:
description: 'Template to apply to schedule tag'
default: 'nightly'
required: false
tag-custom:
description: 'List of custom tags'
required: false
tag-custom-only:
description: 'Only use tag-custom as Docker tags'
required: false
label-custom:
labels:
description: 'List of custom labels'
required: false
sep-tags:

522
dist/index.js generated vendored
View File

@ -56,17 +56,8 @@ exports.tmpDir = tmpDir;
function getInputs() {
return {
images: getInputList('images'),
tagSha: /true/i.test(core.getInput('tag-sha') || 'false'),
tagEdge: /true/i.test(core.getInput('tag-edge') || 'false'),
tagEdgeBranch: core.getInput('tag-edge-branch'),
tagSemver: getInputList('tag-semver'),
tagMatch: core.getInput('tag-match'),
tagMatchGroup: Number(core.getInput('tag-match-group')) || 0,
tagLatest: /true/i.test(core.getInput('tag-latest') || core.getInput('tag-match-latest') || 'true'),
tagSchedule: core.getInput('tag-schedule') || 'nightly',
tagCustom: getInputList('tag-custom'),
tagCustomOnly: /true/i.test(core.getInput('tag-custom-only') || 'false'),
labelCustom: getInputList('label-custom', true),
tags: getInputList('tags', true),
labels: getInputList('labels', true),
sepTags: core.getInput('sep-tags') || `\n`,
sepLabels: core.getInput('sep-labels') || `\n`,
githubToken: core.getInput('github-token')
@ -226,7 +217,7 @@ function run() {
core.endGroup();
core.setOutput('version', version.main || '');
// Docker tags
const tags = meta.tags();
const tags = meta.getTags();
core.startGroup(`Docker tags`);
for (let tag of tags) {
core.info(tag);
@ -234,7 +225,7 @@ function run() {
core.endGroup();
core.setOutput('tags', tags.join(inputs.sepTags));
// Docker labels
const labels = meta.labels();
const labels = meta.getLabels();
core.startGroup(`Docker labels`);
for (let label of labels) {
core.info(label);
@ -242,7 +233,7 @@ function run() {
core.endGroup();
core.setOutput('labels', labels.join(inputs.sepLabels));
// Bake definition file
const bakeFile = meta.bakeFile();
const bakeFile = meta.getBakeFile();
core.startGroup(`Bake definition file`);
core.info(fs.readFileSync(bakeFile, 'utf8'));
core.endGroup();
@ -293,99 +284,270 @@ const path = __importStar(__webpack_require__(5622));
const moment_1 = __importDefault(__webpack_require__(9623));
const semver = __importStar(__webpack_require__(1383));
const context_1 = __webpack_require__(3842);
const tcl = __importStar(__webpack_require__(2829));
const core = __importStar(__webpack_require__(2186));
class Meta {
constructor(inputs, context, repo) {
this.inputs = inputs;
if (!this.inputs.tagEdgeBranch) {
this.inputs.tagEdgeBranch = repo.default_branch;
}
this.context = context;
this.repo = repo;
this.tags = tcl.Transform(inputs.tags);
this.date = new Date();
this.version = this.getVersion();
}
getVersion() {
const currentDate = this.date;
let version = {
main: undefined,
partial: [],
latest: false
latest: undefined
};
if (/schedule/.test(this.context.eventName)) {
version.main = handlebars.compile(this.inputs.tagSchedule)({
date: function (format) {
return moment_1.default(currentDate).utc().format(format);
for (const tag of this.tags) {
switch (tag.type) {
case tcl.Type.Schedule: {
version = this.procSchedule(version, tag);
break;
}
});
}
else if (/^refs\/tags\//.test(this.context.ref)) {
version.main = this.context.ref.replace(/^refs\/tags\//g, '').replace(/\//g, '-');
if (this.inputs.tagSemver.length > 0 && !semver.valid(version.main)) {
core.warning(`${version.main} is not a valid semver. More info: https://semver.org/`);
}
if (this.inputs.tagSemver.length > 0 && semver.valid(version.main)) {
const sver = semver.parse(version.main, {
includePrerelease: true
});
if (semver.prerelease(version.main)) {
version.main = handlebars.compile('{{version}}')(sver);
case tcl.Type.Semver: {
version = this.procSemver(version, tag);
break;
}
else {
version.latest = this.inputs.tagLatest;
version.main = handlebars.compile(this.inputs.tagSemver[0])(sver);
for (const semverTpl of this.inputs.tagSemver) {
const partial = handlebars.compile(semverTpl)(sver);
if (partial == version.main) {
continue;
}
version.partial.push(partial);
}
case tcl.Type.Match: {
version = this.procMatch(version, tag);
break;
}
}
else if (this.inputs.tagMatch) {
let tagMatch;
const isRegEx = this.inputs.tagMatch.match(/^\/(.+)\/(.*)$/);
if (isRegEx) {
tagMatch = version.main.match(new RegExp(isRegEx[1], isRegEx[2]));
case tcl.Type.Ref: {
version = this.procRef(version, tag);
break;
}
else {
tagMatch = version.main.match(this.inputs.tagMatch);
case tcl.Type.Edge: {
version = this.procEdge(version, tag);
break;
}
if (tagMatch) {
version.main = tagMatch[this.inputs.tagMatchGroup];
version.latest = this.inputs.tagLatest;
case tcl.Type.Raw: {
version = this.procRaw(version, tag);
break;
}
case tcl.Type.Sha: {
version = this.procSha(version, tag);
break;
}
}
else {
version.latest = this.inputs.tagLatest;
}
}
else if (/^refs\/heads\//.test(this.context.ref)) {
version.main = this.context.ref.replace(/^refs\/heads\//g, '').replace(/[^a-zA-Z0-9._-]+/g, '-');
if (this.inputs.tagEdge && this.inputs.tagEdgeBranch === version.main) {
version.main = 'edge';
}
}
else if (/^refs\/pull\//.test(this.context.ref)) {
version.main = `pr-${this.context.ref.replace(/^refs\/pull\//g, '').replace(/\/merge$/g, '')}`;
}
if (this.inputs.tagCustom.length > 0) {
if (this.inputs.tagCustomOnly) {
version = {
main: this.inputs.tagCustom.shift(),
partial: this.inputs.tagCustom,
latest: false
};
}
else {
version.partial.push(...this.inputs.tagCustom);
}
}
version.partial = version.partial.filter((item, index) => version.partial.indexOf(item) === index);
if (version.latest == undefined) {
version.latest = false;
}
return version;
}
tags() {
procSchedule(version, tag) {
if (!/schedule/.test(this.context.eventName)) {
return version;
}
const currentDate = this.date;
const vraw = handlebars.compile(tag.attrs['pattern'])({
date: function (format) {
return moment_1.default(currentDate).utc().format(format);
}
});
if (version.main == undefined) {
version.main = vraw;
}
else if (vraw !== version.main) {
version.partial.push(vraw);
}
if (version.latest == undefined) {
version.latest = tag.attrs['latest'] == 'auto' ? false : tag.attrs['latest'] == 'true';
}
return version;
}
procSemver(version, tag) {
if (!/^refs\/tags\//.test(this.context.ref)) {
return version;
}
let vraw = this.context.ref.replace(/^refs\/tags\//g, '').replace(/\//g, '-');
if (!semver.valid(vraw)) {
core.warning(`${vraw} is not a valid semver. More info: https://semver.org/`);
return version;
}
let latest = false;
const sver = semver.parse(vraw, {
includePrerelease: true
});
if (semver.prerelease(vraw)) {
vraw = handlebars.compile('{{version}}')(sver);
if (version.main == undefined) {
version.main = vraw;
}
else if (vraw !== version.main) {
version.partial.push(vraw);
}
}
else {
vraw = handlebars.compile(tag.attrs['pattern'])(sver);
if (version.main == undefined) {
version.main = vraw;
}
else if (vraw !== version.main) {
version.partial.push(vraw);
}
latest = true;
}
if (version.latest == undefined) {
version.latest = tag.attrs['latest'] == 'auto' ? latest : tag.attrs['latest'] == 'true';
}
return version;
}
procMatch(version, tag) {
if (!/^refs\/tags\//.test(this.context.ref)) {
return version;
}
let vraw = this.context.ref.replace(/^refs\/tags\//g, '').replace(/\//g, '-');
let latest = false;
let tmatch;
const isRegEx = tag.attrs['pattern'].match(/^\/(.+)\/(.*)$/);
if (isRegEx) {
tmatch = vraw.match(new RegExp(isRegEx[1], isRegEx[2]));
}
else {
tmatch = vraw.match(tag.attrs['pattern']);
}
if (tmatch) {
vraw = tmatch[tag.attrs['group']];
latest = true;
}
if (version.main == undefined) {
version.main = vraw;
}
else if (vraw !== version.main) {
version.partial.push(vraw);
}
if (version.latest == undefined) {
version.latest = tag.attrs['latest'] == 'auto' ? latest : tag.attrs['latest'] == 'true';
}
return version;
}
procRef(version, tag) {
if (tag.attrs['event'] == tcl.RefEvent.Branch) {
return this.procRefBranch(version, tag);
}
else if (tag.attrs['event'] == tcl.RefEvent.Tag) {
return this.procRefTag(version, tag);
}
else if (tag.attrs['event'] == tcl.RefEvent.PR) {
return this.procRefPr(version, tag);
}
return version;
}
procRefBranch(version, tag) {
if (!/^refs\/heads\//.test(this.context.ref)) {
return version;
}
const vraw = this.setFlavor(this.context.ref.replace(/^refs\/heads\//g, '').replace(/[^a-zA-Z0-9._-]+/g, '-'), tag);
if (version.main == undefined) {
version.main = vraw;
}
else if (vraw !== version.main) {
version.partial.push(vraw);
}
if (version.latest == undefined) {
version.latest = tag.attrs['latest'] == 'auto' ? false : tag.attrs['latest'] == 'true';
}
return version;
}
procRefTag(version, tag) {
if (!/^refs\/tags\//.test(this.context.ref)) {
return version;
}
const vraw = this.setFlavor(this.context.ref.replace(/^refs\/tags\//g, '').replace(/\//g, '-'), tag);
if (version.main == undefined) {
version.main = vraw;
}
else if (vraw !== version.main) {
version.partial.push(vraw);
}
if (version.latest == undefined) {
version.latest = tag.attrs['latest'] == 'auto' ? true : tag.attrs['latest'] == 'true';
}
return version;
}
procRefPr(version, tag) {
if (!/^refs\/pull\//.test(this.context.ref)) {
return version;
}
const vraw = this.setFlavor(this.context.ref.replace(/^refs\/pull\//g, '').replace(/\/merge$/g, ''), tag);
if (version.main == undefined) {
version.main = vraw;
}
else if (vraw !== version.main) {
version.partial.push(vraw);
}
if (version.latest == undefined) {
version.latest = tag.attrs['latest'] == 'auto' ? false : tag.attrs['latest'] == 'true';
}
return version;
}
procEdge(version, tag) {
if (!/^refs\/heads\//.test(this.context.ref)) {
return version;
}
let val = this.context.ref.replace(/^refs\/heads\//g, '').replace(/[^a-zA-Z0-9._-]+/g, '-');
if (tag.attrs['branch'].length == 0) {
tag.attrs['branch'] = this.repo.default_branch;
}
if (tag.attrs['branch'] === val) {
val = 'edge';
}
const vraw = this.setFlavor(val, tag);
if (version.main == undefined) {
version.main = vraw;
}
else if (vraw !== version.main) {
version.partial.push(vraw);
}
if (version.latest == undefined) {
version.latest = tag.attrs['latest'] == 'auto' ? false : tag.attrs['latest'] == 'true';
}
return version;
}
procRaw(version, tag) {
const vraw = this.setFlavor(tag.attrs['value'], tag);
if (version.main == undefined) {
version.main = vraw;
}
else if (vraw !== version.main) {
version.partial.push(vraw);
}
if (version.latest == undefined) {
version.latest = tag.attrs['latest'] == 'auto' ? false : tag.attrs['latest'] == 'true';
}
return version;
}
procSha(version, tag) {
if (!this.context.sha) {
return version;
}
const vraw = this.setFlavor(this.context.sha.substr(0, 7), tag);
if (version.main == undefined) {
version.main = vraw;
}
else if (vraw !== version.main) {
version.partial.push(vraw);
}
if (version.latest == undefined) {
version.latest = tag.attrs['latest'] == 'auto' ? false : tag.attrs['latest'] == 'true';
}
return version;
}
setFlavor(val, tag) {
if (tag.attrs['prefix'].length > 0) {
val = `${tag.attrs['prefix']}${val}`;
}
if (tag.attrs['suffix'].length > 0) {
val = `${val}${tag.attrs['suffix']}`;
}
return val;
}
getTags() {
if (!this.version.main) {
return [];
}
@ -399,13 +561,10 @@ class Meta {
if (this.version.latest) {
tags.push(`${imageLc}:latest`);
}
if (this.context.sha && this.inputs.tagSha) {
tags.push(`${imageLc}:sha-${this.context.sha.substr(0, 7)}`);
}
}
return tags;
}
labels() {
getLabels() {
var _a;
let labels = [
`org.opencontainers.image.title=${this.repo.name || ''}`,
@ -417,12 +576,12 @@ class Meta {
`org.opencontainers.image.revision=${this.context.sha || ''}`,
`org.opencontainers.image.licenses=${((_a = this.repo.license) === null || _a === void 0 ? void 0 : _a.spdx_id) || ''}`
];
labels.push(...this.inputs.labelCustom);
labels.push(...this.inputs.labels);
return labels;
}
bakeFile() {
getBakeFile() {
let jsonLabels = {};
for (let label of this.labels()) {
for (let label of this.getLabels()) {
const matches = label.match(/([^=]*)=(.*)/);
if (!matches) {
continue;
@ -433,7 +592,7 @@ class Meta {
fs.writeFileSync(bakeFile, JSON.stringify({
target: {
'ghaction-docker-meta': {
tags: this.tags(),
tags: this.getTags(),
labels: jsonLabels,
args: {
DOCKER_META_IMAGES: this.inputs.images.join(','),
@ -450,6 +609,189 @@ exports.Meta = Meta;
/***/ }),
/***/ 2829:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.Parse = exports.Transform = exports.DefaultPriorities = exports.RefEvents = exports.RefEvent = exports.Type = void 0;
const sync_1 = __importDefault(__webpack_require__(8750));
var Type;
(function (Type) {
Type["Raw"] = "raw";
Type["Schedule"] = "schedule";
Type["Semver"] = "semver";
Type["Match"] = "match";
Type["Edge"] = "edge";
Type["Ref"] = "ref";
Type["Sha"] = "sha";
})(Type = exports.Type || (exports.Type = {}));
var RefEvent;
(function (RefEvent) {
RefEvent["Branch"] = "branch";
RefEvent["Tag"] = "tag";
RefEvent["PR"] = "pr";
})(RefEvent = exports.RefEvent || (exports.RefEvent = {}));
exports.RefEvents = Object.keys(RefEvent).map(key => RefEvent[key]);
exports.DefaultPriorities = {
[Type.Schedule]: '1000',
[Type.Semver]: '900',
[Type.Match]: '800',
[Type.Edge]: '700',
[Type.Ref]: '600',
[Type.Raw]: '200',
[Type.Sha]: '100'
};
function Transform(inputs) {
const tags = [];
if (inputs.length == 0) {
// prettier-ignore
inputs = [
`type=schedule`,
`type=ref,event=${RefEvent.Branch}`,
`type=ref,event=${RefEvent.Tag}`,
`type=ref,event=${RefEvent.PR}`
];
}
for (const input of inputs) {
tags.push(Parse(input));
}
return tags.sort((tag1, tag2) => {
if (Number(tag1.attrs['priority']) < Number(tag2.attrs['priority'])) {
return 1;
}
if (Number(tag1.attrs['priority']) > Number(tag2.attrs['priority'])) {
return -1;
}
return 0;
});
}
exports.Transform = Transform;
function Parse(s) {
const fields = sync_1.default(s, {
relaxColumnCount: true,
skipLinesWithEmptyValues: true
})[0];
const tag = {
attrs: {}
};
for (const field of fields) {
const parts = field.toString().split('=', 2);
if (parts.length == 1) {
tag.attrs['value'] = parts[0].trim();
}
else if (parts.length == 2) {
const key = parts[0].trim().toLowerCase();
const value = parts[1].trim();
switch (key) {
case 'type': {
if (!Object.values(Type).includes(value)) {
throw new Error(`Unknown type attribute: ${value}`);
}
tag.type = value;
break;
}
default: {
tag.attrs[key] = value;
break;
}
}
}
else {
throw new Error(`Invalid entry: ${field}`);
}
}
if (tag.type == undefined) {
tag.type = Type.Raw;
}
switch (tag.type) {
case Type.Schedule: {
if (!tag.attrs.hasOwnProperty('pattern')) {
tag.attrs['pattern'] = 'nightly';
}
break;
}
case Type.Semver: {
if (!tag.attrs.hasOwnProperty('pattern')) {
throw new Error(`Missing pattern attribute for ${s}`);
}
break;
}
case Type.Match: {
if (!tag.attrs.hasOwnProperty('pattern')) {
throw new Error(`Missing pattern attribute for ${s}`);
}
if (!tag.attrs.hasOwnProperty('group')) {
tag.attrs['group'] = '0';
}
if (isNaN(+tag.attrs['group'])) {
throw new Error(`Invalid match group for ${s}`);
}
break;
}
case Type.Edge: {
if (!tag.attrs.hasOwnProperty('branch')) {
tag.attrs['branch'] = '';
}
break;
}
case Type.Ref: {
if (!tag.attrs.hasOwnProperty('event')) {
throw new Error(`Missing event attribute for ${s}`);
}
if (!exports.RefEvents.includes(tag.attrs['event'])) {
throw new Error(`Invalid event for ${s}`);
}
if (tag.attrs['event'] == RefEvent.PR && !tag.attrs.hasOwnProperty('prefix')) {
tag.attrs['prefix'] = 'pr-';
}
break;
}
case Type.Raw: {
if (!tag.attrs.hasOwnProperty('value')) {
throw new Error(`Missing value attribute for ${s}`);
}
break;
}
case Type.Sha: {
if (!tag.attrs.hasOwnProperty('prefix')) {
tag.attrs['prefix'] = 'sha-';
}
break;
}
}
if (!tag.attrs.hasOwnProperty('enable')) {
tag.attrs['enable'] = 'true';
}
if (!tag.attrs.hasOwnProperty('priority')) {
tag.attrs['priority'] = exports.DefaultPriorities[tag.type];
}
if (!tag.attrs.hasOwnProperty('latest')) {
tag.attrs['latest'] = 'auto';
}
if (!tag.attrs.hasOwnProperty('prefix')) {
tag.attrs['prefix'] = '';
}
if (!tag.attrs.hasOwnProperty('suffix')) {
tag.attrs['suffix'] = '';
}
if (!['true', 'false'].includes(tag.attrs['enable'])) {
throw new Error(`Invalid value for enable attribute: ${tag.attrs['enable']}`);
}
if (!['auto', 'true', 'false'].includes(tag.attrs['latest'])) {
throw new Error(`Invalid value for latest attribute: ${tag.attrs['latest']}`);
}
return tag;
}
exports.Parse = Parse;
//# sourceMappingURL=tag.js.map
/***/ }),
/***/ 7351:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

View File

@ -8,17 +8,8 @@ let _tmpDir: string;
export interface Inputs {
images: string[];
tagSha: boolean;
tagEdge: boolean;
tagEdgeBranch: string;
tagSemver: string[];
tagMatch: string;
tagMatchGroup: number;
tagLatest: boolean;
tagSchedule: string;
tagCustom: string[];
tagCustomOnly: boolean;
labelCustom: string[];
tags: string[];
labels: string[];
sepTags: string;
sepLabels: string;
githubToken: string;
@ -34,17 +25,8 @@ export function tmpDir(): string {
export function getInputs(): Inputs {
return {
images: getInputList('images'),
tagSha: /true/i.test(core.getInput('tag-sha') || 'false'),
tagEdge: /true/i.test(core.getInput('tag-edge') || 'false'),
tagEdgeBranch: core.getInput('tag-edge-branch'),
tagSemver: getInputList('tag-semver'),
tagMatch: core.getInput('tag-match'),
tagMatchGroup: Number(core.getInput('tag-match-group')) || 0,
tagLatest: /true/i.test(core.getInput('tag-latest') || core.getInput('tag-match-latest') || 'true'),
tagSchedule: core.getInput('tag-schedule') || 'nightly',
tagCustom: getInputList('tag-custom'),
tagCustomOnly: /true/i.test(core.getInput('tag-custom-only') || 'false'),
labelCustom: getInputList('label-custom', true),
tags: getInputList('tags', true),
labels: getInputList('labels', true),
sepTags: core.getInput('sep-tags') || `\n`,
sepLabels: core.getInput('sep-labels') || `\n`,
githubToken: core.getInput('github-token')

View File

@ -35,7 +35,7 @@ async function run() {
core.setOutput('version', version.main || '');
// Docker tags
const tags: Array<string> = meta.tags();
const tags: Array<string> = meta.getTags();
core.startGroup(`Docker tags`);
for (let tag of tags) {
core.info(tag);
@ -44,7 +44,7 @@ async function run() {
core.setOutput('tags', tags.join(inputs.sepTags));
// Docker labels
const labels: Array<string> = meta.labels();
const labels: Array<string> = meta.getLabels();
core.startGroup(`Docker labels`);
for (let label of labels) {
core.info(label);
@ -53,7 +53,7 @@ async function run() {
core.setOutput('labels', labels.join(inputs.sepLabels));
// Bake definition file
const bakeFile: string = meta.bakeFile();
const bakeFile: string = meta.getBakeFile();
core.startGroup(`Bake definition file`);
core.info(fs.readFileSync(bakeFile, 'utf8'));
core.endGroup();

View File

@ -4,6 +4,7 @@ import * as path from 'path';
import moment from 'moment';
import * as semver from 'semver';
import {Inputs, tmpDir} from './context';
import * as tcl from './tag';
import * as core from '@actions/core';
import {Context} from '@actions/github/lib/context';
import {ReposGetResponseData} from '@octokit/types';
@ -11,7 +12,7 @@ import {ReposGetResponseData} from '@octokit/types';
export interface Version {
main: string | undefined;
partial: string[];
latest: boolean;
latest: boolean | undefined;
}
export class Meta {
@ -20,96 +21,292 @@ export class Meta {
private readonly inputs: Inputs;
private readonly context: Context;
private readonly repo: ReposGetResponseData;
private readonly tags: tcl.Tag[];
private readonly date: Date;
constructor(inputs: Inputs, context: Context, repo: ReposGetResponseData) {
this.inputs = inputs;
if (!this.inputs.tagEdgeBranch) {
this.inputs.tagEdgeBranch = repo.default_branch;
}
this.context = context;
this.repo = repo;
this.tags = tcl.Transform(inputs.tags);
this.date = new Date();
this.version = this.getVersion();
}
private getVersion(): Version {
const currentDate = this.date;
let version: Version = {
main: undefined,
partial: [],
latest: false
latest: undefined
};
if (/schedule/.test(this.context.eventName)) {
version.main = handlebars.compile(this.inputs.tagSchedule)({
date: function (format) {
return moment(currentDate).utc().format(format);
for (const tag of this.tags) {
switch (tag.type) {
case tcl.Type.Schedule: {
version = this.procSchedule(version, tag);
break;
}
});
} else if (/^refs\/tags\//.test(this.context.ref)) {
version.main = this.context.ref.replace(/^refs\/tags\//g, '').replace(/\//g, '-');
if (this.inputs.tagSemver.length > 0 && !semver.valid(version.main)) {
core.warning(`${version.main} is not a valid semver. More info: https://semver.org/`);
}
if (this.inputs.tagSemver.length > 0 && semver.valid(version.main)) {
const sver = semver.parse(version.main, {
includePrerelease: true
});
if (semver.prerelease(version.main)) {
version.main = handlebars.compile('{{version}}')(sver);
} else {
version.latest = this.inputs.tagLatest;
version.main = handlebars.compile(this.inputs.tagSemver[0])(sver);
for (const semverTpl of this.inputs.tagSemver) {
const partial = handlebars.compile(semverTpl)(sver);
if (partial == version.main) {
continue;
}
version.partial.push(partial);
}
case tcl.Type.Semver: {
version = this.procSemver(version, tag);
break;
}
} else if (this.inputs.tagMatch) {
let tagMatch;
const isRegEx = this.inputs.tagMatch.match(/^\/(.+)\/(.*)$/);
if (isRegEx) {
tagMatch = version.main.match(new RegExp(isRegEx[1], isRegEx[2]));
} else {
tagMatch = version.main.match(this.inputs.tagMatch);
case tcl.Type.Match: {
version = this.procMatch(version, tag);
break;
}
if (tagMatch) {
version.main = tagMatch[this.inputs.tagMatchGroup];
version.latest = this.inputs.tagLatest;
case tcl.Type.Ref: {
version = this.procRef(version, tag);
break;
}
case tcl.Type.Edge: {
version = this.procEdge(version, tag);
break;
}
case tcl.Type.Raw: {
version = this.procRaw(version, tag);
break;
}
case tcl.Type.Sha: {
version = this.procSha(version, tag);
break;
}
} else {
version.latest = this.inputs.tagLatest;
}
} else if (/^refs\/heads\//.test(this.context.ref)) {
version.main = this.context.ref.replace(/^refs\/heads\//g, '').replace(/[^a-zA-Z0-9._-]+/g, '-');
if (this.inputs.tagEdge && this.inputs.tagEdgeBranch === version.main) {
version.main = 'edge';
}
} else if (/^refs\/pull\//.test(this.context.ref)) {
version.main = `pr-${this.context.ref.replace(/^refs\/pull\//g, '').replace(/\/merge$/g, '')}`;
}
if (this.inputs.tagCustom.length > 0) {
if (this.inputs.tagCustomOnly) {
version = {
main: this.inputs.tagCustom.shift(),
partial: this.inputs.tagCustom,
latest: false
};
} else {
version.partial.push(...this.inputs.tagCustom);
}
}
version.partial = version.partial.filter((item, index) => version.partial.indexOf(item) === index);
if (version.latest == undefined) {
version.latest = false;
}
return version;
}
public tags(): Array<string> {
private procSchedule(version: Version, tag: tcl.Tag): Version {
if (!/schedule/.test(this.context.eventName)) {
return version;
}
const currentDate = this.date;
const vraw = handlebars.compile(tag.attrs['pattern'])({
date: function (format) {
return moment(currentDate).utc().format(format);
}
});
if (version.main == undefined) {
version.main = vraw;
} else if (vraw !== version.main) {
version.partial.push(vraw);
}
if (version.latest == undefined) {
version.latest = tag.attrs['latest'] == 'auto' ? false : tag.attrs['latest'] == 'true';
}
return version;
}
private procSemver(version: Version, tag: tcl.Tag): Version {
if (!/^refs\/tags\//.test(this.context.ref)) {
return version;
}
let vraw = this.context.ref.replace(/^refs\/tags\//g, '').replace(/\//g, '-');
if (!semver.valid(vraw)) {
core.warning(`${vraw} is not a valid semver. More info: https://semver.org/`);
return version;
}
let latest: boolean = false;
const sver = semver.parse(vraw, {
includePrerelease: true
});
if (semver.prerelease(vraw)) {
vraw = handlebars.compile('{{version}}')(sver);
if (version.main == undefined) {
version.main = vraw;
} else if (vraw !== version.main) {
version.partial.push(vraw);
}
} else {
vraw = handlebars.compile(tag.attrs['pattern'])(sver);
if (version.main == undefined) {
version.main = vraw;
} else if (vraw !== version.main) {
version.partial.push(vraw);
}
latest = true;
}
if (version.latest == undefined) {
version.latest = tag.attrs['latest'] == 'auto' ? latest : tag.attrs['latest'] == 'true';
}
return version;
}
private procMatch(version: Version, tag: tcl.Tag): Version {
if (!/^refs\/tags\//.test(this.context.ref)) {
return version;
}
let vraw = this.context.ref.replace(/^refs\/tags\//g, '').replace(/\//g, '-');
let latest: boolean = false;
let tmatch;
const isRegEx = tag.attrs['pattern'].match(/^\/(.+)\/(.*)$/);
if (isRegEx) {
tmatch = vraw.match(new RegExp(isRegEx[1], isRegEx[2]));
} else {
tmatch = vraw.match(tag.attrs['pattern']);
}
if (tmatch) {
vraw = tmatch[tag.attrs['group']];
latest = true;
}
if (version.main == undefined) {
version.main = vraw;
} else if (vraw !== version.main) {
version.partial.push(vraw);
}
if (version.latest == undefined) {
version.latest = tag.attrs['latest'] == 'auto' ? latest : tag.attrs['latest'] == 'true';
}
return version;
}
private procRef(version: Version, tag: tcl.Tag): Version {
if (tag.attrs['event'] == tcl.RefEvent.Branch) {
return this.procRefBranch(version, tag);
} else if (tag.attrs['event'] == tcl.RefEvent.Tag) {
return this.procRefTag(version, tag);
} else if (tag.attrs['event'] == tcl.RefEvent.PR) {
return this.procRefPr(version, tag);
}
return version;
}
private procRefBranch(version: Version, tag: tcl.Tag): Version {
if (!/^refs\/heads\//.test(this.context.ref)) {
return version;
}
const vraw = this.setFlavor(this.context.ref.replace(/^refs\/heads\//g, '').replace(/[^a-zA-Z0-9._-]+/g, '-'), tag);
if (version.main == undefined) {
version.main = vraw;
} else if (vraw !== version.main) {
version.partial.push(vraw);
}
if (version.latest == undefined) {
version.latest = tag.attrs['latest'] == 'auto' ? false : tag.attrs['latest'] == 'true';
}
return version;
}
private procRefTag(version: Version, tag: tcl.Tag): Version {
if (!/^refs\/tags\//.test(this.context.ref)) {
return version;
}
const vraw = this.setFlavor(this.context.ref.replace(/^refs\/tags\//g, '').replace(/\//g, '-'), tag);
if (version.main == undefined) {
version.main = vraw;
} else if (vraw !== version.main) {
version.partial.push(vraw);
}
if (version.latest == undefined) {
version.latest = tag.attrs['latest'] == 'auto' ? true : tag.attrs['latest'] == 'true';
}
return version;
}
private procRefPr(version: Version, tag: tcl.Tag): Version {
if (!/^refs\/pull\//.test(this.context.ref)) {
return version;
}
const vraw = this.setFlavor(this.context.ref.replace(/^refs\/pull\//g, '').replace(/\/merge$/g, ''), tag);
if (version.main == undefined) {
version.main = vraw;
} else if (vraw !== version.main) {
version.partial.push(vraw);
}
if (version.latest == undefined) {
version.latest = tag.attrs['latest'] == 'auto' ? false : tag.attrs['latest'] == 'true';
}
return version;
}
private procEdge(version: Version, tag: tcl.Tag): Version {
if (!/^refs\/heads\//.test(this.context.ref)) {
return version;
}
let val = this.context.ref.replace(/^refs\/heads\//g, '').replace(/[^a-zA-Z0-9._-]+/g, '-');
if (tag.attrs['branch'].length == 0) {
tag.attrs['branch'] = this.repo.default_branch;
}
if (tag.attrs['branch'] === val) {
val = 'edge';
}
const vraw = this.setFlavor(val, tag);
if (version.main == undefined) {
version.main = vraw;
} else if (vraw !== version.main) {
version.partial.push(vraw);
}
if (version.latest == undefined) {
version.latest = tag.attrs['latest'] == 'auto' ? false : tag.attrs['latest'] == 'true';
}
return version;
}
private procRaw(version: Version, tag: tcl.Tag): Version {
const vraw = this.setFlavor(tag.attrs['value'], tag);
if (version.main == undefined) {
version.main = vraw;
} else if (vraw !== version.main) {
version.partial.push(vraw);
}
if (version.latest == undefined) {
version.latest = tag.attrs['latest'] == 'auto' ? false : tag.attrs['latest'] == 'true';
}
return version;
}
private procSha(version: Version, tag: tcl.Tag): Version {
if (!this.context.sha) {
return version;
}
const vraw = this.setFlavor(this.context.sha.substr(0, 7), tag);
if (version.main == undefined) {
version.main = vraw;
} else if (vraw !== version.main) {
version.partial.push(vraw);
}
if (version.latest == undefined) {
version.latest = tag.attrs['latest'] == 'auto' ? false : tag.attrs['latest'] == 'true';
}
return version;
}
private setFlavor(val: string, tag: tcl.Tag): string {
if (tag.attrs['prefix'].length > 0) {
val = `${tag.attrs['prefix']}${val}`;
}
if (tag.attrs['suffix'].length > 0) {
val = `${val}${tag.attrs['suffix']}`;
}
return val;
}
public getTags(): Array<string> {
if (!this.version.main) {
return [];
}
@ -124,14 +321,11 @@ export class Meta {
if (this.version.latest) {
tags.push(`${imageLc}:latest`);
}
if (this.context.sha && this.inputs.tagSha) {
tags.push(`${imageLc}:sha-${this.context.sha.substr(0, 7)}`);
}
}
return tags;
}
public labels(): Array<string> {
public getLabels(): Array<string> {
let labels: Array<string> = [
`org.opencontainers.image.title=${this.repo.name || ''}`,
`org.opencontainers.image.description=${this.repo.description || ''}`,
@ -142,13 +336,13 @@ export class Meta {
`org.opencontainers.image.revision=${this.context.sha || ''}`,
`org.opencontainers.image.licenses=${this.repo.license?.spdx_id || ''}`
];
labels.push(...this.inputs.labelCustom);
labels.push(...this.inputs.labels);
return labels;
}
public bakeFile(): string {
public getBakeFile(): string {
let jsonLabels = {};
for (let label of this.labels()) {
for (let label of this.getLabels()) {
const matches = label.match(/([^=]*)=(.*)/);
if (!matches) {
continue;
@ -163,7 +357,7 @@ export class Meta {
{
target: {
'ghaction-docker-meta': {
tags: this.tags(),
tags: this.getTags(),
labels: jsonLabels,
args: {
DOCKER_META_IMAGES: this.inputs.images.join(','),

180
src/tag.ts Normal file
View File

@ -0,0 +1,180 @@
import csvparse from 'csv-parse/lib/sync';
export enum Type {
Raw = 'raw',
Schedule = 'schedule',
Semver = 'semver',
Match = 'match',
Edge = 'edge',
Ref = 'ref',
Sha = 'sha'
}
export interface Tag {
type: Type;
attrs: Record<string, string>;
}
export enum RefEvent {
Branch = 'branch',
Tag = 'tag',
PR = 'pr'
}
export const RefEvents = Object.keys(RefEvent).map(key => RefEvent[key]);
export const DefaultPriorities: Record<Type, string> = {
[Type.Schedule]: '1000',
[Type.Semver]: '900',
[Type.Match]: '800',
[Type.Edge]: '700',
[Type.Ref]: '600',
[Type.Raw]: '200',
[Type.Sha]: '100'
};
export function Transform(inputs: string[]): Tag[] {
const tags: Tag[] = [];
if (inputs.length == 0) {
// prettier-ignore
inputs = [
`type=schedule`,
`type=ref,event=${RefEvent.Branch}`,
`type=ref,event=${RefEvent.Tag}`,
`type=ref,event=${RefEvent.PR}`
];
}
for (const input of inputs) {
tags.push(Parse(input));
}
return tags.sort((tag1, tag2) => {
if (Number(tag1.attrs['priority']) < Number(tag2.attrs['priority'])) {
return 1;
}
if (Number(tag1.attrs['priority']) > Number(tag2.attrs['priority'])) {
return -1;
}
return 0;
});
}
export function Parse(s: string): Tag {
const fields = csvparse(s, {
relaxColumnCount: true,
skipLinesWithEmptyValues: true
})[0];
const tag = {
attrs: {}
} as Tag;
for (const field of fields) {
const parts = field.toString().split('=', 2);
if (parts.length == 1) {
tag.attrs['value'] = parts[0].trim();
} else if (parts.length == 2) {
const key = parts[0].trim().toLowerCase();
const value = parts[1].trim();
switch (key) {
case 'type': {
if (!Object.values(Type).includes(value)) {
throw new Error(`Unknown type attribute: ${value}`);
}
tag.type = value;
break;
}
default: {
tag.attrs[key] = value;
break;
}
}
} else {
throw new Error(`Invalid entry: ${field}`);
}
}
if (tag.type == undefined) {
tag.type = Type.Raw;
}
switch (tag.type) {
case Type.Schedule: {
if (!tag.attrs.hasOwnProperty('pattern')) {
tag.attrs['pattern'] = 'nightly';
}
break;
}
case Type.Semver: {
if (!tag.attrs.hasOwnProperty('pattern')) {
throw new Error(`Missing pattern attribute for ${s}`);
}
break;
}
case Type.Match: {
if (!tag.attrs.hasOwnProperty('pattern')) {
throw new Error(`Missing pattern attribute for ${s}`);
}
if (!tag.attrs.hasOwnProperty('group')) {
tag.attrs['group'] = '0';
}
if (isNaN(+tag.attrs['group'])) {
throw new Error(`Invalid match group for ${s}`);
}
break;
}
case Type.Edge: {
if (!tag.attrs.hasOwnProperty('branch')) {
tag.attrs['branch'] = '';
}
break;
}
case Type.Ref: {
if (!tag.attrs.hasOwnProperty('event')) {
throw new Error(`Missing event attribute for ${s}`);
}
if (!RefEvents.includes(tag.attrs['event'])) {
throw new Error(`Invalid event for ${s}`);
}
if (tag.attrs['event'] == RefEvent.PR && !tag.attrs.hasOwnProperty('prefix')) {
tag.attrs['prefix'] = 'pr-';
}
break;
}
case Type.Raw: {
if (!tag.attrs.hasOwnProperty('value')) {
throw new Error(`Missing value attribute for ${s}`);
}
break;
}
case Type.Sha: {
if (!tag.attrs.hasOwnProperty('prefix')) {
tag.attrs['prefix'] = 'sha-';
}
break;
}
}
if (!tag.attrs.hasOwnProperty('enable')) {
tag.attrs['enable'] = 'true';
}
if (!tag.attrs.hasOwnProperty('priority')) {
tag.attrs['priority'] = DefaultPriorities[tag.type];
}
if (!tag.attrs.hasOwnProperty('latest')) {
tag.attrs['latest'] = 'auto';
}
if (!tag.attrs.hasOwnProperty('prefix')) {
tag.attrs['prefix'] = '';
}
if (!tag.attrs.hasOwnProperty('suffix')) {
tag.attrs['suffix'] = '';
}
if (!['true', 'false'].includes(tag.attrs['enable'])) {
throw new Error(`Invalid value for enable attribute: ${tag.attrs['enable']}`);
}
if (!['auto', 'true', 'false'].includes(tag.attrs['latest'])) {
throw new Error(`Invalid value for latest attribute: ${tag.attrs['latest']}`);
}
return tag;
}