UNPKG

2.55 kBJavaScriptView Raw
1"use strict";
2
3const path = require('path');
4
5const spawn = require('cross-spawn');
6
7const glob = require('glob');
8
9const [executor, ignoredBin, script, ...args] = process.argv;
10
11if (script) {
12 spawnScript();
13} else {
14 const scriptsPath = path.join(__dirname, 'scripts/');
15 const scriptsAvailable = glob.sync(path.join(__dirname, 'scripts', '*')); // `glob.sync` returns paths with unix style path separators even on Windows.
16 // So we normalize it before attempting to strip out the scripts path.
17
18 const scriptsAvailableMessage = scriptsAvailable.map(path.normalize).map(s => s.replace(scriptsPath, '').replace(/__tests__/, '').replace(/\.js$/, '')).filter(Boolean).join('\n ').trim();
19 const fullMessage = `
20Usage: ${ignoredBin} [script] [--flags]
21
22Available Scripts:
23 ${scriptsAvailableMessage}
24
25Options:
26 All options depend on the script. Docs will be improved eventually, but for most scripts you can assume that the args you pass will be forwarded to the respective tool that's being run under the hood.
27
28May the force be with you.
29 `.trim();
30 console.log(`\n${fullMessage}\n`);
31}
32
33function getEnv() {
34 // this is required to address an issue in cross-spawn
35 // https://github.com/kentcdodds/kcd-scripts/issues/4
36 return Object.keys(process.env).filter(key => process.env[key] !== undefined).reduce((envCopy, key) => {
37 envCopy[key] = process.env[key];
38 return envCopy;
39 }, {
40 [`SCRIPTS_${script.toUpperCase()}`]: true
41 });
42}
43
44function spawnScript() {
45 const relativeScriptPath = path.join(__dirname, './scripts', script);
46 const scriptPath = attemptResolve(relativeScriptPath);
47
48 if (!scriptPath) {
49 throw new Error(`Unknown script "${script}".`);
50 }
51
52 const result = spawn.sync(executor, [scriptPath, ...args], {
53 stdio: 'inherit',
54 env: getEnv()
55 });
56
57 if (result.signal) {
58 handleSignal(result);
59 } else {
60 process.exit(result.status);
61 }
62}
63
64function handleSignal(result) {
65 if (result.signal === 'SIGKILL') {
66 console.log(`The script "${script}" failed because the process exited too early. ` + 'This probably means the system ran out of memory or someone called ' + '`kill -9` on the process.');
67 } else if (result.signal === 'SIGTERM') {
68 console.log(`The script "${script}" failed because the process exited too early. ` + 'Someone might have called `kill` or `killall`, or the system could ' + 'be shutting down.');
69 }
70
71 process.exit(1);
72}
73
74function attemptResolve(...resolveArgs) {
75 try {
76 return require.resolve(...resolveArgs);
77 } catch (error) {
78 return null;
79 }
80}
\No newline at end of file