Skip to content

Commit

Permalink
refactor(cli): reject invalid persist.format option
Browse files Browse the repository at this point in the history
  • Loading branch information
Tlacenka committed Jan 15, 2024
1 parent 4897165 commit fb9f5cf
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 7 deletions.
7 changes: 1 addition & 6 deletions e2e/cli-e2e/tests/collect.e2e.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,12 +65,7 @@ describe('CLI collect', () => {
it('should print report summary to stdout', async () => {
const { code, stdout, stderr } = await executeProcess({
command: 'code-pushup',
args: [
'collect',
'--verbose',
'--persist.format=stdout',
'--no-progress',
],
args: ['collect', '--no-progress'],
cwd: 'examples/react-todos-app',
});

Expand Down
9 changes: 9 additions & 0 deletions packages/cli/src/lib/yargs-cli.integration.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,15 @@ describe('yargsCli', () => {
expect(parsedArgv.persist?.format).toEqual(['md', 'json']);
});

it('should throw for an invalid persist format', () => {
expect(() =>
yargsCli<CoreConfig>(['--persist.format=md', '--persist.format=stdout'], {
options,
noExitProcess: true,
}).parse(),
).toThrow('Invalid persist.format option');
});

it('should parse global options correctly', async () => {
const parsedArgv = await yargsCli<GeneralCliOptions>(
['--verbose', '--no-progress'],
Expand Down
21 changes: 20 additions & 1 deletion packages/cli/src/lib/yargs-cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import yargs, {
Options,
ParserConfigurationOptions,
} from 'yargs';
import { PersistConfig, formatSchema } from '@code-pushup/models';
import { logErrorBeforeThrow } from './implementation/utils';

/**
Expand Down Expand Up @@ -42,10 +43,13 @@ export function yargsCli<T = unknown>(
.help()
.version(false)
.alias('h', 'help')
.check(args => {
const persist = args['persist'] as PersistConfig | undefined;
return persist == null || validatePersistFormat(persist);
})
.parserConfiguration({
'strip-dashed': true,
} satisfies Partial<ParserConfigurationOptions>)
.array('persist.format')
.coerce('config', (config: string | string[]) =>
Array.isArray(config) ? config.at(-1) : config,
)
Expand Down Expand Up @@ -90,3 +94,18 @@ export function yargsCli<T = unknown>(
// return CLI object
return cli as unknown as Argv<T>;
}

function validatePersistFormat(persist: PersistConfig) {
try {
if (persist?.format != null) {
persist.format.forEach(format => formatSchema.parse(format));
}
return true;
} catch {
throw new Error(
`Invalid persist.format option. Valid options are: ${Object.values(
formatSchema.Values,
).join(', ')}`,
);
}
}

0 comments on commit fb9f5cf

Please sign in to comment.