Skip to content
This repository has been archived by the owner on Jun 5, 2023. It is now read-only.

Commit

Permalink
fix(collect): better cli default arg message & correct default cli tr…
Browse files Browse the repository at this point in the history
…ansformer order
  • Loading branch information
vnphanquang committed Mar 11, 2022
1 parent 82a58ee commit 185dbdf
Show file tree
Hide file tree
Showing 10 changed files with 168 additions and 125 deletions.
111 changes: 0 additions & 111 deletions src/commands/collect/collect.cli.ts

This file was deleted.

@@ -1,6 +1,6 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP

exports[`cli collect: default --no-output: cli collect: default 1`] = `
exports[`cli collect: default --no-output no-arg: cli collect: default 1`] = `
Object {
"json": "{
\\"admin\\": {
Expand Down
Expand Up @@ -6,38 +6,55 @@ import {
} from 'memfs';

import { collectCli } from '$commands/collect/collect.cli';
import { defaultCollectOptions } from '$commands/collect/collect.constants';
import { FILES } from '$tests/fixtures/memfs';

import { defaultCollectOptions } from './collect.constants';

jest.mock('fs', () => {
const fs = jest.requireActual('fs');
const sourcePath = './generators/route/route.source.ts';
const sourcePath = '../generators/route/route.source.ts';
const sourceOfRouteUtil = fs.readFileSync(resolve(__dirname, sourcePath), 'utf-8');
vol.fromJSON({
['./generators/route.source.ts']: sourceOfRouteUtil,
}, __dirname);
}, resolve(__dirname, '..'));

return memfs;
});

const savedJSON = vol.toJSON();
beforeEach(() => {
vol.fromNestedJSON(FILES, defaultCollectOptions.inDir);
vol.fromJSON(savedJSON, __dirname);
vol.fromJSON(savedJSON, resolve(__dirname, '..'));
});
afterEach(() => {
vol.reset();
});

test('cli collect: default --no-output', () => {
test('cli collect: default --no-output no-arg', () => {
const writeSpy = jest.spyOn(console, 'log').mockImplementation();
const program = collectCli().exitOverride();
program.parse(['node', 'collect', '--no-output']);
expect(writeSpy).toHaveBeenCalledTimes(1);
expect(writeSpy.mock.calls[writeSpy.mock.calls.length - 1][0]).toMatchSnapshot('cli collect: default');
});

test('cli collect: default --no-output with all default args', () => {
const writeSpy = jest.spyOn(console, 'log').mockImplementation();
const program = collectCli().exitOverride();
program.parse([
'node',
'collect',
'--no-output',
'--inDir=src/routes',
'--extensions=.svelte',
'--ignorePatterns=/^_/',
'--outDir=src/generated/routing',
'--depth=Infinity',
'--keyTransform=dollarArg',
'--keyTransform=camelCase',
]);
expect(writeSpy).toHaveBeenCalledTimes(1);
});

test('cli collect: verbose', () => {
const logInfo = jest.spyOn(console, 'info').mockImplementation();
const tableSpy = jest.spyOn(console, 'table').mockImplementation();
Expand All @@ -46,3 +63,10 @@ test('cli collect: verbose', () => {
expect(logInfo).toHaveBeenCalled();
expect(tableSpy).toHaveBeenCalled();
});

test('cli collect: invalid keyTransform choice', () => {
const program = collectCli().exitOverride();
expect(() => {
program.parse(['node', 'collect', '--no-output', '--keyTransform=invalid']);
}).toThrow();
});
125 changes: 125 additions & 0 deletions src/commands/collect/collect.cli/collect.cli.ts
@@ -0,0 +1,125 @@
import {
Command,
InvalidArgumentError,
Option,
} from 'commander';

import { collect } from '$commands/collect/collect';
import {
keyTransformCliToFunc,
defaultCollectOptions,
defaultKeyTransformCli,
} from '$commands/collect/collect.constants';
import type {
CollectOptions,
KeyTransformFn,
} from '$commands/collect/collect.types';
import { KeyTransformCli } from '$commands/collect/collect.types';
import {
commaSeparatedList,
number,
} from '$utils/parser';

export function collectCli() {
return new Command('collect')
.description('collect route data')
.option(
'-i, --inDir <path>',
'directory path to collect',
defaultCollectOptions.inDir
)
.addOption(
new Option(
'-e, --extensions <list>',
'comma-separated list of file extensions to collect'
)
.argParser(commaSeparatedList)
.default(
defaultCollectOptions.extensions,
defaultCollectOptions.extensions.join(',')
)
)
.addOption(
new Option(
'-x, --ignorePatterns <list>',
'comma-separated list of filename patterns (string literal or regex) to ignore'
)
.argParser(commaSeparatedList)
.default(
defaultCollectOptions.ignorePatterns,
defaultCollectOptions.ignorePatterns.join(',')
)
)
.option(
'-o, --outDir <path>',
'outputs generated files to this folder',
defaultCollectOptions.outDir
)
.addOption(
new Option('-d, --depth <number>', 'depth of inDir to collect')
.argParser(number)
.default(
defaultCollectOptions.depth,
defaultCollectOptions.depth.toString()
)
)
.addOption(
new Option('-t, --keyTransform <variant>', 'how to transform route key')
.default([], `--keyTransform=dollarArg --keyTransform=camelCase`)
.argParser<KeyTransformFn[]>((value, previous) => {
if (!(value in KeyTransformCli)) {
throw new InvalidArgumentError(
`Must be one of: ${Object.keys(KeyTransformCli).join(', ')}`
);
}
const valued =
keyTransformCliToFunc[KeyTransformCli[value] as KeyTransformCli];
return [...previous, valued];
})
)
.option(
'-k, --dirkey <name>',
'how to transform route key',
defaultCollectOptions.dirkey
)
.option(
'--no-output',
"don't write to disk but print to console instead",
defaultCollectOptions.output
)
.option(
'--no-utils',
"don't generate utils for building path with arguments",
defaultCollectOptions.utils
)
.option(
'--no-typescript',
'outputs files in javascript instead of typescript',
defaultCollectOptions.typescript
)
.option(
'--verbose',
'prints more info during operation',
defaultCollectOptions.verbose
)
.action((options: CollectOptions) => {
if (options.keyTransform.length === 0) {
options.keyTransform = defaultKeyTransformCli.map(
(k) => keyTransformCliToFunc[k]
);
}
if (options.verbose) {
console.info('Running "collect" with options:');
console.table(
Object.fromEntries(
Object.entries(options).map(([key, value]) => [key, { value }])
)
);
}

const output = collect(options);
if (!options.output) {
console.log(output);
}
});
}
1 change: 1 addition & 0 deletions src/commands/collect/collect.cli/index.ts
@@ -0,0 +1 @@
export * from './collect.cli';
4 changes: 2 additions & 2 deletions src/commands/collect/collect.constants.ts
Expand Up @@ -2,7 +2,7 @@ import type {
CollectOptions,
KeyTransformFn
} from '$commands/collect/collect.types';
import {KeyTransformCli} from '$commands/collect/collect.types';
import { KeyTransformCli } from '$commands/collect/collect.types';
import {
camelCasify,
dollarArgify,
Expand All @@ -26,8 +26,8 @@ export const defaultCollectOptions: CollectOptions = {
};

export const defaultKeyTransformCli: KeyTransformCli[] = [
KeyTransformCli.camelCase,
KeyTransformCli.dollarArg,
KeyTransformCli.camelCase,
];

export const keyTransformCliToFunc: Record<KeyTransformCli, KeyTransformFn> = {
Expand Down
2 changes: 2 additions & 0 deletions src/commands/collect/collect.test.ts
Expand Up @@ -68,3 +68,5 @@ test('collect: failure in generateRouteUtil', () => {
expect(spyGenerateJSON).toHaveBeenCalled();
expect(spyError).toHaveBeenCalled();
});

// TODO: check other custom options
5 changes: 3 additions & 2 deletions src/commands/collect/generators/json/json.ts
Expand Up @@ -13,6 +13,7 @@ import {

import { MAPPING_FILENAME } from '$commands/collect/collect.constants';
import type { CollectOptions } from '$commands/collect/collect.types';
import { compose } from '$utils/transformer';

export type DeepObject<T> = {
[key: string]: T | DeepObject<T>;
Expand All @@ -39,7 +40,7 @@ export function extractRouteMapping(options: CollectOptions, inputDir: string =
if (!childMap['index']) {
childMap[options.dirkey] = nextPath;
}
const transformed = options.keyTransform.reduce((acc, transform) => transform(acc, child), child);
const transformed = compose(child, ...options.keyTransform);
map[transformed] = childMap;
}
} else {
Expand All @@ -48,7 +49,7 @@ export function extractRouteMapping(options: CollectOptions, inputDir: string =

// transform filename to route key
const routeKey = filename.replace(/\.[^/.]+$/, ''); // trim extension
const transformed = options.keyTransform.reduce((acc, transform) => transform(acc, child), routeKey);
const transformed = compose(routeKey, ...options.keyTransform);

let routeName = routeKey;
if (routeKey === 'index') {
Expand Down
3 changes: 3 additions & 0 deletions src/commands/collect/index.ts
@@ -0,0 +1,3 @@
export * from './collect';
export * from './collect.types';
export { defaultCollectOptions } from '$commands/collect/collect.constants';
4 changes: 1 addition & 3 deletions src/lib.ts
@@ -1,4 +1,2 @@
export * from '$commands/collect/collect.types';
export { collect } from '$commands/collect/collect';
export { defaultCollectOptions } from '$commands/collect/collect.constants';
export * from '$commands/collect';
export * from '$utils/transformer';

0 comments on commit 185dbdf

Please sign in to comment.