flow2schema/src/cli.js

68 lines
1.6 KiB
JavaScript
Raw Permalink Normal View History

2018-07-25 08:38:10 +03:00
// @flow
2017-11-30 14:27:05 +03:00
import * as yaml from 'yaml-js';
2017-12-17 13:13:27 +03:00
import yargs from 'yargs';
2017-12-16 17:03:22 +03:00
import stringifyJson from 'json-stringify-pretty-compact';
2017-11-16 15:17:15 +03:00
import collect from '.';
2017-12-17 13:13:27 +03:00
type Args = {
_: string[],
type: 'json-schema' | 'intermediate',
indent: number,
maxWidth: number,
};
2017-11-16 15:17:15 +03:00
2017-12-17 13:13:27 +03:00
function run(file: string, args: Args): string {
const {types, schema} = collect(file);
2017-11-16 15:17:15 +03:00
2017-12-17 13:13:27 +03:00
switch (args.type) {
case 'intermediate':
return yaml.dump(types, null, null, {
indent: args.indent,
width: args.maxWidth,
}).trimRight();
case 'json-schema':
default:
return stringifyJson(schema, {
indent: args.indent,
maxLength: args.maxWidth,
});
2017-11-16 15:17:15 +03:00
}
2017-12-17 13:13:27 +03:00
}
export default function (argv: string[]) {
const args: Args = yargs(argv)
.usage('flow2schema -t type [file]')
.option('type', {
alias: 't',
choices: ['json-schema', 'intermediate'],
demand: true,
})
.option('indent', {
type: 'number',
default: 4,
coerce: val => val >= 2 ? Math.floor(val) : 4,
})
.option('max-width', {
type: 'number',
default: 100,
coerce: val => val >= 20 ? Math.floor(val) : 100,
})
.argv;
// TODO: support Windows.
const file = args._.length === 0 ? '/dev/stdin' : args._[0];
2017-11-16 15:17:15 +03:00
try {
2017-12-17 13:13:27 +03:00
const output = run(file, args);
console.log(output);
2017-11-16 15:17:15 +03:00
} catch (ex) {
console.error(ex.message);
console.error(ex.stack);
2017-12-17 13:13:27 +03:00
process.exit(1);
2017-11-16 15:17:15 +03:00
}
}