UNPKG

1.99 kBJavaScriptView Raw
1const findScripts = require('./find-scripts')
2const runNpmCommand = require('npm-utils').test
3const join = require('path').join
4const findup = require('findup')
5const printNames = require('./print-names')
6
7function printAllScripts (pkg) {
8 printNames('Available scripts are',
9 Object.keys(pkg.scripts))
10}
11
12const npmErrorLoggers = {
13 errorOutput: '',
14 npmErrorStarted: false,
15 stdout: function (str) {
16 process.stdout.write(str)
17 },
18 stderr: function (str) {
19 if (npmErrorLoggers.npmErrorStarted) {
20 return
21 }
22 npmErrorLoggers.errorOutput += str
23 if (/npm ERR/.test(npmErrorLoggers.errorOutput)) {
24 npmErrorLoggers.npmErrorStarted = true
25 process.stderr.write('\n')
26 return
27 }
28 // TODO buffer by line
29 process.stderr.write(str)
30 }
31}
32
33function runPrefix (prefix) {
34 try {
35 var fullPath = findup.sync(process.cwd(), 'package.json')
36 } catch (e) {
37 console.error('Cannot find package.json in the current folder and its ancestors')
38 process.exit(-1)
39 }
40 const pkg = require(join(fullPath, 'package.json'))
41 if (!pkg.scripts) {
42 console.error('Cannot find any scripts in the current package')
43 process.exit(-1)
44 }
45
46 if (!prefix) {
47 printAllScripts(pkg)
48 return
49 }
50 console.log('running command with prefix "' + prefix + '"')
51
52 const candidates = findScripts(prefix, pkg.scripts)
53 if (!candidates.length) {
54 console.error('Cannot find any scripts starting with "%s"', prefix)
55 printAllScripts(pkg)
56 process.exit(-1)
57 }
58 if (candidates.length > 1) {
59 printNames('Several scripts start with ' + '"' + prefix + '"',
60 candidates)
61 console.error('Be more specific')
62 process.exit(-1)
63 }
64
65 var cmd = 'npm run ' + candidates[0]
66 var extraArguments = process.argv.slice(3)
67 if (extraArguments.length) {
68 cmd += ' -- ' + extraArguments.join(' ')
69 }
70
71 runNpmCommand(cmd, npmErrorLoggers)
72 .catch(function (result) {
73 process.exit(result.code)
74 })
75}
76
77module.exports = runPrefix