-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcli.js
executable file
·125 lines (110 loc) · 2.76 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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
#!/usr/bin/env node
import jsonfile from 'jsonfile';
import inquirer from 'inquirer';
import { pkgUp as findPkg } from 'pkg-up';
// help message:
if (process.argv[2] === '--help') {
console.log(
`Edit npm scripts from the command line without worrying about json escaping.
edit-script
edit-script <script>`,
);
process.exit();
}
const NEW_SCRIPT_SYMBOL = Symbol('Create new script');
const EXIT_SYMBOL = Symbol('Exit');
async function main() {
const pkgPath = await findPkg();
if (!pkgPath) throw new Error('No package.json file found!');
const pkg = await jsonfile.readFile(pkgPath);
if (!pkg.scripts) pkg.scripts = {};
const script = await getScriptName(pkg.scripts);
const answers = await inquirer.prompt([
{
type: 'editor',
name: 'script',
message: 'Edit your script; an empty script deletes the script',
default: pkg.scripts[script],
},
]);
const val = answers.script.trim();
if (!val) {
console.log('Deleting script.');
delete pkg.scripts[script];
} else pkg.scripts[script] = val;
await jsonfile.writeFile(pkgPath, pkg, { spaces: 2 });
}
main().catch((err) => {
console.error(err);
process.exit(1);
});
async function getScriptName(scripts) {
const cliScript = process.argv[2];
if (cliScript) {
if (!scripts[cliScript]) await confirmCreation(cliScript);
return cliScript;
}
const choices = Object.entries(scripts)
.map(([key, value]) => {
return {
name: pad(key, value),
value: key,
short: key,
};
})
.concat([
new inquirer.Separator(),
{
name: 'Create a new script',
value: NEW_SCRIPT_SYMBOL,
},
{
name: 'Exit edit-script',
value: EXIT_SYMBOL,
},
]);
// Prompt for script name:
const { script } = await inquirer.prompt([
{
type: 'list',
name: 'script',
message: 'Select a script to edit:',
choices,
},
]);
switch (script) {
case NEW_SCRIPT_SYMBOL:
// Get script name:
return (
await inquirer.prompt([
{
type: 'input',
name: 'name',
message: 'Enter the script name:',
validate: (val) => !!val || 'Script name must not be empty',
},
])
).name;
case EXIT_SYMBOL:
return process.exit();
default:
return script;
}
}
async function confirmCreation(script) {
const { create } = await inquirer.prompt([
{
type: 'confirm',
name: 'create',
message: `The script "${script}" does not exist. Create it?`,
},
]);
if (!create) {
console.log('Aborting');
process.exit();
}
}
function pad(str1, str2) {
const desiredWidth = 80;
return `${str1.padEnd(desiredWidth - str2.length - 1)} ${str2}`;
}