Skip to content

Commit

Permalink
feat(nx-container): forward quiet option to metadata generation for q…
Browse files Browse the repository at this point in the history
…uiet logs
  • Loading branch information
gperdomor committed Aug 16, 2024
1 parent 2a73eef commit 12acea1
Show file tree
Hide file tree
Showing 13 changed files with 115 additions and 81 deletions.
3 changes: 3 additions & 0 deletions packages/container-metadata/src/lib/context.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ describe('getInputs', () => {
['images', 'moby/buildkit\nghcr.io/moby/mbuildkit'],
]),
{
quiet: false,
"bake-target": 'container-metadata-action',
flavor: [],
"github-token": '',
Expand All @@ -52,6 +53,7 @@ describe('getInputs', () => {
['sep-annotations', ',']
]),
{
quiet: false,
"bake-target": 'metadata',
flavor: [],
"github-token": '',
Expand All @@ -70,6 +72,7 @@ describe('getInputs', () => {
['images', 'moby/buildkit\n#comment\nghcr.io/moby/mbuildkit'],
]),
{
quiet: false,
"bake-target": 'container-metadata-action',
flavor: [],
"github-token": '',
Expand Down
2 changes: 2 additions & 0 deletions packages/container-metadata/src/lib/context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import * as core from '@nx-tools/core';
import { ExecutorContext, names } from '@nx/devkit';

export interface Inputs {
quiet?: boolean;
'bake-target': string;
'github-token': string;
'sep-annotations': string;
Expand All @@ -19,6 +20,7 @@ export function getInputs(options: Partial<Inputs>, ctx?: ExecutorContext): Inpu
const prefix = names(ctx?.projectName || '').constantName;

return {
quiet: options.quiet || false,
'bake-target': core.getInput('bake-target', {
prefix,
fallback: options['bake-target'] || 'container-metadata-action',
Expand Down
3 changes: 2 additions & 1 deletion packages/container-metadata/src/lib/flavor.spec.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { logger } from '@nx-tools/core';
import { Flavor, Transform } from './flavor';

describe('transform', () => {
Expand Down Expand Up @@ -176,7 +177,7 @@ describe('transform', () => {
]
])('given %p attributes', async (inputs: string[], expected: Flavor, invalid: boolean) => {
try {
const flavor = Transform(inputs);
const flavor = Transform(inputs, logger);
expect(flavor).toEqual(expected);
} catch (err) {
if (!invalid) {
Expand Down
4 changes: 2 additions & 2 deletions packages/container-metadata/src/lib/flavor.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { logger } from '@nx-tools/core';
import { logger as L } from '@nx-tools/core';
import { parse } from 'csv-parse/sync';

export interface Flavor {
Expand All @@ -9,7 +9,7 @@ export interface Flavor {
suffixLatest: boolean;
}

export function Transform(inputs: string[]): Flavor {
export function Transform(inputs: string[], logger: typeof L): Flavor {
const flavor: Flavor = {
latest: 'auto',
prefix: '',
Expand Down
3 changes: 2 additions & 1 deletion packages/container-metadata/src/lib/image.spec.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { logger } from '@nx-tools/core';
import { Image, Transform } from './image';

describe('transform', () => {
Expand Down Expand Up @@ -96,7 +97,7 @@ describe('transform', () => {
]
])('given %p', async (l: string[], expected: Image[] | undefined, invalid: boolean) => {
try {
const images = Transform(l);
const images = Transform(l, logger);
expect(images).toEqual(expected);
} catch (err) {
if (!invalid) {
Expand Down
10 changes: 5 additions & 5 deletions packages/container-metadata/src/lib/image.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import { logger } from '@nx-tools/core';
import { logger as L } from '@nx-tools/core';
import { parse } from 'csv-parse/sync';

export interface Image {
name: string;
enable: boolean;
}

export function Transform(inputs: string[]): Image[] {
export function Transform(inputs: string[], logger: typeof L): Image[] {
let images: Image[] = [];

// backward compatibility with old format
Expand All @@ -29,7 +29,7 @@ export function Transform(inputs: string[]): Image[] {
}
}
if (!newformat) {
return output(images);
return output(images, logger);
}
}

Expand Down Expand Up @@ -73,10 +73,10 @@ export function Transform(inputs: string[]): Image[] {
}
images.push(image);
}
return output(images);
return output(images, logger);
}

function output(images: Image[]): Image[] {
function output(images: Image[], logger: typeof L): Image[] {
const group = 'Processing images input';
logger.startGroup(group);
for (const image of images) {
Expand Down
116 changes: 67 additions & 49 deletions packages/container-metadata/src/lib/main.ts
Original file line number Diff line number Diff line change
@@ -1,44 +1,57 @@
import { RunnerContext as Context, ContextProxyFactory, RepoMetadata, RepoProxyFactory } from '@nx-tools/ci-context';
import { isDebug, logger } from '@nx-tools/core';
import { isDebug, logger as L } from '@nx-tools/core';
import { ExecutorContext } from '@nx/devkit';
import * as fs from 'node:fs';
import { Inputs, getInputs } from './context';
import { getInputs, Inputs } from './context';
import { Meta, Version } from './meta';

function setOutput(name: string, value: string) {
// core.setOutput(name, value);
// core.exportVariable(`DOCKER_METADATA_OUTPUT_${name.replace(/\W/g, '_').toUpperCase()}`, value);
}

// eslint-disable-next-line @typescript-eslint/no-empty-function
const noop = () => {};

export async function getMetadata(options: Partial<Inputs>, ctx?: ExecutorContext): Promise<Meta> {
const inputs: Inputs = getInputs(options, ctx);
const context: Context = await ContextProxyFactory.create();
const repo: RepoMetadata = await RepoProxyFactory.create(inputs['github-token']);

await logger.group(`Context info`, async () => {
logger.info(`eventName: ${context.eventName}`);
logger.info(`sha: ${context.sha}`);
logger.info(`ref: ${context.ref}`);
logger.info(`actor: ${context.actor}`);
logger.info(`runNumber: ${context.runNumber}`);
logger.info(`runId: ${context.runId}`);
});
const logger: typeof L = {
...L,
info: options.quiet ? noop : L.info,
startGroup: options.quiet ? noop : L.startGroup,
endGroup: options.quiet ? noop : L.endGroup,
};

let group = 'Context info';
logger.startGroup(group);
logger.info(`eventName: ${context.eventName}`);
logger.info(`sha: ${context.sha}`);
logger.info(`ref: ${context.ref}`);
logger.info(`actor: ${context.actor}`);
logger.info(`runNumber: ${context.runNumber}`);
logger.info(`runId: ${context.runId}`);
logger.endGroup(group);

if (isDebug()) {
await logger.group(`Context payload`, async () => {
logger.info(JSON.stringify(context.payload, null, 2));
});
const group = 'Context payload';
logger.startGroup(group);
logger.info(JSON.stringify(context.payload, null, 2));
logger.endGroup(group);
}

const meta: Meta = new Meta(inputs, context, repo);
const meta: Meta = new Meta(inputs, context, repo, logger);

const version: Version = meta.version;
if (meta.version.main == undefined || meta.version.main.length == 0) {
logger.warn(`No Docker image version has been generated. Check tags input.`);
} else {
await logger.group(`Docker image version`, async () => {
logger.info(version.main || '');
});
const group = 'Docker image version';
logger.startGroup(group);
logger.info(version.main || '');
logger.endGroup(group);
}
setOutput('version', version.main || '');

Expand All @@ -47,55 +60,60 @@ export async function getMetadata(options: Partial<Inputs>, ctx?: ExecutorContex
if (tags.length == 0) {
logger.warn('No Docker tag has been generated. Check tags input.');
} else {
await logger.group(`Docker tags`, async () => {
for (const tag of tags) {
logger.info(tag);
}
});
const group = 'Docker tags';
logger.startGroup(group);
for (const tag of tags) {
logger.info(tag);
}
logger.endGroup(group);
}
setOutput('tags', tags.join(inputs['sep-tags']));

// Docker labels
const labels: Array<string> = meta.getLabels();
await logger.group(`Docker labels`, async () => {
for (const label of labels) {
logger.info(label);
}
setOutput('labels', labels.join(inputs['sep-labels']));
});
group = 'Docker labels';
logger.startGroup(group);
for (const label of labels) {
logger.info(label);
}
setOutput('labels', labels.join(inputs['sep-labels']));
logger.endGroup(group);

// Annotations
const annotationsRaw: Array<string> = meta.getAnnotations();
const annotationsLevels = process.env.DOCKER_METADATA_ANNOTATIONS_LEVELS || 'manifest';
await logger.group(`Annotations`, async () => {
const annotations: Array<string> = [];
for (const level of annotationsLevels.split(',')) {
annotations.push(
...annotationsRaw.map((label) => {
const v = `${level}:${label}`;
logger.info(v);
return v;
})
);
}
setOutput(`annotations`, annotations.join(inputs['sep-annotations']));
});
group = 'Annotations';
logger.startGroup(group);
const annotations: Array<string> = [];
for (const level of annotationsLevels.split(',')) {
annotations.push(
...annotationsRaw.map((label) => {
const v = `${level}:${label}`;
logger.info(v);
return v;
})
);
}
setOutput(`annotations`, annotations.join(inputs['sep-annotations']));
logger.endGroup(group);

// JSON
const jsonOutput = meta.getJSON(annotationsLevels.split(','));
await logger.group(`JSON output`, async () => {
logger.info(JSON.stringify(jsonOutput, null, 2));
setOutput('json', JSON.stringify(jsonOutput));
});
group = 'JSON output';
logger.startGroup(group);
logger.info(JSON.stringify(jsonOutput, null, 2));
setOutput('json', JSON.stringify(jsonOutput));
logger.endGroup(group);

// Bake files
for (const kind of ['tags', 'labels', 'annotations:' + annotationsLevels]) {
const outputName = kind.split(':')[0];
const bakeFile: string = meta.getBakeFile(kind);
await logger.group(`Bake file definition (${outputName})`, async () => {
logger.info(fs.readFileSync(bakeFile, 'utf8'));
setOutput(`bake-file-${outputName}`, bakeFile);
});
const group = `Bake file definition (${outputName})`;
logger.startGroup(group);
logger.info(fs.readFileSync(bakeFile, 'utf8'));
setOutput(`bake-file-${outputName}`, bakeFile);
logger.endGroup(group);
}

// Bake file with tags and labels
Expand Down
13 changes: 7 additions & 6 deletions packages/container-metadata/src/lib/meta.spec.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { ContextProxyFactory, RepoMetadata, RepoProxyFactory, RunnerContext } from '@nx-tools/ci-context';
import { logger } from '@nx-tools/core';
import { workspaceRoot } from '@nx/devkit';
import * as dotenv from 'dotenv';
import * as fs from 'node:fs';
Expand Down Expand Up @@ -72,7 +73,7 @@ const tagsLabelsTest = async (
) => {
process.env = dotenv.parse(fs.readFileSync(path.join(__dirname, '..', '..', '__tests__', 'fixtures', envFile)));
const repo = await RepoProxyFactory.create(process.env.GITHUB_TOKEN || '');
const meta = new Meta({ ...getInputs({}), ...inputs }, await getContext(), repo);
const meta = new Meta({ ...getInputs({}), ...inputs }, await getContext(), repo, logger);

const version = meta.version;
expect(version).toEqual(exVersion);
Expand Down Expand Up @@ -2987,7 +2988,7 @@ describe('pr-head-sha', () => {
process.env.DOCKER_METADATA_PR_HEAD_SHA = 'true';

const repo = await RepoProxyFactory.create(process.env.GITHUB_TOKEN || '');
const meta = new Meta({...getInputs({}), ...inputs}, await getContext(), repo);
const meta = new Meta({...getInputs({}), ...inputs}, await getContext(), repo, logger);

const version = meta.version;
expect(version).toEqual(exVersion);
Expand Down Expand Up @@ -4019,7 +4020,7 @@ describe('json', () => {
process.env = dotenv.parse(fs.readFileSync(path.join(__dirname, '..', '..', '__tests__', 'fixtures', envFile)));

const repo = await RepoProxyFactory.create(process.env.GITHUB_TOKEN || '');
const meta = new Meta({...getInputs({}), ...inputs}, await getContext(), repo);
const meta = new Meta({...getInputs({}), ...inputs}, await getContext(), repo, logger);

const jsonOutput = meta.getJSON(['manifest']);
expect(jsonOutput).toEqual(exJSON);
Expand Down Expand Up @@ -4533,7 +4534,7 @@ describe('bakeFile', () => {
process.env = dotenv.parse(fs.readFileSync(path.join(__dirname, '..', '..', '__tests__', 'fixtures', envFile)));

const repo = await RepoProxyFactory.create(process.env.GITHUB_TOKEN || '');
const meta = new Meta({...getInputs({}), ...inputs}, await getContext(), repo);
const meta = new Meta({...getInputs({}), ...inputs}, await getContext(), repo, logger);

const bakeFileTags = meta.getBakeFile('tags');
expect(JSON.parse(fs.readFileSync(bakeFileTags, 'utf8'))).toEqual(exBakeTags);
Expand Down Expand Up @@ -4595,7 +4596,7 @@ describe('bakeFileTagsLabels', () => {
process.env = dotenv.parse(fs.readFileSync(path.join(__dirname, '..', '..', '__tests__', 'fixtures', envFile)));

const repo = await RepoProxyFactory.create(process.env.GITHUB_TOKEN || '');
const meta = new Meta({...getInputs({}), ...inputs}, await getContext(), repo);
const meta = new Meta({...getInputs({}), ...inputs}, await getContext(), repo, logger);

const bakeFile = meta.getBakeFileTagsLabels();
expect(JSON.parse(fs.readFileSync(bakeFile, 'utf8'))).toEqual(exBakeDefinition);
Expand Down Expand Up @@ -4640,7 +4641,7 @@ describe('sepTags', () => {
process.env = dotenv.parse(fs.readFileSync(path.join(__dirname, '..', '..', '__tests__', 'fixtures', envFile)));

const repo = await RepoProxyFactory.create(process.env.GITHUB_TOKEN || '');
const meta = new Meta({...getInputs({}), ...inputs}, await getContext(), repo);
const meta = new Meta({...getInputs({}), ...inputs}, await getContext(), repo, logger);

expect(meta.getTags().join(inputs["sep-tags"])).toEqual(expTags);
});
Expand Down
Loading

0 comments on commit 12acea1

Please sign in to comment.