1 | 'use strict'
|
2 |
|
3 | const parse = require('string-argv')
|
4 | const npmWhich = require('npm-which')(process.cwd())
|
5 | const checkPkgScripts = require('./checkPkgScripts')
|
6 |
|
7 | const debug = require('debug')('lint-staged:find-bin')
|
8 |
|
9 |
|
10 | let pkg
|
11 | try {
|
12 |
|
13 | pkg = require(`${process.cwd()}/package.json`)
|
14 | debug('Loaded package.json using `process.cwd()`')
|
15 | } catch (ignore) {
|
16 | debug('Could not load package.json using `process.cwd()`')
|
17 | pkg = {}
|
18 | }
|
19 |
|
20 | const cache = new Map()
|
21 |
|
22 | module.exports = function findBin(cmd) {
|
23 | debug('Resolving binary for command `%s`', cmd)
|
24 |
|
25 | |
26 |
|
27 |
|
28 |
|
29 |
|
30 |
|
31 |
|
32 |
|
33 |
|
34 |
|
35 | const [binName, ...args] = parse(cmd)
|
36 |
|
37 | if (cache.has(binName)) {
|
38 | debug('Resolving binary for `%s` from cache', binName)
|
39 | return { bin: cache.get(binName), args }
|
40 | }
|
41 |
|
42 | try {
|
43 |
|
44 |
|
45 | const bin = npmWhich.sync(binName)
|
46 | debug('Binary for `%s` resolved to `%s`', cmd, bin)
|
47 | cache.set(binName, bin)
|
48 | return { bin, args }
|
49 | } catch (err) {
|
50 |
|
51 | checkPkgScripts(pkg, cmd, binName, args)
|
52 | throw new Error(`${binName} could not be found. Try \`npm install ${binName}\`.`)
|
53 | }
|
54 | }
|