Debian Codegraph @

spawn-wrap/lib/mungers/shebang.js

raw
1 'use strict';
2
3 const fs = require("fs")
4 const path = require("path")
5 const {isNode} = require("../exe-type")
6 const whichOrUndefined = require("../which-or-undefined")
7
8 /**
9 * Intercepts processes spawned through a script with a shebang line.
10 *
11 * @param workingDir {string} Absolute system-dependent path to the directory containing the shim files.
12 * @param options {import("../munge").InternalSpawnOptions} Original internal spawn options.
13 * @return {import("../munge").InternalSpawnOptions} Updated internal spawn options.
14 */
15 function mungeShebang(workingDir, options) {
16 const resolved = whichOrUndefined(options.file)
17 if (resolved === undefined) {
18 return {...options}
19 }
20
21 const shebang = fs.readFileSync(resolved, 'utf8')
22 const match = shebang.match(/^#!([^\r\n]+)/)
23 if (!match) {
24 return {...options} // not a shebang script, probably a binary
25 }
26
27 const shebangbin = match[1].split(' ')[0]
28 const maybeNode = path.basename(shebangbin)
29 if (!isNode(maybeNode)) {
30 return {...options} // not a node shebang, leave untouched
31 }
32
33 const originalNode = shebangbin
34 const file = shebangbin
35 const args = [shebangbin, path.join(workingDir, maybeNode)]
36 .concat(resolved)
37 .concat(match[1].split(' ').slice(1))
38 .concat(options.args.slice(1))
39
40 return {...options, file, args, originalNode};
41 }
42
43 module.exports = mungeShebang