npm: upgrade to v1.4.14
[platform/upstream/nodejs.git] / deps / npm / lib / utils / lifecycle.js
1 exports = module.exports = lifecycle
2 exports.cmd = cmd
3 exports.makeEnv = makeEnv
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 || npm.config.get('ignore-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   if (log.level !== 'silent') {
165     if (npm.spinner.int) {
166       npm.config.get("logstream").write("\r \r")
167     }
168     console.log(note)
169   }
170   log.verbose("unsafe-perm in lifecycle", unsafe)
171
172   if (process.platform === "win32") {
173     unsafe = true
174   }
175
176   if (unsafe) {
177     runCmd_(cmd, pkg, env, wd, stage, unsafe, 0, 0, cb)
178   } else {
179     uidNumber(user, group, function (er, uid, gid) {
180       runCmd_(cmd, pkg, env, wd, stage, unsafe, uid, gid, cb)
181     })
182   }
183 }
184
185 function runCmd_ (cmd, pkg, env, wd, stage, unsafe, uid, gid, cb_) {
186
187   function cb (er) {
188     cb_.apply(null, arguments)
189     log.resume()
190     process.nextTick(dequeue)
191   }
192
193   var conf = { cwd: wd
194              , env: env
195              , stdio: [ 0, 1, 2 ]
196              }
197
198   if (!unsafe) {
199     conf.uid = uid ^ 0
200     conf.gid = gid ^ 0
201   }
202
203   var sh = "sh"
204   var shFlag = "-c"
205
206   if (process.platform === "win32") {
207     sh = "cmd"
208     shFlag = "/c"
209     conf.windowsVerbatimArguments = true
210   }
211
212   var proc = spawn(sh, [shFlag, cmd], conf)
213   proc.on("close", function (code, signal) {
214     if (signal) {
215       process.kill(process.pid, signal);
216     } else if (code) {
217       var er = new Error("Exit status " + code)
218     }
219     if (er && !npm.ROLLBACK) {
220       log.info(pkg._id, "Failed to exec "+stage+" script")
221       er.message = pkg._id + " "
222                  + stage + ": `" + cmd +"`\n"
223                  + er.message
224       if (er.code !== "EPERM") {
225         er.code = "ELIFECYCLE"
226       }
227       er.pkgid = pkg._id
228       er.stage = stage
229       er.script = cmd
230       er.pkgname = pkg.name
231       return cb(er)
232     } else if (er) {
233       log.error(pkg._id+"."+stage, er)
234       log.error(pkg._id+"."+stage, "continuing anyway")
235       return cb()
236     }
237     cb(er)
238   })
239 }
240
241
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")
248     , cmd = hook
249
250   fs.stat(hook, function (er) {
251     if (er) return cb()
252     var note = "\n> " + pkg._id + " " + stage + " " + wd
253              + "\n> " + cmd
254     runCmd(note, hook, pkg, env, stage, wd, unsafe, cb)
255   })
256 }
257
258 function makeEnv (data, prefix, env) {
259   prefix = prefix || "npm_package_"
260   if (!env) {
261     env = {}
262     for (var i in process.env) if (!i.match(/^npm_/)) {
263       env[i] = process.env[i]
264     }
265
266     // npat asks for tap output
267     if (npm.config.get("npat")) env.TAP = 1
268
269     // express and others respect the NODE_ENV value.
270     if (npm.config.get("production")) env.NODE_ENV = "production"
271
272   } else if (!data.hasOwnProperty("_lifecycleEnv")) {
273     Object.defineProperty(data, "_lifecycleEnv",
274       { value : env
275       , enumerable : false
276       })
277   }
278
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") {
282       continue
283     }
284     if (data[i] && typeof(data[i]) === "object") {
285       try {
286         // quick and dirty detection for cyclical structures
287         JSON.stringify(data[i])
288         makeEnv(data[i], envKey+"_", env)
289       } catch (ex) {
290         // usually these are package objects.
291         // just get the path and basic details.
292         var d = data[i]
293         makeEnv( { name: d.name, version: d.version, path:d.path }
294                , envKey+"_", env)
295       }
296     } else {
297       env[envKey] = String(data[i])
298       env[envKey] = -1 !== env[envKey].indexOf("\n")
299                   ? JSON.stringify(env[envKey])
300                   : env[envKey]
301     }
302
303   }
304
305   if (prefix !== "npm_package_") return env
306
307   prefix = "npm_config_"
308   var pkgConfig = {}
309     , keys = npm.config.keys
310     , pkgVerConfig = {}
311     , namePref = data.name + ":"
312     , verPref = data.name + "@" + data.version + ":"
313
314   keys.forEach(function (i) {
315     if (i.charAt(0) === "_" && i.indexOf("_"+namePref) !== 0) {
316       return
317     }
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)
323
324     value = -1 !== value.indexOf("\n")
325           ? JSON.stringify(value)
326           : 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
334     }
335     var envKey = (prefix+i).replace(/[^a-zA-Z0-9_]/g, "_")
336     env[envKey] = value
337   })
338
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]
344     }
345   })
346
347   return env
348 }
349
350 function cmd (stage) {
351   function CMD (args, cb) {
352     if (args.length) {
353       chain(args.map(function (p) {
354         return [npm.commands, "run-script", [p, stage]]
355       }), cb)
356     } else npm.commands["run-script"]([stage], cb)
357   }
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]
363     }, cb)
364   }
365   return CMD
366 }