PageRenderTime 57ms CodeModel.GetById 11ms app.highlight 40ms RepoModel.GetById 1ms app.codeStats 0ms

/node_modules/hook.io/node_modules/npm/lib/utils/error-handler.js

https://bitbucket.org/baldpenguin/af-node-calipso
JavaScript | 288 lines | 242 code | 37 blank | 9 comment | 44 complexity | 4a7a70a444c8965f070bf99529c6ec92 MD5 | raw file
  1
  2module.exports = errorHandler
  3
  4var cbCalled = false
  5  , log = require("npmlog")
  6  , npm = require("../npm.js")
  7  , rm = require("rimraf")
  8  , itWorked = false
  9  , path = require("path")
 10  , ini = require("./ini.js")
 11  , wroteLogFile = false
 12  , exitCode = 0
 13
 14
 15process.on("exit", function (code) {
 16  // console.error("exit", code)
 17  if (!ini.resolved) return
 18  if (code) itWorked = false
 19  if (itWorked) log.info("ok")
 20  else {
 21    if (!cbCalled) {
 22      log.error("", "cb() never called!")
 23    }
 24
 25    if (wroteLogFile) {
 26      log.error("", [""
 27                ,"Additional logging details can be found in:"
 28                ,"    " + path.resolve("npm-debug.log")
 29                ].join("\n"))
 30      wroteLogFile = false
 31    }
 32    log.error("not ok", "code", code)
 33  }
 34
 35  var doExit = npm.config.get("_exit")
 36  if (doExit) {
 37    // actually exit.
 38    if (exitCode === 0 && !itWorked) {
 39      exitCode = 1
 40    }
 41    if (exitCode !== 0) process.exit(exitCode)
 42  } else {
 43    itWorked = false // ready for next exit
 44  }
 45})
 46
 47function exit (code, noLog) {
 48  exitCode = exitCode || code
 49
 50  var doExit = npm.config.get("_exit")
 51  log.verbose("exit", [code, doExit])
 52  if (log.level === "silent") noLog = true
 53
 54  if (code && !noLog) writeLogFile(reallyExit)
 55  else rm("npm-debug.log", function () { rm(npm.tmp, reallyExit) })
 56
 57  function reallyExit() {
 58    // truncate once it's been written.
 59    log.record.length = 0
 60
 61    itWorked = !code
 62
 63    // just emit a fake exit event.
 64    // if we're really exiting, then let it exit on its own, so that
 65    // in-process stuff can finish or clean up first.
 66    if (!doExit) process.emit("exit", code)
 67  }
 68}
 69
 70
 71function errorHandler (er) {
 72  var printStack = false
 73  // console.error("errorHandler", er)
 74  if (!ini.resolved) {
 75    // logging won't work unless we pretend that it's ready
 76    er = er || new Error("Exit prior to config file resolving.")
 77    console.error(er.stack || er.message)
 78  }
 79
 80  if (cbCalled) {
 81    er = er || new Error("Callback called more than once.")
 82  }
 83
 84  cbCalled = true
 85  if (!er) return exit(0)
 86  if (typeof er === "string") {
 87    log.error("", er)
 88    return exit(1, true)
 89  } else if (!(er instanceof Error)) {
 90    log.error("weird error", er)
 91    return exit(1, true)
 92  }
 93
 94  var m = er.code || er.message.match(/^(?:Error: )?(E[A-Z]+)/)
 95  if (m && !er.code) er.code = m
 96
 97  switch (er.code) {
 98  case "ECONNREFUSED":
 99    log.error("", er)
100    log.error("", ["\nIf you are behind a proxy, please make sure that the"
101              ,"'proxy' config is set properly.  See: 'npm help config'"
102              ].join("\n"))
103    printStack = true
104    break
105
106  case "EACCES":
107  case "EPERM":
108    log.error("", er)
109    log.error("", ["\nPlease try running this command again as root/Administrator."
110              ].join("\n"))
111    printStack = true
112    break
113
114  case "ELIFECYCLE":
115    er.code = "ELIFECYCLE"
116    log.error("", er.message)
117    log.error("", ["","Failed at the "+er.pkgid+" "+er.stage+" script."
118              ,"This is most likely a problem with the "+er.pkgname+" package,"
119              ,"not with npm itself."
120              ,"Tell the author that this fails on your system:"
121              ,"    "+er.script
122              ,"You can get their info via:"
123              ,"    npm owner ls "+er.pkgname
124              ,"There is likely additional logging output above."
125              ].join("\n"))
126    break
127
128  case "EJSONPARSE":
129    er.code = "EJSONPARSE"
130    log.error("", er.message)
131    log.error("", "File: "+er.file)
132    log.error("", ["Failed to parse package.json data."
133              ,"package.json must be actual JSON, not just JavaScript."
134              ,"","This is not a bug in npm."
135              ,"Tell the package author to fix their package.json file."
136              ].join("\n"), "JSON.parse")
137    break
138
139  case "E404":
140    er.code = "E404"
141    if (er.pkgid && er.pkgid !== "-") {
142      var msg = ["'"+er.pkgid+"' is not in the npm registry."
143                ,"You should bug the author to publish it"]
144      if (er.pkgid.match(/^node[\.\-]|[\.\-]js$/)) {
145        var s = er.pkgid.replace(/^node[\.\-]|[\.\-]js$/g, "")
146        if (s !== er.pkgid) {
147          s = s.replace(/[^a-z0-9]/g, ' ')
148          msg.push("\nMaybe try 'npm search " + s + "'")
149        }
150      }
151      msg.push("\nNote that you can also install from a"
152              ,"tarball, folder, or http url, or git url.")
153      log.error("404", msg.join("\n"))
154    }
155    break
156
157  case "EPUBLISHCONFLICT":
158    er.code = "EPUBLISHCONFLICT"
159    log.error("publish fail", ["Cannot publish over existing version."
160              ,"Bump the 'version' field, set the --force flag, or"
161              ,"    npm unpublish '"+er.pkgid+"'"
162              ,"and try again"
163              ].join("\n"))
164    break
165
166  case "EISGIT":
167    er.code = "EISGIT"
168    log.error("git", [er.message
169              ,"    "+er.path
170              ,"Refusing to remove it. Update manually,"
171              ,"or move it out of the way first."
172              ].join("\n"))
173    break
174
175  case "ECYCLE":
176    er.code = "ECYCLE"
177    log.error("cycle", [er.message
178              ,"While installing: "+er.pkgid
179              ,"Found a pathological dependency case that npm cannot solve."
180              ,"Please report this to the package author."
181              ].join("\n"))
182    break
183
184  case "EBADPLATFORM":
185    er.code = "EBADPLATFORM"
186    log.error("notsup", [er.message
187              ,"Not compatible with your operating system or architecture: "+er.pkgid
188              ,"Valid OS:    "+er.os.join(",")
189              ,"Valid Arch:  "+er.cpu.join(",")
190              ,"Actual OS:   "+process.platform
191              ,"Actual Arch: "+process.arch
192              ].join("\n"))
193    break
194
195  case "EEXIST":
196    log.error([er.message
197              ,"File exists: "+er.path
198              ,"Move it away, and try again."].join("\n"))
199    break
200
201  case "ENOTSUP":
202    if (er.required) {
203      log.error("notsup", [er.message
204                ,"Not compatible with your version of node/npm: "+er.pkgid
205                ,"Required: "+JSON.stringify(er.required)
206                ,"Actual:   "
207                +JSON.stringify({npm:npm.version
208                                ,node:npm.config.get("node-version")})
209                ].join("\n"))
210      break
211    } // else passthrough
212
213  default:
214    log.error("", er.stack || er.message || er)
215    log.error("", ["If you need help, you may report this log at:"
216                  ,"    <http://github.com/isaacs/npm/issues>"
217                  ,"or email it to:"
218                  ,"    <npm-@googlegroups.com>"
219                  ].join("\n"))
220    printStack = false
221    break
222  }
223
224  var os = require("os")
225  // just a line break
226  console.error("")
227  log.error("System", os.type() + " " + os.release())
228  log.error("command", process.argv
229            .map(JSON.stringify).join(" "))
230  log.error("cwd", process.cwd())
231  log.error("node -v", process.version)
232  log.error("npm -v", npm.version)
233
234  ; [ "file"
235    , "path"
236    , "type"
237    , "syscall"
238    , "fstream_path"
239    , "fstream_unc_path"
240    , "fstream_type"
241    , "fstream_class"
242    , "fstream_finish_call"
243    , "fstream_linkpath"
244    , "code"
245    , "errno"
246    , "stack"
247    , "fstream_stack"
248    ].forEach(function (k) {
249      var v = er[k]
250      if (k === "stack") {
251        if (!printStack) return
252        if (!v) v = er.message
253      }
254      if (!v) return
255      if (k === "fstream_stack") v = v.join("\n")
256      log.error(k, v)
257    })
258
259  exit(typeof er.errno === "number" ? er.errno : 1)
260}
261
262var writingLogFile = false
263function writeLogFile (cb) {
264  if (writingLogFile) return cb()
265  writingLogFile = true
266  wroteLogFile = true
267
268  var fs = require("graceful-fs")
269    , fstr = fs.createWriteStream("npm-debug.log")
270    , util = require("util")
271    , eol = process.platform === "win32" ? "\r\n" : "\n"
272    , out = ""
273
274  log.record.forEach(function (m) {
275    var pref = [m.id, m.level]
276    if (m.prefix) pref.push(m.prefix)
277    pref = pref.join(' ')
278
279    m.message.trim().split(/\r?\n/).map(function (line) {
280      return (pref + ' ' + line).trim()
281    }).forEach(function (line) {
282      out += line + eol
283    })
284  })
285
286  fstr.end(out)
287  fstr.on("close", cb)
288}