2 exports = module.exports = lifecycle
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) 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")
165 log.verbose("unsafe-perm in lifecycle", unsafe)
167 if (process.platform === "win32") {
172 runCmd_(cmd, pkg, env, wd, stage, unsafe, 0, 0, cb)
174 uidNumber(user, group, function (er, uid, gid) {
175 runCmd_(cmd, pkg, env, wd, stage, unsafe, uid, gid, cb)
180 function runCmd_ (cmd, pkg, env, wd, stage, unsafe, uid, gid, cb_) {
183 cb_.apply(null, arguments)
185 process.nextTick(dequeue)
191 if (process.platform === "win32") {
206 var proc = spawn(sh, [shFlag, cmd], conf)
207 proc.on("close", function (code, signal) {
209 process.kill(process.pid, signal);
211 var er = new Error("Exit status " + code)
213 if (er && !npm.ROLLBACK) {
214 log.info(pkg._id, "Failed to exec "+stage+" script")
215 er.message = pkg._id + " "
216 + stage + ": `" + cmd +"`\n"
218 if (er.code !== "EPERM") {
219 er.code = "ELIFECYCLE"
224 er.pkgname = pkg.name
227 log.error(pkg._id+"."+stage, er)
228 log.error(pkg._id+"."+stage, "continuing anyway")
236 function runHookLifecycle (pkg, env, wd, unsafe, cb) {
237 // check for a hook script, run if present.
238 var stage = env.npm_lifecycle_event
239 , hook = path.join(npm.dir, ".hooks", stage)
240 , user = unsafe ? null : npm.config.get("user")
241 , group = unsafe ? null : npm.config.get("group")
244 fs.stat(hook, function (er) {
246 var note = "\n> " + pkg._id + " " + stage + " " + wd
248 runCmd(note, hook, pkg, env, stage, wd, unsafe, cb)
252 function makeEnv (data, prefix, env) {
253 prefix = prefix || "npm_package_"
256 for (var i in process.env) if (!i.match(/^npm_/)) {
257 env[i] = process.env[i]
260 // npat asks for tap output
261 if (npm.config.get("npat")) env.TAP = 1
263 // express and others respect the NODE_ENV value.
264 if (npm.config.get("production")) env.NODE_ENV = "production"
266 } else if (!data.hasOwnProperty("_lifecycleEnv")) {
267 Object.defineProperty(data, "_lifecycleEnv",
273 for (var i in data) if (i.charAt(0) !== "_") {
274 var envKey = (prefix+i).replace(/[^a-zA-Z0-9_]/g, '_')
275 if (i === "readme") {
278 if (data[i] && typeof(data[i]) === "object") {
280 // quick and dirty detection for cyclical structures
281 JSON.stringify(data[i])
282 makeEnv(data[i], envKey+"_", env)
284 // usually these are package objects.
285 // just get the path and basic details.
287 makeEnv( { name: d.name, version: d.version, path:d.path }
291 env[envKey] = String(data[i])
292 env[envKey] = -1 !== env[envKey].indexOf("\n")
293 ? JSON.stringify(env[envKey])
299 if (prefix !== "npm_package_") return env
301 prefix = "npm_config_"
303 , keys = npm.config.keys
305 , namePref = data.name + ":"
306 , verPref = data.name + "@" + data.version + ":"
308 keys.forEach(function (i) {
309 if (i.charAt(0) === "_" && i.indexOf("_"+namePref) !== 0) {
312 var value = npm.config.get(i)
313 if (value instanceof Stream || Array.isArray(value)) return
314 if (!value) value = ""
315 else if (typeof value !== "string") value = JSON.stringify(value)
317 value = -1 !== value.indexOf("\n")
318 ? JSON.stringify(value)
320 i = i.replace(/^_+/, "")
321 if (i.indexOf(namePref) === 0) {
322 var k = i.substr(namePref.length).replace(/[^a-zA-Z0-9_]/g, "_")
323 pkgConfig[ k ] = value
324 } else if (i.indexOf(verPref) === 0) {
325 var k = i.substr(verPref.length).replace(/[^a-zA-Z0-9_]/g, "_")
326 pkgVerConfig[ k ] = value
328 var envKey = (prefix+i).replace(/[^a-zA-Z0-9_]/g, "_")
332 prefix = "npm_package_config_"
333 ;[pkgConfig, pkgVerConfig].forEach(function (conf) {
334 for (var i in conf) {
335 var envKey = (prefix+i)
336 env[envKey] = conf[i]
343 function cmd (stage) {
344 function CMD (args, cb) {
346 chain(args.map(function (p) {
347 return [npm.commands, "run-script", [p, stage]]
349 } else npm.commands["run-script"]([stage], cb)
351 CMD.usage = "npm "+stage+" <name>"
352 var installedShallow = require("./completion/installed-shallow.js")
353 CMD.completion = function (opts, cb) {
354 installedShallow(opts, function (d) {
355 return d.scripts && d.scripts[stage]