-
Notifications
You must be signed in to change notification settings - Fork 7
/
index.js
148 lines (122 loc) · 3.84 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
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
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
'use strict'
let path = require('path')
let meow = require('meow')
let { promisify } = require('util')
let executable = require('executable')
let crossSpawn = require('cross-spawn')
let readPkgUp = require('read-pkg-up')
let stripIndent = require('strip-indent')
let withFileTypes = require('readdir-withfiletypes')
let stripAnsiStream = require('strip-ansi-stream')
let supportsColor = require('supports-color')
let readdir = promisify(withFileTypes.readdir)
function isPlainObject(val) {
return typeof val === 'object' && val !== null && !Array.isArray(val)
}
// Prevent caching of this module so module.parent is always accurate
delete require.cache[__filename];
let parentDir = path.dirname(module.parent.filename)
async function scritch(dir, opts = {}) {
let scriptsPath = opts.scriptsPath || 'scripts'
let env = opts.env || {}
let helpContent = opts.help
let scriptsDir = path.resolve(dir, scriptsPath)
// Lookup scripts
let dirents = await readdir(scriptsDir, { withFileTypes: true })
let scripts = []
for (let dirent of dirents) {
// Ignore directories
if (dirent.isDirectory()) {
continue
}
// Ignore scripts that start with `_` (treated like helpers)
if (dirent.name.startsWith('_')) {
continue
}
// Get base name (without extension) and path of file
let name = path.basename(dirent.name, path.extname(dirent.name))
let filePath = path.join(scriptsDir, dirent.name)
// Ensure file is executable
if (!await executable(filePath)) {
throw new Error(`Expected path to be executable: "${filePath}"`)
}
scripts.push({ name, filePath })
}
// Store raw argv
let argv = process.argv.slice(2)
// Store args to pass to script
let args = argv.slice(1)
// Lookup package for CLI
let foundPkg = readPkgUp.sync({
cwd: parentDir,
normalize: false,
})
let pkg = foundPkg.pkg || {}
let pkgPath = foundPkg.path
let pkgRootPath = path.dirname(pkgPath)
let pkgNodeModulesBinPath = path.join(pkgRootPath, 'node_modules', '.bin')
// Extract bin name
let binName;
if (isPlainObject(pkg.bin)) {
binName = Object.keys(pkg.bin)[0]
} else if (pkg.name) {
binName = pkg.name
}
if (!binName) binName = 'cli'
// Create help content
let help = ''
help += `Usage\n`
help += ` $ ${binName} <script> [...args]\n`
help += '\n'
help += `Scripts\n`
help += scripts.map(script => ` - ${script.name}`).join('\n') + '\n'
if (helpContent) {
help += stripIndent(helpContent).trimRight()
}
let cli = meow({ argv, pkg, help })
// Match script being run
let scriptName = cli.input[0]
let script = scripts.find(script => {
return script.name === scriptName
})
// Show help if no script passed
if (!script) {
cli.showHelp()
return
}
return new Promise(async (resolve, reject) => {
let stdoutSupportsColor = supportsColor.stdout;
// Spawn matching script
let proc = crossSpawn(script.filePath, args, {
cwd: process.cwd(),
shell: true,
// only pipe if it does not support color as we lose ability to retain color otherwise
stdio: !stdoutSupportsColor ? 'pipe' : 'inherit',
env: Object.assign({}, process.env, {
PATH: `${pkgNodeModulesBinPath}:${scriptsDir}:${process.env.PATH}`,
SCRITCH_SCRIPT_NAME: script.name,
SCRITCH_SCRIPT_PATH: script.filePath,
SCRITCH_SCRIPTS_DIR: scriptsDir,
}, env),
})
if (!stdoutSupportsColor) {
proc.stdout.pipe(stripAnsiStream()).pipe(process.stdout)
proc.stderr.pipe(stripAnsiStream()).pipe(process.stderr)
}
proc.on('error', err => {
reject(err);
});
proc.on('close', code => {
if (code !== 0) {
process.exitCode = code;
}
resolve();
});
});
}
module.exports = (...args) => {
return scritch(...args).catch(err => {
console.error(err);
process.exit(1);
});
}