-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
executable file
·86 lines (70 loc) · 2.68 KB
/
index.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
#!/usr/bin/env node
// @flow
const HARD_CODED = {
s: 'start',
t: 'test'
};
const chalk = require('chalk');
const readline = require('readline');
const run = require('./run');
const { join } = require('path');
const Fuse = require('fuse.js');
const [term, ...args] = process.argv.slice(2);
// $FlowFixMe: surpress require not accepting a variable
const getScripts = dir => require(join(dir, 'package.json')).scripts;
const removeEnvVars = bit => bit.includes('=') && !bit.match(/[a-z]/g)
const scripts = getScripts(process.cwd());
const showErrorScript = (msg = 'Something went wrong') => {
console.log(chalk.bold.red(msg));
console.log();
console.log(chalk.dim('Possible scripts are: '));
keys.forEach(({ key }) => console.log(`${chalk.bold.white(key)}\n ${chalk.dim(scripts[key])}`));
process.exit(1);
}
const keys = Object.keys(scripts)
.reduce((arr, key) => [...arr, {
key,
}], []);
if (!term || (term === '')) {
showErrorScript('No serch term provided');
process.exit(1);
}
if (HARD_CODED[term] && scripts[HARD_CODED[term]]) {
const script = scripts[HARD_CODED[term]];
return run(script).catch(e => showErrorScript(e.message));
}
const list = new Fuse(keys, { tokenize: true, shouldSort: true, keys: ['key'] });
const matches = list.search(term);
if (matches.length === 0) {
showErrorScript(`No matching script found for: ${term}`);
}
if (matches.length === 1) {
console.log(chalk.green(`Found cmd:`), chalk.green.bold(matches[0].key));
return run(scripts[matches[0].key])
.then(() => console.log(chalk.green.bold('Finished')))
.catch(err => showErrorScript(err.message));
}
if (matches.length > 1) {
console.log(chalk.blue.bold('Found multiple commands:'));
const opts = matches.map(({ key }, i) => `${i + 1}) ${chalk.blue(key)}`).concat(`${matches.length + 1}) all`).join('\n');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
rl.question(`Which command do you want to run?\n${opts}\n`, answer => {
rl.close();
if (Number(answer) === matches.length + 1) {
Promise.all(matches.map(match =>
run(match.cmd)
)).then(() => console.log(chalk.green.bold('Finished')))
.catch(err => showErrorScript(err.message));
return;
}
if (isNaN(Number(answer)) || Number(answer) > matches.length) {
return showErrorScript('Not a valid option');
}
return run(matches[Number(answer) - 1].cmd)
.then(() => console.log(chalk.green.bold('Finished')))
.catch(err => showErrorScript(err.message));
});
}