1 exports = module.exports = lifecycle
3 exports.makeEnv = makeEnv
5 var log = require("npmlog")
6 , spawn = require("child_process").spawn
7 , npm = require("../npm.js")
8 , path = require("path")
9 , fs = require("graceful-fs")
10 , chain = require("slide").chain
11 , Stream = require("stream").Stream
13 , uidNumber = require("uid-number")
15 // windows calls it's path "Path" usually, but this is not guaranteed.
16 if (process.platform === "win32") {
18 Object.keys(process.env).forEach(function (e) {
19 if (e.match(/^PATH$/i)) {
25 function lifecycle (pkg, stage, wd, unsafe, failOk, cb) {
26 if (typeof cb !== "function") cb = failOk, failOk = false
27 if (typeof cb !== "function") cb = unsafe, unsafe = false
28 if (typeof cb !== "function") cb = wd, wd = null
30 while (pkg && pkg._data) pkg = pkg._data
31 if (!pkg) return cb(new Error("Invalid package data"))
33 log.info(stage, pkg._id)
34 if (!pkg.scripts || npm.config.get('ignore-scripts')) pkg.scripts = {}
36 validWd(wd || path.resolve(npm.dir, pkg.name), function (er, wd) {
39 unsafe = unsafe || npm.config.get("unsafe-perm")
41 if ((wd.indexOf(npm.dir) !== 0 || path.basename(wd) !== pkg.name)
42 && !unsafe && pkg.scripts[stage]) {
43 log.warn( "cannot run in wd", "%s %s (wd=%s)"
44 , pkg._id, pkg.scripts[stage], wd)
48 // set the env variables, then run scripts as a child process.
49 var env = makeEnv(pkg)
50 env.npm_lifecycle_event = stage
51 env.npm_node_execpath = env.NODE = env.NODE || process.execPath
52 env.npm_execpath = require.main.filename
54 // "nobody" typically doesn't have permission to write to /tmp
55 // even if it's never used, sh freaks out.
56 if (!npm.config.get("unsafe-perm")) env.TMPDIR = wd
58 lifecycle_(pkg, stage, wd, env, unsafe, failOk, cb)
62 function checkForLink (pkg, cb) {
63 var f = path.join(npm.dir, pkg.name)
64 fs.lstat(f, function (er, s) {
65 cb(null, !(er || !s.isSymbolicLink()))
69 function lifecycle_ (pkg, stage, wd, env, unsafe, failOk, cb) {
71 , p = wd.split("node_modules")
72 , acc = path.resolve(p.shift())
74 // first add the directory containing the `node` executable currently
75 // running, so that any lifecycle script that invoke "node" will execute
77 pathArr.unshift(path.dirname(process.execPath))
79 p.forEach(function (pp) {
80 pathArr.unshift(path.join(acc, "node_modules", ".bin"))
81 acc = path.join(acc, "node_modules", pp)
83 pathArr.unshift(path.join(acc, "node_modules", ".bin"))
85 // we also unshift the bundled node-gyp-bin folder so that
86 // the bundled one will be used for installing things.
87 pathArr.unshift(path.join(__dirname, "..", "..", "bin", "node-gyp-bin"))
89 if (env[PATH]) pathArr.push(env[PATH])
90 env[PATH] = pathArr.join(process.platform === "win32" ? ";" : ":")
92 var packageLifecycle = pkg.scripts && pkg.scripts.hasOwnProperty(stage)
94 if (packageLifecycle) {
95 // define this here so it's available to all scripts.
96 env.npm_lifecycle_script = pkg.scripts[stage]
100 cb = (function (cb_) { return function (er) {
101 if (er) log.warn("continuing anyway", er.message)
106 if (npm.config.get("force")) {
107 cb = (function (cb_) { return function (er) {
108 if (er) log.info("forced, continuing", er)
114 ( [ packageLifecycle && [runPackageLifecycle, pkg, env, wd, unsafe]
115 , [runHookLifecycle, pkg, env, wd, unsafe] ]
119 function validWd (d, cb) {
120 fs.stat(d, function (er, st) {
121 if (er || !st.isDirectory()) {
122 var p = path.dirname(d)
124 return cb(new Error("Could not find suitable wd"))
126 return validWd(p, cb)
132 function runPackageLifecycle (pkg, env, wd, unsafe, cb) {
133 // run package lifecycle scripts in the package root, or the nearest parent.
134 var stage = env.npm_lifecycle_event
135 , cmd = env.npm_lifecycle_script
137 var note = "\n> " + pkg._id + " " + stage + " " + wd
138 + "\n> " + cmd + "\n"
139 runCmd(note, cmd, pkg, env, stage, wd, unsafe, cb)
148 var r = queue.shift()
149 runCmd.apply(null, r)
153 function runCmd (note, cmd, pkg, env, stage, wd, unsafe, cb) {
155 queue.push([note, cmd, pkg, env, stage, wd, unsafe, cb])
161 var user = unsafe ? null : npm.config.get("user")
162 , group = unsafe ? null : npm.config.get("group")
164 if (log.level !== 'silent') {
165 if (npm.spinner.int) {
166 npm.config.get("logstream").write("\r \r")
170 log.verbose("unsafe-perm in lifecycle", unsafe)
172 if (process.platform === "win32") {
177 runCmd_(cmd, pkg, env, wd, stage, unsafe, 0, 0, cb)
179 uidNumber(user, group, function (er, uid, gid) {
180 runCmd_(cmd, pkg, env, wd, stage, unsafe, uid, gid, cb)
185 function runCmd_ (cmd, pkg, env, wd, stage, unsafe, uid, gid, cb_) {
188 cb_.apply(null, arguments)
190 process.nextTick(dequeue)
206 if (process.platform === "win32") {
209 conf.windowsVerbatimArguments = true
212 var proc = spawn(sh, [shFlag, cmd], conf)
213 proc.on("close", function (code, signal) {
215 process.kill(process.pid, signal);
217 var er = new Error("Exit status " + code)
219 if (er && !npm.ROLLBACK) {
220 log.info(pkg._id, "Failed to exec "+stage+" script")
221 er.message = pkg._id + " "
222 + stage + ": `" + cmd +"`\n"
224 if (er.code !== "EPERM") {
225 er.code = "ELIFECYCLE"
230 er.pkgname = pkg.name
233 log.error(pkg._id+"."+stage, er)
234 log.error(pkg._id+"."+stage, "continuing anyway")
242 function runHookLifecycle (pkg, env, wd, unsafe, cb) {
243 // check for a hook script, run if present.
244 var stage = env.npm_lifecycle_event
245 , hook = path.join(npm.dir, ".hooks", stage)
246 , user = unsafe ? null : npm.config.get("user")
247 , group = unsafe ? null : npm.config.get("group")
250 fs.stat(hook, function (er) {
252 var note = "\n> " + pkg._id + " " + stage + " " + wd
254 runCmd(note, hook, pkg, env, stage, wd, unsafe, cb)
258 function makeEnv (data, prefix, env) {
259 prefix = prefix || "npm_package_"
262 for (var i in process.env) if (!i.match(/^npm_/)) {
263 env[i] = process.env[i]
266 // npat asks for tap output
267 if (npm.config.get("npat")) env.TAP = 1
269 // express and others respect the NODE_ENV value.
270 if (npm.config.get("production")) env.NODE_ENV = "production"
272 } else if (!data.hasOwnProperty("_lifecycleEnv")) {
273 Object.defineProperty(data, "_lifecycleEnv",
279 for (var i in data) if (i.charAt(0) !== "_") {
280 var envKey = (prefix+i).replace(/[^a-zA-Z0-9_]/g, '_')
281 if (i === "readme") {
284 if (data[i] && typeof(data[i]) === "object") {
286 // quick and dirty detection for cyclical structures
287 JSON.stringify(data[i])
288 makeEnv(data[i], envKey+"_", env)
290 // usually these are package objects.
291 // just get the path and basic details.
293 makeEnv( { name: d.name, version: d.version, path:d.path }
297 env[envKey] = String(data[i])
298 env[envKey] = -1 !== env[envKey].indexOf("\n")
299 ? JSON.stringify(env[envKey])
305 if (prefix !== "npm_package_") return env
307 prefix = "npm_config_"
309 , keys = npm.config.keys
311 , namePref = data.name + ":"
312 , verPref = data.name + "@" + data.version + ":"
314 keys.forEach(function (i) {
315 if (i.charAt(0) === "_" && i.indexOf("_"+namePref) !== 0) {
318 var value = npm.config.get(i)
319 if (value instanceof Stream || Array.isArray(value)) return
320 if (!value) value = ""
321 else if (typeof value === "number") value = "" + value
322 else if (typeof value !== "string") value = JSON.stringify(value)
324 value = -1 !== value.indexOf("\n")
325 ? JSON.stringify(value)
327 i = i.replace(/^_+/, "")
328 if (i.indexOf(namePref) === 0) {
329 var k = i.substr(namePref.length).replace(/[^a-zA-Z0-9_]/g, "_")
330 pkgConfig[ k ] = value
331 } else if (i.indexOf(verPref) === 0) {
332 var k = i.substr(verPref.length).replace(/[^a-zA-Z0-9_]/g, "_")
333 pkgVerConfig[ k ] = value
335 var envKey = (prefix+i).replace(/[^a-zA-Z0-9_]/g, "_")
339 prefix = "npm_package_config_"
340 ;[pkgConfig, pkgVerConfig].forEach(function (conf) {
341 for (var i in conf) {
342 var envKey = (prefix+i)
343 env[envKey] = conf[i]
350 function cmd (stage) {
351 function CMD (args, cb) {
353 chain(args.map(function (p) {
354 return [npm.commands, "run-script", [p, stage]]
356 } else npm.commands["run-script"]([stage], cb)
358 CMD.usage = "npm "+stage+" <name>"
359 var installedShallow = require("./completion/installed-shallow.js")
360 CMD.completion = function (opts, cb) {
361 installedShallow(opts, function (d) {
362 return d.scripts && d.scripts[stage]