forked from flow-typed/flow-typed
/
cli.js
executable file
·106 lines (99 loc) · 2.67 KB
/
cli.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
#!/usr/bin/env node
// @flow
import yargs from 'yargs';
import {fs, path} from './lib/node';
import * as Install from './commands/install';
import * as CreateDef from './commands/create-def';
import * as CreateStub from './commands/create-stub';
import * as Outdated from './commands/outdated';
import * as RunTests from './commands/runTests';
import * as Search from './commands/search';
import * as Update from './commands/update';
import * as UpdateCache from './commands/update-cache';
import * as ValidateDefs from './commands/validateDefs';
import type {Argv} from 'yargs';
import typeof Yargs from 'yargs';
const identity = <T>(x: T): T => x;
export function runCLI() {
type CommandModule = {
name: string,
description: string,
setup?: (yargs: Yargs) => Yargs,
run: (argv: Argv) => Promise<number>,
...
};
const commands: Array<CommandModule> = [
CreateDef,
CreateStub,
Install,
Outdated,
RunTests,
Search,
Update,
UpdateCache,
ValidateDefs,
];
commands
.reduce(
(cmdYargs, cmd) =>
cmdYargs.command(
cmd.name,
cmd.description,
cmd.setup || identity,
args =>
cmd
// $FlowExpectedError[extra-arg] cmd.run expects only one arg
.run(args, yargs)
.catch(err => {
if (err.stack) {
console.log('UNCAUGHT ERROR: %s', err.stack);
} else if (typeof err === 'object' && err !== null) {
console.log(
'UNCAUGHT ERROR: %s',
JSON.stringify(err, null, 2),
);
} else {
console.log('UNCAUGHT ERROR:', err);
}
process.exit(1);
})
.then(code => process.exit(code)),
),
yargs,
)
.demand(1)
.strict()
.recommendCommands()
.help('h')
.alias('h', 'help').argv;
}
/**
* Look to see if the CWD is within an npm project. If it is, and that project
* has a flow-typed CLI `npm install`ed, use that version instead of the global
* version of the CLI.
*/
if (require.main === module) {
const CWD = process.cwd();
let currDir = CWD;
let lastDir = null;
let run = runCLI;
while (currDir !== lastDir) {
const localCLIPath = path.join(
currDir,
'node_modules',
'.bin',
'flow-typed',
);
try {
if (fs.statSync(localCLIPath).isFile()) {
run = require.call(null, localCLIPath).runCLI;
break;
}
} catch (e) {
/* File doesn't exist, move up a dir... */
}
lastDir = currDir;
currDir = path.resolve(currDir, '..');
}
run();
}