71c8e07b82e28e32e0c9925dfa631bf8e9fcc8b1
[platform/upstream/nodejs.git] / deps / npm / lib / utils / lifecycle.js
1
2 exports = module.exports = lifecycle
3 exports.cmd = cmd
4
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
12   , PATH = "PATH"
13   , uidNumber = require("uid-number")
14
15 // windows calls it's path "Path" usually, but this is not guaranteed.
16 if (process.platform === "win32") {
17   PATH = "Path"
18   Object.keys(process.env).forEach(function (e) {
19     if (e.match(/^PATH$/i)) {
20       PATH = e
21     }
22   })
23 }
24
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
29
30   while (pkg && pkg._data) pkg = pkg._data
31   if (!pkg) return cb(new Error("Invalid package data"))
32
33   log.info(stage, pkg._id)
34   if (!pkg.scripts) pkg.scripts = {}
35
36   validWd(wd || path.resolve(npm.dir, pkg.name), function (er, wd) {
37     if (er) return cb(er)
38
39     unsafe = unsafe || npm.config.get("unsafe-perm")
40
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)
45       return cb()
46     }
47
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
53
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
57
58     lifecycle_(pkg, stage, wd, env, unsafe, failOk, cb)
59   })
60 }
61
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()))
66   })
67 }
68
69 function lifecycle_ (pkg, stage, wd, env, unsafe, failOk, cb) {
70   var pathArr = []
71     , p = wd.split("node_modules")
72     , acc = path.resolve(p.shift())
73
74   // first add the directory containing the `node` executable currently
75   // running, so that any lifecycle script that invoke "node" will execute
76   // this same one.
77   pathArr.unshift(path.dirname(process.execPath))
78
79   p.forEach(function (pp) {
80     pathArr.unshift(path.join(acc, "node_modules", ".bin"))
81     acc = path.join(acc, "node_modules", pp)
82   })
83   pathArr.unshift(path.join(acc, "node_modules", ".bin"))
84
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"))
88
89   if (env[PATH]) pathArr.push(env[PATH])
90   env[PATH] = pathArr.join(process.platform === "win32" ? ";" : ":")
91
92   var packageLifecycle = pkg.scripts && pkg.scripts.hasOwnProperty(stage)
93
94   if (packageLifecycle) {
95     // define this here so it's available to all scripts.
96     env.npm_lifecycle_script = pkg.scripts[stage]
97   }
98
99   if (failOk) {
100     cb = (function (cb_) { return function (er) {
101       if (er) log.warn("continuing anyway", er.message)
102       cb_()
103     }})(cb)
104   }
105
106   if (npm.config.get("force")) {
107     cb = (function (cb_) { return function (er) {
108       if (er) log.info("forced, continuing", er)
109       cb_()
110     }})(cb)
111   }
112
113   chain
114     ( [ packageLifecycle && [runPackageLifecycle, pkg, env, wd, unsafe]
115       , [runHookLifecycle, pkg, env, wd, unsafe] ]
116     , cb )
117 }
118
119 function validWd (d, cb) {
120   fs.stat(d, function (er, st) {
121     if (er || !st.isDirectory()) {
122       var p = path.dirname(d)
123       if (p === d) {
124         return cb(new Error("Could not find suitable wd"))
125       }
126       return validWd(p, cb)
127     }
128     return cb(null, d)
129   })
130 }
131
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
136
137   var note = "\n> " + pkg._id + " " + stage + " " + wd
138            + "\n> " + cmd + "\n"
139   runCmd(note, cmd, pkg, env, stage, wd, unsafe, cb)
140 }
141
142
143 var running = false
144 var queue = []
145 function dequeue() {
146   running = false
147   if (queue.length) {
148     var r = queue.shift()
149     runCmd.apply(null, r)
150   }
151 }
152
153 function runCmd (note, cmd, pkg, env, stage, wd, unsafe, cb) {
154   if (running) {
155     queue.push([note, cmd, pkg, env, stage, wd, unsafe, cb])
156     return
157   }
158
159   running = true
160   log.pause()
161   var user = unsafe ? null : npm.config.get("user")
162     , group = unsafe ? null : npm.config.get("group")
163
164   console.log(note)
165   log.verbose("unsafe-perm in lifecycle", unsafe)
166
167   if (process.platform === "win32") {
168     unsafe = true
169   }
170
171   if (unsafe) {
172     runCmd_(cmd, pkg, env, wd, stage, unsafe, 0, 0, cb)
173   } else {
174     uidNumber(user, group, function (er, uid, gid) {
175       runCmd_(cmd, pkg, env, wd, stage, unsafe, uid, gid, cb)
176     })
177   }
178 }
179
180 function runCmd_ (cmd, pkg, env, wd, stage, unsafe, uid, gid, cb_) {
181
182   function cb (er) {
183     cb_.apply(null, arguments)
184     log.resume()
185     process.nextTick(dequeue)
186   }
187
188   var sh = "sh"
189   var shFlag = "-c"
190
191   if (process.platform === "win32") {
192     sh = "cmd"
193     shFlag = "/c"
194   }
195
196   var conf = { cwd: wd
197              , env: env
198              , stdio: [ 0, 1, 2 ]
199              }
200
201   if (!unsafe) {
202     conf.uid = uid ^ 0
203     conf.gid = gid ^ 0
204   }
205
206   var proc = spawn(sh, [shFlag, cmd], conf)
207   proc.on("close", function (code, signal) {
208     if (signal) {
209       process.kill(process.pid, signal);
210     } else if (code) {
211       var er = new Error("Exit status " + code)
212     }
213     if (er && !npm.ROLLBACK) {
214       log.info(pkg._id, "Failed to exec "+stage+" script")
215       er.message = pkg._id + " "
216                  + stage + ": `" + cmd +"`\n"
217                  + er.message
218       if (er.code !== "EPERM") {
219         er.code = "ELIFECYCLE"
220       }
221       er.pkgid = pkg._id
222       er.stage = stage
223       er.script = cmd
224       er.pkgname = pkg.name
225       return cb(er)
226     } else if (er) {
227       log.error(pkg._id+"."+stage, er)
228       log.error(pkg._id+"."+stage, "continuing anyway")
229       return cb()
230     }
231     cb(er)
232   })
233 }
234
235
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")
242     , cmd = hook
243
244   fs.stat(hook, function (er) {
245     if (er) return cb()
246     var note = "\n> " + pkg._id + " " + stage + " " + wd
247              + "\n> " + cmd
248     runCmd(note, hook, pkg, env, stage, wd, unsafe, cb)
249   })
250 }
251
252 function makeEnv (data, prefix, env) {
253   prefix = prefix || "npm_package_"
254   if (!env) {
255     env = {}
256     for (var i in process.env) if (!i.match(/^npm_/)) {
257       env[i] = process.env[i]
258     }
259
260     // npat asks for tap output
261     if (npm.config.get("npat")) env.TAP = 1
262
263     // express and others respect the NODE_ENV value.
264     if (npm.config.get("production")) env.NODE_ENV = "production"
265
266   } else if (!data.hasOwnProperty("_lifecycleEnv")) {
267     Object.defineProperty(data, "_lifecycleEnv",
268       { value : env
269       , enumerable : false
270       })
271   }
272
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") {
276       continue
277     }
278     if (data[i] && typeof(data[i]) === "object") {
279       try {
280         // quick and dirty detection for cyclical structures
281         JSON.stringify(data[i])
282         makeEnv(data[i], envKey+"_", env)
283       } catch (ex) {
284         // usually these are package objects.
285         // just get the path and basic details.
286         var d = data[i]
287         makeEnv( { name: d.name, version: d.version, path:d.path }
288                , envKey+"_", env)
289       }
290     } else {
291       env[envKey] = String(data[i])
292       env[envKey] = -1 !== env[envKey].indexOf("\n")
293                   ? JSON.stringify(env[envKey])
294                   : env[envKey]
295     }
296
297   }
298
299   if (prefix !== "npm_package_") return env
300
301   prefix = "npm_config_"
302   var pkgConfig = {}
303     , keys = npm.config.keys
304     , pkgVerConfig = {}
305     , namePref = data.name + ":"
306     , verPref = data.name + "@" + data.version + ":"
307
308   keys.forEach(function (i) {
309     if (i.charAt(0) === "_" && i.indexOf("_"+namePref) !== 0) {
310       return
311     }
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)
316
317     value = -1 !== value.indexOf("\n")
318           ? JSON.stringify(value)
319           : 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
327     }
328     var envKey = (prefix+i).replace(/[^a-zA-Z0-9_]/g, "_")
329     env[envKey] = value
330   })
331
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]
337     }
338   })
339
340   return env
341 }
342
343 function cmd (stage) {
344   function CMD (args, cb) {
345     if (args.length) {
346       chain(args.map(function (p) {
347         return [npm.commands, "run-script", [p, stage]]
348       }), cb)
349     } else npm.commands["run-script"]([stage], cb)
350   }
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]
356     }, cb)
357   }
358   return CMD
359 }