Debian Codegraph @

spawn-wrap/lib/mungers/sh.js

raw
1 'use strict';
2
3 const isWindows = require("is-windows")
4 const path = require("path")
5 const {debug} = require("../debug")
6 const {isNode} = require("../exe-type")
7 const whichOrUndefined = require("../which-or-undefined")
8
9 /**
10 * Intercepts Node and npm processes spawned through a Linux shell.
11 *
12 * @param workingDir {string} Absolute system-dependent path to the directory containing the shim files.
13 * @param options {import("../munge").InternalSpawnOptions} Original internal spawn options.
14 * @return {import("../munge").InternalSpawnOptions} Updated internal spawn options.
15 */
16 function mungeSh(workingDir, options) {
17 const cmdi = options.args.indexOf('-c')
18 if (cmdi === -1) {
19 return {...options} // no -c argument
20 }
21
22 let c = options.args[cmdi + 1]
23 const re = /^\s*((?:[^\= ]*\=[^\=\s]*)*[\s]*)([^\s]+|"[^"]+"|'[^']+')( .*)?$/
24 const match = c.match(re)
25 if (match === null) {
26 return {...options} // not a command invocation. weird but possible
27 }
28
29 let command = match[2]
30 // strip quotes off the command
31 const quote = command.charAt(0)
32 if ((quote === '"' || quote === '\'') && command.endsWith(quote)) {
33 command = command.slice(1, -1)
34 }
35 const exe = path.basename(command)
36
37 let newArgs = [...options.args];
38 // Remember the original Node command to use it in the shim
39 let originalNode;
40 const workingNode = path.join(workingDir, 'node')
41
42 if (isNode(exe)) {
43 originalNode = command
44 c = `${match[1]}${match[2]} "${workingNode}" ${match[3]}`
45 newArgs[cmdi + 1] = c
46 } else if (exe === 'npm' && !isWindows()) {
47 // XXX this will exhibit weird behavior when using /path/to/npm,
48 // if some other npm is first in the path.
49 const npmPath = whichOrUndefined('npm')
50
51 if (npmPath) {
52 c = c.replace(re, `$1 "${workingNode}" "${npmPath}" $3`)
53 newArgs[cmdi + 1] = c
54 debug('npm munge!', c)
55 }
56 }
57
58 return {...options, args: newArgs, originalNode};
59 }
60
61 module.exports = mungeSh