diff options
author | Forrest L Norvell <forrest@npmjs.com> | 2015-06-23 08:18:52 +0300 |
---|---|---|
committer | Rebecca Turner <me@re-becca.org> | 2015-06-26 03:27:33 +0300 |
commit | b50be6aff34a739ca43de65f546e743d1a9975b9 (patch) | |
tree | 3153fd3a271245b8a05a9be196286fbe31fc9d44 | |
parent | 7c5ebe0552b7b5d0cdca34d28c4f16fe794ff2ff (diff) |
src: make the npm source comply with `standard`
This is a huge set of mostly mechanical changes. Going forward, all
changes to the npm source base are expected to comply with `standard`,
and it's been integrated into the test suite to enforce that. There are
a few notes below about specific classes of changes that need to be
handled specially for npm's code base.
standard: "Expected error to be handled."
`standard` only expects errors spelled "err" to be handled.
`npm-registry-mock` never actually invokes its callback with an error,
so in some cases I just changed it to be spelled "er" and called it
good.
standard: "Expected a "break" statement before 'case'."
This behavior is actually on purpose, and I don't feel like rewriting
the affected code right now (or, you know, ever). So I added code
comments disabling the checks in the three applicable changes.
standard: "x is a function."
Rebinding functions created via declarations (as opposed to expressions)
is a no-no?
PR-URL: https://github.com/npm/npm/pull/8668
207 files changed, 6637 insertions, 6455 deletions
diff --git a/bin/npm-cli.js b/bin/npm-cli.js index 82a75be52..c60fd737e 100755 --- a/bin/npm-cli.js +++ b/bin/npm-cli.js @@ -1,79 +1,79 @@ #!/usr/bin/env node ;(function () { // wrapper in case we're in module_context mode -// windows: running "npm blah" in this folder will invoke WSH, not node. -if (typeof WScript !== "undefined") { - WScript.echo("npm does not work when run\n" - +"with the Windows Scripting Host\n\n" - +"'cd' to a different directory,\n" - +"or type 'npm.cmd <args>',\n" - +"or type 'node npm <args>'.") - WScript.quit(1) - return -} - - -process.title = "npm" - -var log = require("npmlog") -log.pause() // will be unpaused when config is loaded. -log.enableProgress() - -log.info("it worked if it ends with", "ok") - -var path = require("path") - , log = require("npmlog") - , npm = require("../lib/npm.js") - , npmconf = require("../lib/config/core.js") - , errorHandler = require("../lib/utils/error-handler.js") - - , configDefs = npmconf.defs - , shorthands = configDefs.shorthands - , types = configDefs.types - , nopt = require("nopt") - -// if npm is called as "npmg" or "npm_g", then -// run in global mode. -if (path.basename(process.argv[1]).slice(-1) === "g") { - process.argv.splice(1, 1, "npm", "-g") -} - -log.verbose("cli", process.argv) - -var conf = nopt(types, shorthands) -npm.argv = conf.argv.remain -if (npm.deref(npm.argv[0])) npm.command = npm.argv.shift() -else conf.usage = true - - -if (conf.version) { - console.log(npm.version) - return -} - -if (conf.versions) { - npm.command = "version" - conf.usage = false - npm.argv = [] -} - -log.info("using", "npm@%s", npm.version) -log.info("using", "node@%s", process.version) - -process.on("uncaughtException", errorHandler) - -if (conf.usage && npm.command !== "help") { - npm.argv.unshift(npm.command) - npm.command = "help" -} - -// now actually fire up npm and run the command. -// this is how to use npm programmatically: -conf._exit = true -npm.load(conf, function (er) { - if (er) return errorHandler(er) + // windows: running "npm blah" in this folder will invoke WSH, not node. + /*global WScript*/ + if (typeof WScript !== 'undefined') { + WScript.echo( + 'npm does not work when run\n' + + 'with the Windows Scripting Host\n\n' + + "'cd' to a different directory,\n" + + "or type 'npm.cmd <args>',\n" + + "or type 'node npm <args>'." + ) + WScript.quit(1) + return + } + + process.title = 'npm' + + var log = require('npmlog') + log.pause() // will be unpaused when config is loaded. log.enableProgress() - npm.commands[npm.command](npm.argv, errorHandler) -}) + + log.info('it worked if it ends with', 'ok') + + var path = require('path') + var npm = require('../lib/npm.js') + var npmconf = require('../lib/config/core.js') + var errorHandler = require('../lib/utils/error-handler.js') + + var configDefs = npmconf.defs + var shorthands = configDefs.shorthands + var types = configDefs.types + var nopt = require('nopt') + + // if npm is called as "npmg" or "npm_g", then + // run in global mode. + if (path.basename(process.argv[1]).slice(-1) === 'g') { + process.argv.splice(1, 1, 'npm', '-g') + } + + log.verbose('cli', process.argv) + + var conf = nopt(types, shorthands) + npm.argv = conf.argv.remain + if (npm.deref(npm.argv[0])) npm.command = npm.argv.shift() + else conf.usage = true + + if (conf.version) { + console.log(npm.version) + return + } + + if (conf.versions) { + npm.command = 'version' + conf.usage = false + npm.argv = [] + } + + log.info('using', 'npm@%s', npm.version) + log.info('using', 'node@%s', process.version) + + process.on('uncaughtException', errorHandler) + + if (conf.usage && npm.command !== 'help') { + npm.argv.unshift(npm.command) + npm.command = 'help' + } + + // now actually fire up npm and run the command. + // this is how to use npm programmatically: + conf._exit = true + npm.load(conf, function (er) { + if (er) return errorHandler(er) + log.enableProgress() + npm.commands[npm.command](npm.argv, errorHandler) + }) })() diff --git a/bin/read-package-json.js b/bin/read-package-json.js index 3e5a0c77f..7e62a0bd7 100755 --- a/bin/read-package-json.js +++ b/bin/read-package-json.js @@ -1,22 +1,24 @@ var argv = process.argv if (argv.length < 3) { - console.error("Usage: read-package.json <file> [<fields> ...]") + console.error('Usage: read-package.json <file> [<fields> ...]') process.exit(1) } -var fs = require("fs") - , file = argv[2] - , readJson = require("read-package-json") +var file = argv[2] +var readJson = require('read-package-json') readJson(file, function (er, data) { if (er) throw er - if (argv.length === 3) console.log(data) - else argv.slice(3).forEach(function (field) { - field = field.split(".") - var val = data - field.forEach(function (f) { - val = val[f] + if (argv.length === 3) { + console.log(data) + } else { + argv.slice(3).forEach(function (field) { + field = field.split('.') + var val = data + field.forEach(function (f) { + val = val[f] + }) + console.log(val) }) - console.log(val) - }) + } }) @@ -1,2 +1,2 @@ #!/usr/bin/env node -require("./bin/npm-cli.js") +require('./bin/npm-cli.js') diff --git a/html/static/toc.js b/html/static/toc.js index 2cfebd0aa..7551e47ef 100644 --- a/html/static/toc.js +++ b/html/static/toc.js @@ -1,29 +1,29 @@ ;(function () { -var wrapper = document.getElementById("wrapper") -var els = Array.prototype.slice.call(wrapper.getElementsByTagName("*"), 0) - .filter(function (el) { - return el.parentNode === wrapper - && el.tagName.match(/H[1-6]/) - && el.id - }) -var l = 2 - , toc = document.createElement("ul") -toc.innerHTML = els.map(function (el) { - var i = el.tagName.charAt(1) - , out = "" - while (i > l) { - out += "<ul>" - l ++ - } - while (i < l) { - out += "</ul>" - l -- - } - out += "<li><a href='#" + el.id + "'>" + - ( el.innerText || el.text || el.innerHTML) - + "</a>" - return out -}).join("\n") -toc.id = "toc" -document.body.appendChild(toc) -})(); + var wrapper = document.getElementById('wrapper') + var els = Array.prototype.slice.call(wrapper.getElementsByTagName('*'), 0) + .filter(function (el) { + return el.parentNode === wrapper && + el.tagName.match(/H[1-6]/) && + el.id + }) + var l = 2 + var toc = document.createElement('ul') + toc.innerHTML = els.map(function (el) { + var i = el.tagName.charAt(1) + var out = '' + while (i > l) { + out += '<ul>' + l++ + } + while (i < l) { + out += '</ul>' + l-- + } + out += '<li><a href=\'#' + el.id + '\'>' + + (el.innerText || el.text || el.innerHTML) + + '</a>' + return out + }).join('\n') + toc.id = 'toc' + document.body.appendChild(toc) +})() diff --git a/lib/access.js b/lib/access.js index cf960a67d..7a4fda7d3 100644 --- a/lib/access.js +++ b/lib/access.js @@ -1,80 +1,80 @@ -var assert = require("assert") -var resolve = require("path").resolve -var url = require("url") +var assert = require('assert') +var resolve = require('path').resolve +var url = require('url') -var log = require("npmlog") -var readPackageJson = require("read-package-json") +var log = require('npmlog') +var readPackageJson = require('read-package-json') -var mapToRegistry = require("./utils/map-to-registry.js") -var npa = require("npm-package-arg") -var npm = require("./npm.js") +var mapToRegistry = require('./utils/map-to-registry.js') +var npa = require('npm-package-arg') +var npm = require('./npm.js') module.exports = access -access.usage = "npm access public [<package>]" - + "\nnpm access restricted [<package>]" - + "\nnpm access add <read-only|read-write> <entity> [<package>]" - + "\nnpm access rm <entity> [<package>]" - + "\nnpm access ls [<package>]" - + "\nnpm access edit [<package>]" +access.usage = 'npm access public [<package>]' + + '\nnpm access restricted [<package>]' + + '\nnpm access add <read-only|read-write> <entity> [<package>]' + + '\nnpm access rm <entity> [<package>]' + + '\nnpm access ls [<package>]' + + '\nnpm access edit [<package>]' access.completion = function (opts, cb) { var argv = opts.conf.argv.remain if (argv.length === 2) { - return cb(null, ["public", "restricted", "add", "rm", "ls", "edit"]) + return cb(null, ['public', 'restricted', 'add', 'rm', 'ls', 'edit']) } switch (argv[2]) { - case "public": - case "restricted": - case "ls": - case "edit": - return cb(new Error("unimplemented: packages you can change")) - case "add": - if (argv.length === 3) return cb(null, ["read-only", "read-write"]) - - return cb(new Error("unimplemented: entities and packages")) - case "rm": - return cb(new Error("unimplemented: entities and packages")) + case 'public': + case 'restricted': + case 'ls': + case 'edit': + return cb(new Error('unimplemented: packages you can change')) + case 'add': + if (argv.length === 3) return cb(null, ['read-only', 'read-write']) + + return cb(new Error('unimplemented: entities and packages')) + case 'rm': + return cb(new Error('unimplemented: entities and packages')) default: - return cb(new Error(argv[2]+" not recognized")) + return cb(new Error(argv[2] + ' not recognized')) } } function access (args, cb) { var cmd = args.shift() switch (cmd) { - case "public": case "restricted": return changeAccess(args, cmd, cb) - case "add": case "set": return add(args, cb) - case "rm": case "del": case "clear": return rm(args, cb) - case "list": case "sl": case "ls": return ls(args, cb) - case "edit": case "ed": return edit(args, cb) - default: return cb("Usage:\n"+access.usage) + case 'public': case 'restricted': return changeAccess(args, cmd, cb) + case 'add': case 'set': return add(args, cb) + case 'rm': case 'del': case 'clear': return rm(args, cb) + case 'list': case 'sl': case 'ls': return ls(args, cb) + case 'edit': case 'ed': return edit(args, cb) + default: return cb('Usage:\n' + access.usage) } } function changeAccess (args, level, cb) { - assert(Array.isArray(args), "changeAccess requires args be an array") + assert(Array.isArray(args), 'changeAccess requires args be an array') assert( - ["public", "restricted"].indexOf(level) !== -1, + ['public', 'restricted'].indexOf(level) !== -1, "access level must be either 'public' or 'restricted'" ) - assert(typeof cb === "function", "changeAccess requires a callback") + assert(typeof cb === 'function', 'changeAccess requires a callback') - var p = (args.shift() || "").trim() + var p = (args.shift() || '').trim() if (!p) return getCurrentPackage(level, cb) changeAccess_(p, level, cb) } function getCurrentPackage (level, cb) { - var here = resolve(npm.prefix, "package.json") - log.verbose("setPackageLevel", "here", here) + var here = resolve(npm.prefix, 'package.json') + log.verbose('setPackageLevel', 'here', here) readPackageJson(here, function (er, data) { if (er) return cb(er) if (!data.name) { - return cb(new Error("Package must be named")) + return cb(new Error('Package must be named')) } changeAccess_(data.name, level, cb) @@ -82,24 +82,24 @@ function getCurrentPackage (level, cb) { } function changeAccess_ (name, level, cb) { - log.verbose("changeAccess", "name", name, "level", level) + log.verbose('changeAccess', 'name', name, 'level', level) mapToRegistry(name, npm.config, function (er, uri, auth, base) { if (er) return cb(er) var data = npa(name) if (!data.scope) { var msg = "Sorry, you can't change the access level of unscoped packages." - log.error("access", msg) + log.error('access', msg) return cb(new Error(msg)) } // name must be scoped, so escape separator - name = name.replace("/", "%2f") + name = name.replace('/', '%2f') // FIXME: mapToRegistry still isn't generic enough SIGH - uri = url.resolve(base, "-/package/"+name+"/access") + uri = url.resolve(base, '-/package/' + name + '/access') var params = { - level : level, - auth : auth + level: level, + auth: auth } npm.registry.access(uri, params, cb) diff --git a/lib/adduser.js b/lib/adduser.js index 79babe02c..cd4db2b5d 100644 --- a/lib/adduser.js +++ b/lib/adduser.js @@ -1,29 +1,32 @@ - module.exports = adduser -var log = require("npmlog") - , npm = require("./npm.js") - , read = require("read") - , userValidate = require("npm-user-validate") - , crypto +var log = require('npmlog') +var npm = require('./npm.js') +var read = require('read') +var userValidate = require('npm-user-validate') +var crypto try { - crypto = process.binding("crypto") && require("crypto") + crypto = process.binding('crypto') && require('crypto') } catch (ex) {} -adduser.usage = "npm adduser [--registry=url] [--scope=@orgname] [--always-auth]" +adduser.usage = 'npm adduser [--registry=url] [--scope=@orgname] [--always-auth]' function adduser (args, cb) { - if (!crypto) return cb(new Error( - "You must compile node with ssl support to use the adduser feature")) + if (!crypto) { + return cb(new Error( + 'You must compile node with ssl support to use the adduser feature' + )) + } - var creds = npm.config.getCredentialsByURI(npm.config.get("registry")) - var c = { u : creds.username || "" - , p : creds.password || "" - , e : creds.email || "" - } - , u = {} - , fns = [readUsername, readPassword, readEmail, save] + var creds = npm.config.getCredentialsByURI(npm.config.get('registry')) + var c = { + u: creds.username || '', + p: creds.password || '', + e: creds.email || '' + } + var u = {} + var fns = [readUsername, readPassword, readEmail, save] loop() function loop (er) { @@ -36,9 +39,9 @@ function adduser (args, cb) { function readUsername (c, u, cb) { var v = userValidate.username - read({prompt: "Username: ", default: c.u || ""}, function (er, un) { + read({prompt: 'Username: ', default: c.u || ''}, function (er, un) { if (er) { - return cb(er.message === "cancelled" ? er.message : er) + return cb(er.message === 'cancelled' ? er.message : er) } // make sure it's valid. we have to do this here, because @@ -67,17 +70,17 @@ function readPassword (c, u, cb) { var prompt if (c.p && !c.changed) { - prompt = "Password: (or leave unchanged) " + prompt = 'Password: (or leave unchanged) ' } else { - prompt = "Password: " + prompt = 'Password: ' } read({prompt: prompt, silent: true}, function (er, pw) { if (er) { - return cb(er.message === "cancelled" ? er.message : er) + return cb(er.message === 'cancelled' ? er.message : er) } - if (!c.changed && pw === "") { + if (!c.changed && pw === '') { // when the username was not changed, // empty response means "use the old value" pw = c.p @@ -101,10 +104,10 @@ function readPassword (c, u, cb) { function readEmail (c, u, cb) { var v = userValidate.email - var r = { prompt: "Email: (this IS public) ", default: c.e || "" } + var r = { prompt: 'Email: (this IS public) ', default: c.e || '' } read(r, function (er, em) { if (er) { - return cb(er.message === "cancelled" ? er.message : er) + return cb(er.message === 'cancelled' ? er.message : er) } if (!em) { @@ -124,48 +127,47 @@ function readEmail (c, u, cb) { function save (c, u, cb) { // save existing configs, but yank off for this PUT - var uri = npm.config.get("registry") - var scope = npm.config.get("scope") + var uri = npm.config.get('registry') + var scope = npm.config.get('scope') // there may be a saved scope and no --registry (for login) if (scope) { - if (scope.charAt(0) !== "@") scope = "@" + scope + if (scope.charAt(0) !== '@') scope = '@' + scope - var scopedRegistry = npm.config.get(scope + ":registry") - var cliRegistry = npm.config.get("registry", "cli") + var scopedRegistry = npm.config.get(scope + ':registry') + var cliRegistry = npm.config.get('registry', 'cli') if (scopedRegistry && !cliRegistry) uri = scopedRegistry } var params = { - auth : { - username : u.u, - password : u.p, - email : u.e + auth: { + username: u.u, + password: u.p, + email: u.e } } npm.registry.adduser(uri, params, function (er, doc) { if (er) return cb(er) // don't want this polluting the configuration - npm.config.del("_token", "user") + npm.config.del('_token', 'user') - if (scope) npm.config.set(scope + ":registry", uri, "user") + if (scope) npm.config.set(scope + ':registry', uri, 'user') if (doc && doc.token) { npm.config.setCredentialsByURI(uri, { - token : doc.token + token: doc.token }) - } - else { + } else { npm.config.setCredentialsByURI(uri, { - username : u.u, - password : u.p, - email : u.e, - alwaysAuth : npm.config.get("always-auth") + username: u.u, + password: u.p, + email: u.e, + alwaysAuth: npm.config.get('always-auth') }) } - log.info("adduser", "Authorized user %s", u.u) - npm.config.save("user", cb) + log.info('adduser', 'Authorized user %s', u.u) + npm.config.save('user', cb) }) } diff --git a/lib/bin.js b/lib/bin.js index 62922447b..2e02617d3 100644 --- a/lib/bin.js +++ b/lib/bin.js @@ -1,19 +1,22 @@ module.exports = bin -var npm = require("./npm.js") -var osenv = require("osenv") +var npm = require('./npm.js') +var osenv = require('osenv') -bin.usage = "npm bin [--global]" +bin.usage = 'npm bin [--global]' function bin (args, silent, cb) { - if (typeof cb !== "function") cb = silent, silent = false + if (typeof cb !== 'function') { + cb = silent + silent = false + } var b = npm.bin - , PATH = osenv.path() + var PATH = osenv.path() if (!silent) console.log(b) process.nextTick(cb.bind(this, null, b)) - if (npm.config.get("global") && PATH.indexOf(b) === -1) { - npm.config.get("logstream").write("(not in PATH env variable)\n") + if (npm.config.get('global') && PATH.indexOf(b) === -1) { + npm.config.get('logstream').write('(not in PATH env variable)\n') } } diff --git a/lib/bugs.js b/lib/bugs.js index c7f094bf3..d42e68faa 100644 --- a/lib/bugs.js +++ b/lib/bugs.js @@ -1,13 +1,11 @@ module.exports = bugs -bugs.usage = "npm bugs [<pkgname>]" +bugs.usage = 'npm bugs [<pkgname>]' -var npm = require("./npm.js") - , log = require("npmlog") - , opener = require("opener") - , fetchPackageMetadata = require("./fetch-package-metadata.js") - , mapToRegistry = require("./utils/map-to-registry.js") - , registry = npm.registry +var npm = require('./npm.js') +var log = require('npmlog') +var opener = require('opener') +var fetchPackageMetadata = require('./fetch-package-metadata.js') bugs.completion = function (opts, cb) { // FIXME: there used to be registry completion here, but it stopped making @@ -16,15 +14,15 @@ bugs.completion = function (opts, cb) { } function bugs (args, cb) { - var n = args.length ? args[0] : "." - fetchPackageMetadata(n, ".", function (er, d) { + var n = args.length ? args[0] : '.' + fetchPackageMetadata(n, '.', function (er, d) { if (er) return cb(er) - var url = d.bugs && ((typeof d.bugs === "string") ? d.bugs : d.bugs.url) + var url = d.bugs && ((typeof d.bugs === 'string') ? d.bugs : d.bugs.url) if (!url) { - url = "https://www.npmjs.org/package/" + d.name + url = 'https://www.npmjs.org/package/' + d.name } - log.silly("bugs", "url", url) - opener(url, { command: npm.config.get("browser") }, cb) + log.silly('bugs', 'url', url) + opener(url, { command: npm.config.get('browser') }, cb) }) } diff --git a/lib/build.js b/lib/build.js index 4c284311d..b399a99e3 100644 --- a/lib/build.js +++ b/lib/build.js @@ -7,59 +7,70 @@ // This runs AFTER install or link are completed. -var npm = require("./npm.js") - , log = require("npmlog") - , chain = require("slide").chain - , fs = require("graceful-fs") - , path = require("path") - , lifecycle = require("./utils/lifecycle.js") - , readJson = require("read-package-json") - , link = require("./utils/link.js") - , linkIfExists = link.ifExists - , cmdShim = require("cmd-shim") - , cmdShimIfExists = cmdShim.ifExists - , asyncMap = require("slide").asyncMap - , ini = require("ini") - , writeFile = require("write-file-atomic") +var npm = require('./npm.js') +var log = require('npmlog') +var chain = require('slide').chain +var fs = require('graceful-fs') +var path = require('path') +var lifecycle = require('./utils/lifecycle.js') +var readJson = require('read-package-json') +var link = require('./utils/link.js') +var linkIfExists = link.ifExists +var cmdShim = require('cmd-shim') +var cmdShimIfExists = cmdShim.ifExists +var asyncMap = require('slide').asyncMap +var ini = require('ini') +var writeFile = require('write-file-atomic') module.exports = build -build.usage = "npm build [<folder>]" +build.usage = 'npm build [<folder>]' build._didBuild = {} build._noLC = {} function build (args, global, didPre, didRB, cb) { - if (typeof cb !== "function") cb = didRB, didRB = false - if (typeof cb !== "function") cb = didPre, didPre = false - if (typeof cb !== "function") { - cb = global, global = npm.config.get("global") + if (typeof cb !== 'function') { + cb = didRB + didRB = false } + if (typeof cb !== 'function') { + cb = didPre + didPre = false + } + if (typeof cb !== 'function') { + cb = global + global = npm.config.get('global') + } + // it'd be nice to asyncMap these, but actually, doing them // in parallel generally munges up the output from node-waf var builder = build_(global, didPre, didRB) - chain(args.map(function (arg) { return function (cb) { - builder(arg, cb) - }}), cb) + chain(args.map(function (arg) { + return function (cb) { + builder(arg, cb) + } + }), cb) } -function build_ (global, didPre, didRB) { return function (folder, cb) { - folder = path.resolve(folder) - if (build._didBuild[folder]) log.info("build", "already built", folder) - build._didBuild[folder] = true - log.info("build", folder) - readJson(path.resolve(folder, "package.json"), function (er, pkg) { - if (er) return cb(er) - chain - ( [ !didPre && [lifecycle, pkg, "preinstall", folder] - , [linkStuff, pkg, folder, global, didRB] - , [writeBuiltinConf, pkg, folder] - , didPre !== build._noLC && [lifecycle, pkg, "install", folder] - , didPre !== build._noLC && [lifecycle, pkg, "postinstall", folder] - , didPre !== build._noLC - && npm.config.get("npat") - && [lifecycle, pkg, "test", folder] ] - , cb ) - }) -}} +function build_ (global, didPre, didRB) { + return function (folder, cb) { + folder = path.resolve(folder) + if (build._didBuild[folder]) log.info('build', 'already built', folder) + build._didBuild[folder] = true + log.info('build', folder) + readJson(path.resolve(folder, 'package.json'), function (er, pkg) { + if (er) return cb(er) + chain([ + !didPre && [lifecycle, pkg, 'preinstall', folder], + [linkStuff, pkg, folder, global, didRB], + [writeBuiltinConf, pkg, folder], + didPre !== build._noLC && [lifecycle, pkg, 'install', folder], + didPre !== build._noLC && [lifecycle, pkg, 'postinstall', folder], + didPre !== build._noLC && npm.config.get('npat') && [lifecycle, pkg, 'test', folder] + ], + cb) + }) + } +} var writeBuiltinConf = build.writeBuiltinConf = function (pkg, folder, cb) { // the builtin config is "sticky". Any time npm installs @@ -67,25 +78,25 @@ var writeBuiltinConf = build.writeBuiltinConf = function (pkg, folder, cb) { var parent = path.dirname(folder) var dir = npm.globalDir - if (pkg.name !== "npm" || - !npm.config.get("global") || + if (pkg.name !== 'npm' || + !npm.config.get('global') || !npm.config.usingBuiltin || dir !== parent) { return cb() } var data = ini.stringify(npm.config.sources.builtin.data) - writeFile(path.resolve(folder, "npmrc"), data, cb) + writeFile(path.resolve(folder, 'npmrc'), data, cb) } var linkStuff = build.linkStuff = function (pkg, folder, global, didRB, cb) { // allow to opt out of linking binaries. - if (npm.config.get("bin-links") === false) return cb() + if (npm.config.get('bin-links') === false) return cb() // if it's global, and folder is in {prefix}/node_modules, // then bins are in {prefix}/bin // otherwise, then bins are in folder/../.bin - var parent = pkg.name && pkg.name[0] === "@" ? path.dirname(path.dirname(folder)) : path.dirname(folder) + var parent = pkg.name && pkg.name[0] === '@' ? path.dirname(path.dirname(folder)) : path.dirname(folder) var gnm = global && npm.globalDir var gtop = parent === gnm @@ -108,16 +119,16 @@ var linkStuff = build.linkStuff = function (pkg, folder, global, didRB, cb) { }) } -function shouldWarn(pkg, folder, global, cb) { +function shouldWarn (pkg, folder, global, cb) { var parent = path.dirname(folder) - , top = parent === npm.dir - , cwd = npm.localPrefix + var top = parent === npm.dir + var cwd = npm.localPrefix - readJson(path.resolve(cwd, "package.json"), function(er, topPkg) { + readJson(path.resolve(cwd, 'package.json'), function (er, topPkg) { if (er) return cb(er) var linkedPkg = path.basename(cwd) - , currentPkg = path.basename(folder) + var currentPkg = path.basename(folder) // current searched package is the linked package on first call if (linkedPkg !== currentPkg) { @@ -128,7 +139,7 @@ function shouldWarn(pkg, folder, global, cb) { if (Object.keys(topPkg.dependencies).indexOf(currentPkg) === -1) { if (top && pkg.preferGlobal && !global) { - log.warn("prefer global", pkg._id + " should be installed with -g") + log.warn('prefer global', pkg._id + ' should be installed with -g') } } } @@ -138,78 +149,81 @@ function shouldWarn(pkg, folder, global, cb) { } function rebuildBundles (pkg, folder, parent, gtop, cb) { - if (!npm.config.get("rebuild-bundle")) return cb() + if (!npm.config.get('rebuild-bundle')) return cb() var deps = Object.keys(pkg.dependencies || {}) .concat(Object.keys(pkg.devDependencies || {})) - , bundles = pkg.bundleDependencies || pkg.bundledDependencies || [] + var bundles = pkg.bundleDependencies || pkg.bundledDependencies || [] - fs.readdir(path.resolve(folder, "node_modules"), function (er, files) { + fs.readdir(path.resolve(folder, 'node_modules'), function (er, files) { // error means no bundles if (er) return cb() - log.verbose("rebuildBundles", files) + log.verbose('rebuildBundles', files) // don't asyncMap these, because otherwise build script output // gets interleaved and is impossible to read chain(files.filter(function (file) { // rebuild if: // not a .folder, like .bin or .hooks - return !file.match(/^[\._-]/) + return !file.match(/^[\._-]/) && // not some old 0.x style bundle - && file.indexOf("@") === -1 + file.indexOf('@') === -1 && // either not a dep, or explicitly bundled - && (deps.indexOf(file) === -1 || bundles.indexOf(file) !== -1) + (deps.indexOf(file) === -1 || bundles.indexOf(file) !== -1) }).map(function (file) { - file = path.resolve(folder, "node_modules", file) + file = path.resolve(folder, 'node_modules', file) return function (cb) { if (build._didBuild[file]) return cb() - log.verbose("rebuild bundle", file) + log.verbose('rebuild bundle', file) // if file is not a package dir, then don't do it. - fs.lstat(path.resolve(file, "package.json"), function (er) { + fs.lstat(path.resolve(file, 'package.json'), function (er) { if (er) return cb() build_(false)(file, cb) }) - }}), cb) + } + }), cb) }) } function linkBins (pkg, folder, parent, gtop, cb) { - if (!pkg.bin || !gtop && path.basename(parent) !== "node_modules") { + if (!pkg.bin || !gtop && path.basename(parent) !== 'node_modules') { return cb() } var binRoot = gtop ? npm.globalBin - : path.resolve(parent, ".bin") - log.verbose("link bins", [pkg.bin, binRoot, gtop]) + : path.resolve(parent, '.bin') + log.verbose('link bins', [pkg.bin, binRoot, gtop]) asyncMap(Object.keys(pkg.bin), function (b, cb) { - linkBin( path.resolve(folder, pkg.bin[b]) - , path.resolve(binRoot, b) - , gtop && folder - , function (er) { - if (er) return cb(er) - // bins should always be executable. - // XXX skip chmod on windows? - var src = path.resolve(folder, pkg.bin[b]) - fs.chmod(src, npm.modes.exec, function (er) { - if (er && er.code === "ENOENT" && npm.config.get("ignore-scripts")) { - return cb() - } - if (er || !gtop) return cb(er) - var dest = path.resolve(binRoot, b) - , out = npm.config.get("parseable") - ? dest + "::" + src + ":BINFILE" - : dest + " -> " + src - log.clearProgress() - console.log(out) - log.showProgress() - cb() - }) - }) + linkBin( + path.resolve(folder, pkg.bin[b]), + path.resolve(binRoot, b), + gtop && folder, + function (er) { + if (er) return cb(er) + // bins should always be executable. + // XXX skip chmod on windows? + var src = path.resolve(folder, pkg.bin[b]) + fs.chmod(src, npm.modes.exec, function (er) { + if (er && er.code === 'ENOENT' && npm.config.get('ignore-scripts')) { + return cb() + } + if (er || !gtop) return cb(er) + var dest = path.resolve(binRoot, b) + var out = npm.config.get('parseable') + ? dest + '::' + src + ':BINFILE' + : dest + ' -> ' + src + log.clearProgress() + console.log(out) + log.showProgress() + cb() + }) + } + ) }, cb) } function linkBin (from, to, gently, cb) { - if (process.platform !== "win32") { + if (process.platform !== 'win32') { return linkIfExists(from, to, gently, cb) } else { return cmdShimIfExists(from, to, cb) @@ -217,10 +231,10 @@ function linkBin (from, to, gently, cb) { } function linkMans (pkg, folder, parent, gtop, cb) { - if (!pkg.man || !gtop || process.platform === "win32") return cb() + if (!pkg.man || !gtop || process.platform === 'win32') return cb() - var manRoot = path.resolve(npm.config.get("prefix"), "share", "man") - log.verbose("linkMans", "man files are", pkg.man, "in", manRoot) + var manRoot = path.resolve(npm.config.get('prefix'), 'share', 'man') + log.verbose('linkMans', 'man files are', pkg.man, 'in', manRoot) // make sure that the mans are unique. // otherwise, if there are dupes, it'll fail with EEXIST @@ -233,14 +247,14 @@ function linkMans (pkg, folder, parent, gtop, cb) { }) asyncMap(pkg.man, function (man, cb) { - if (typeof man !== "string") return cb() - log.silly("linkMans", "preparing to link", man) + if (typeof man !== 'string') return cb() + log.silly('linkMans', 'preparing to link', man) var parseMan = man.match(/(.*\.([0-9]+)(\.gz)?)$/) if (!parseMan) { return cb(new Error( - man+" is not a valid name for a man file. " + - "Man files must end with a number, " + - "and optionally a .gz suffix if they are compressed." + man + ' is not a valid name for a man file. ' + + 'Man files must end with a number, ' + + 'and optionally a .gz suffix if they are compressed.' )) } @@ -248,7 +262,7 @@ function linkMans (pkg, folder, parent, gtop, cb) { var sxn = parseMan[2] var bn = path.basename(stem) var manSrc = path.resolve(folder, man) - var manDest = path.join(manRoot, "man" + sxn, bn) + var manDest = path.join(manRoot, 'man' + sxn, bn) linkIfExists(manSrc, manDest, gtop && folder, cb) }, cb) diff --git a/lib/cache.js b/lib/cache.js index 05d6ca595..02b17498b 100644 --- a/lib/cache.js +++ b/lib/cache.js @@ -60,54 +60,54 @@ cache.unpack = unpack cache.clean = clean cache.read = read -var npm = require("./npm.js") - , fs = require("graceful-fs") - , writeFileAtomic = require("write-file-atomic") - , assert = require("assert") - , rm = require("./utils/gently-rm.js") - , readJson = require("read-package-json") - , log = require("npmlog") - , path = require("path") - , asyncMap = require("slide").asyncMap - , tar = require("./utils/tar.js") - , fileCompletion = require("./utils/completion/file-completion.js") - , deprCheck = require("./utils/depr-check.js") - , addNamed = require("./cache/add-named.js") - , addLocal = require("./cache/add-local.js") - , addRemoteTarball = require("./cache/add-remote-tarball.js") - , addRemoteGit = require("./cache/add-remote-git.js") - , inflight = require("inflight") - , realizePackageSpecifier = require("realize-package-specifier") - , npa = require("npm-package-arg") - , getStat = require("./cache/get-stat.js") - , cachedPackageRoot = require("./cache/cached-package-root.js") - , mapToRegistry = require("./utils/map-to-registry.js") - -cache.usage = "npm cache add <tarball file>" - + "\nnpm cache add <folder>" - + "\nnpm cache add <tarball url>" - + "\nnpm cache add <git url>" - + "\nnpm cache add <name>@<version>" - + "\nnpm cache ls [<path>]" - + "\nnpm cache clean [<pkg>[@<version>]]" +var npm = require('./npm.js') +var fs = require('graceful-fs') +var writeFileAtomic = require('write-file-atomic') +var assert = require('assert') +var rm = require('./utils/gently-rm.js') +var readJson = require('read-package-json') +var log = require('npmlog') +var path = require('path') +var asyncMap = require('slide').asyncMap +var tar = require('./utils/tar.js') +var fileCompletion = require('./utils/completion/file-completion.js') +var deprCheck = require('./utils/depr-check.js') +var addNamed = require('./cache/add-named.js') +var addLocal = require('./cache/add-local.js') +var addRemoteTarball = require('./cache/add-remote-tarball.js') +var addRemoteGit = require('./cache/add-remote-git.js') +var inflight = require('inflight') +var realizePackageSpecifier = require('realize-package-specifier') +var npa = require('npm-package-arg') +var getStat = require('./cache/get-stat.js') +var cachedPackageRoot = require('./cache/cached-package-root.js') +var mapToRegistry = require('./utils/map-to-registry.js') + +cache.usage = 'npm cache add <tarball file>' + + '\nnpm cache add <folder>' + + '\nnpm cache add <tarball url>' + + '\nnpm cache add <git url>' + + '\nnpm cache add <name>@<version>' + + '\nnpm cache ls [<path>]' + + '\nnpm cache clean [<pkg>[@<version>]]' cache.completion = function (opts, cb) { var argv = opts.conf.argv.remain if (argv.length === 2) { - return cb(null, ["add", "ls", "clean"]) + return cb(null, ['add', 'ls', 'clean']) } switch (argv[2]) { - case "clean": - case "ls": + case 'clean': + case 'ls': // cache and ls are easy, because the completion is // what ls_ returns anyway. // just get the partial words, minus the last path part - var p = path.dirname(opts.partialWords.slice(3).join("/")) - if (p === ".") p = "" + var p = path.dirname(opts.partialWords.slice(3).join('/')) + if (p === '.') p = '' return ls_(p, 2, cb) - case "add": + case 'add': // Same semantics as install and publish. return npm.commands.install.completion(opts, cb) } @@ -116,10 +116,10 @@ cache.completion = function (opts, cb) { function cache (args, cb) { var cmd = args.shift() switch (cmd) { - case "rm": case "clear": case "clean": return clean(args, cb) - case "list": case "sl": case "ls": return ls(args, cb) - case "add": return add(args, npm.prefix, cb) - default: return cb("Usage: "+cache.usage) + case 'rm': case 'clear': case 'clean': return clean(args, cb) + case 'list': case 'sl': case 'ls': return ls(args, cb) + case 'add': return add(args, npm.prefix, cb) + default: return cb('Usage: ' + cache.usage) } } @@ -127,30 +127,30 @@ function cache (args, cb) { // just do a readJson and return. // if they're not, then fetch them from the registry. function read (name, ver, forceBypass, cb) { - assert(typeof name === "string", "must include name of module to install") - assert(typeof cb === "function", "must include callback") + assert(typeof name === 'string', 'must include name of module to install') + assert(typeof cb === 'function', 'must include callback') if (forceBypass === undefined || forceBypass === null) forceBypass = true - var root = cachedPackageRoot({name : name, version : ver}) + var root = cachedPackageRoot({name: name, version: ver}) function c (er, data) { - if (er) log.verbose("cache", "addNamed error for", name+"@"+ver, er) + if (er) log.verbose('cache', 'addNamed error for', name + '@' + ver, er) if (data) deprCheck(data) return cb(er, data) } - if (forceBypass && npm.config.get("force")) { - log.verbose("using force", "skipping cache") + if (forceBypass && npm.config.get('force')) { + log.verbose('using force', 'skipping cache') return addNamed(name, ver, null, c) } - readJson(path.join(root, "package", "package.json"), function (er, data) { - if (er && er.code !== "ENOENT" && er.code !== "ENOTDIR") return cb(er) + readJson(path.join(root, 'package', 'package.json'), function (er, data) { + if (er && er.code !== 'ENOENT' && er.code !== 'ENOTDIR') return cb(er) if (data) { - if (!data.name) return cb(new Error("No name provided")) - if (!data.version) return cb(new Error("No version provided")) + if (!data.name) return cb(new Error('No name provided')) + if (!data.version) return cb(new Error('No version provided')) } if (er) return addNamed(name, ver, null, c) @@ -159,33 +159,33 @@ function read (name, ver, forceBypass, cb) { } function normalize (args) { - var normalized = "" + var normalized = '' if (args.length > 0) { var a = npa(args[0]) if (a.name) normalized = a.name - if (a.rawSpec) normalized = [normalized, a.rawSpec].join("/") - if (args.length > 1) normalized = [normalized].concat(args.slice(1)).join("/") + if (a.rawSpec) normalized = [normalized, a.rawSpec].join('/') + if (args.length > 1) normalized = [normalized].concat(args.slice(1)).join('/') } - if (normalized.substr(-1) === "/") { + if (normalized.substr(-1) === '/') { normalized = normalized.substr(0, normalized.length - 1) } normalized = path.normalize(normalized) - log.silly("ls", "normalized", normalized) + log.silly('ls', 'normalized', normalized) return normalized } // npm cache ls [<path>] function ls (args, cb) { - var prefix = npm.config.get("cache") + var prefix = npm.config.get('cache') if (prefix.indexOf(process.env.HOME) === 0) { - prefix = "~" + prefix.substr(process.env.HOME.length) + prefix = '~' + prefix.substr(process.env.HOME.length) } - ls_(normalize(args), npm.config.get("depth"), function (er, files) { + ls_(normalize(args), npm.config.get('depth'), function (er, files) { console.log(files.map(function (f) { return path.join(prefix, f) - }).join("\n").trim()) + }).join('\n').trim()) cb(er, files) }) } @@ -197,7 +197,7 @@ function ls_ (req, depth, cb) { // npm cache clean [<path>] function clean (args, cb) { - assert(typeof cb === "function", "must include callback") + assert(typeof cb === 'function', 'must include callback') if (!args) args = [] @@ -205,15 +205,17 @@ function clean (args, cb) { if (f === npm.cache) { fs.readdir(npm.cache, function (er, files) { if (er) return cb() - asyncMap( files.filter(function (f) { - return npm.config.get("force") || f !== "-" - }).map(function (f) { - return path.join(npm.cache, f) - }) - , rm, cb ) + asyncMap( + files.filter(function (f) { + return npm.config.get('force') || f !== '-' + }).map(function (f) { + return path.join(npm.cache, f) + }), + rm, + cb + ) }) - } - else { + } else { rm(f, cb) } } @@ -223,8 +225,8 @@ function clean (args, cb) { // npm cache add <tarball> // npm cache add <folder> cache.add = function (pkg, ver, where, scrub, cb) { - assert(typeof pkg === "string", "must include name of package to install") - assert(typeof cb === "function", "must include callback") + assert(typeof pkg === 'string', 'must include name of package to install') + assert(typeof cb === 'function', 'must include callback') if (scrub) { return clean([], function (er) { @@ -235,38 +237,37 @@ cache.add = function (pkg, ver, where, scrub, cb) { return add([pkg, ver], where, cb) } - var adding = 0 function add (args, where, cb) { // this is hot code. almost everything passes through here. // the args can be any of: - // ["url"] - // ["pkg", "version"] - // ["pkg@version"] - // ["pkg", "url"] + // ['url'] + // ['pkg', 'version'] + // ['pkg@version'] + // ['pkg', 'url'] // This is tricky, because urls can contain @ // Also, in some cases we get [name, null] rather // that just a single argument. - var usage = "Usage:\n" - + " npm cache add <tarball-url>\n" - + " npm cache add <pkg>@<ver>\n" - + " npm cache add <tarball>\n" - + " npm cache add <folder>\n" - , spec + var usage = 'Usage:\n' + + ' npm cache add <tarball-url>\n' + + ' npm cache add <pkg>@<ver>\n' + + ' npm cache add <tarball>\n' + + ' npm cache add <folder>\n' + var spec - log.silly("cache add", "args", args) + log.silly('cache add', 'args', args) if (args[1] === undefined) args[1] = null // at this point the args length must ==2 if (args[1] !== null) { - spec = args[0]+"@"+args[1] + spec = args[0] + '@' + args[1] } else if (args.length === 2) { spec = args[0] } - log.verbose("cache add", "spec", spec) + log.verbose('cache add', 'spec', spec) if (!spec) return cb(usage) @@ -276,23 +277,23 @@ function add (args, where, cb) { realizePackageSpecifier(spec, where, function (err, p) { if (err) return cb(err) - log.silly("cache add", "parsed spec", p) + log.silly('cache add', 'parsed spec', p) switch (p.type) { - case "local": - case "directory": + case 'local': + case 'directory': addLocal(p, null, cb) break - case "remote": + case 'remote': // get auth, if possible mapToRegistry(spec, npm.config, function (err, uri, auth) { if (err) return cb(err) - addRemoteTarball(p.spec, {name : p.name}, null, auth, cb) + addRemoteTarball(p.spec, { name: p.name }, null, auth, cb) }) break - case "git": - case "hosted": + case 'git': + case 'hosted': addRemoteGit(p.rawSpec, cb) break default: @@ -304,46 +305,62 @@ function add (args, where, cb) { } function unpack (pkg, ver, unpackTarget, dMode, fMode, uid, gid, cb) { - if (typeof cb !== "function") cb = gid, gid = null - if (typeof cb !== "function") cb = uid, uid = null - if (typeof cb !== "function") cb = fMode, fMode = null - if (typeof cb !== "function") cb = dMode, dMode = null + if (typeof cb !== 'function') { + cb = gid + gid = null + } + if (typeof cb !== 'function') { + cb = uid + uid = null + } + if (typeof cb !== 'function') { + cb = fMode + fMode = null + } + if (typeof cb !== 'function') { + cb = dMode + dMode = null + } read(pkg, ver, false, function (er) { if (er) { - log.error("unpack", "Could not read data for %s", pkg + "@" + ver) + log.error('unpack', 'Could not read data for %s', pkg + '@' + ver) return cb(er) } npm.commands.unbuild([unpackTarget], true, function (er) { if (er) return cb(er) - tar.unpack( path.join(cachedPackageRoot({name : pkg, version : ver}), "package.tgz") - , unpackTarget - , dMode, fMode - , uid, gid - , cb ) + tar.unpack( + path.join(cachedPackageRoot({ name: pkg, version: ver }), 'package.tgz'), + unpackTarget, + dMode, fMode, + uid, gid, + cb + ) }) }) } -function afterAdd (cb) { return function (er, data) { - adding-- +function afterAdd (cb) { + return function (er, data) { + adding-- - if (er || !data || !data.name || !data.version) return cb(er, data) - log.silly("cache", "afterAdd", data.name+"@"+data.version) + if (er || !data || !data.name || !data.version) return cb(er, data) + log.silly('cache', 'afterAdd', data.name + '@' + data.version) - // Save the resolved, shasum, etc. into the data so that the next - // time we load from this cached data, we have all the same info. - var pj = path.join(cachedPackageRoot(data), "package", "package.json") + // Save the resolved, shasum, etc. into the data so that the next + // time we load from this cached data, we have all the same info. + var pj = path.join(cachedPackageRoot(data), 'package', 'package.json') - var done = inflight(pj, cb) - if (!done) return log.verbose("afterAdd", pj, "already in flight; not writing") - log.verbose("afterAdd", pj, "not in flight; writing") + var done = inflight(pj, cb) + if (!done) return log.verbose('afterAdd', pj, 'already in flight; not writing') + log.verbose('afterAdd', pj, 'not in flight; writing') - getStat(function (er, cs) { - if (er) return done(er) - writeFileAtomic(pj, JSON.stringify(data), {chown : cs}, function (er) { - if (!er) log.verbose("afterAdd", pj, "written") - return done(er, data) + getStat(function (er, cs) { + if (er) return done(er) + writeFileAtomic(pj, JSON.stringify(data), { chown: cs }, function (er) { + if (!er) log.verbose('afterAdd', pj, 'written') + return done(er, data) + }) }) - }) -}} + } +} diff --git a/lib/cache/add-local-tarball.js b/lib/cache/add-local-tarball.js index 7628c1102..9f252b8ca 100644 --- a/lib/cache/add-local-tarball.js +++ b/lib/cache/add-local-tarball.js @@ -1,27 +1,27 @@ -var mkdir = require("mkdirp") - , assert = require("assert") - , fs = require("graceful-fs") - , writeFileAtomic = require("write-file-atomic") - , path = require("path") - , sha = require("sha") - , npm = require("../npm.js") - , log = require("npmlog") - , tar = require("../utils/tar.js") - , pathIsInside = require("path-is-inside") - , getCacheStat = require("./get-stat.js") - , cachedPackageRoot = require("./cached-package-root.js") - , chownr = require("chownr") - , inflight = require("inflight") - , once = require("once") - , writeStream = require("fs-write-stream-atomic") - , tempFilename = require("../utils/temp-filename.js") - , rimraf = require("rimraf") +var mkdir = require('mkdirp') +var assert = require('assert') +var fs = require('graceful-fs') +var writeFileAtomic = require('write-file-atomic') +var path = require('path') +var sha = require('sha') +var npm = require('../npm.js') +var log = require('npmlog') +var tar = require('../utils/tar.js') +var pathIsInside = require('path-is-inside') +var getCacheStat = require('./get-stat.js') +var cachedPackageRoot = require('./cached-package-root.js') +var chownr = require('chownr') +var inflight = require('inflight') +var once = require('once') +var writeStream = require('fs-write-stream-atomic') +var tempFilename = require('../utils/temp-filename.js') +var rimraf = require('rimraf') module.exports = addLocalTarball function addLocalTarball (p, pkgData, shasum, cb) { - assert(typeof p === "string", "must have path") - assert(typeof cb === "function", "must have callback") + assert(typeof p === 'string', 'must have path') + assert(typeof cb === 'function', 'must have callback') if (!pkgData) pkgData = {} @@ -29,16 +29,16 @@ function addLocalTarball (p, pkgData, shasum, cb) { if (!shasum) { return sha.get(p, function (er, shasum) { if (er) return cb(er) - log.silly("addLocalTarball", "shasum (computed)", shasum) + log.silly('addLocalTarball', 'shasum (computed)', shasum) addLocalTarball(p, pkgData, shasum, cb) }) } if (pathIsInside(p, npm.cache)) { - if (path.basename(p) !== "package.tgz") { - return cb(new Error("Not a valid cache tarball name: "+p)) + if (path.basename(p) !== 'package.tgz') { + return cb(new Error('Not a valid cache tarball name: ' + p)) } - log.verbose("addLocalTarball", "adding from inside cache", p) + log.verbose('addLocalTarball', 'adding from inside cache', p) return addPlacedTarball(p, pkgData, shasum, cb) } @@ -52,8 +52,8 @@ function addLocalTarball (p, pkgData, shasum, cb) { } function addPlacedTarball (p, pkgData, shasum, cb) { - assert(pkgData, "should have package data by now") - assert(typeof cb === "function", "cb function required") + assert(pkgData, 'should have package data by now') + assert(typeof cb === 'function', 'cb function required') getCacheStat(function (er, cs) { if (er) return cb(er) @@ -62,7 +62,7 @@ function addPlacedTarball (p, pkgData, shasum, cb) { } function addPlacedTarball_ (p, pkgData, uid, gid, resolvedSum, cb) { - var folder = path.join(cachedPackageRoot(pkgData), "package") + var folder = path.join(cachedPackageRoot(pkgData), 'package') // First, make sure we have the shasum, if we don't already. if (!resolvedSum) { @@ -75,7 +75,7 @@ function addPlacedTarball_ (p, pkgData, uid, gid, resolvedSum, cb) { mkdir(folder, function (er) { if (er) return cb(er) - var pj = path.join(folder, "package.json") + var pj = path.join(folder, 'package.json') var json = JSON.stringify(pkgData, null, 2) writeFileAtomic(pj, json, function (er) { cb(er, pkgData) @@ -84,19 +84,19 @@ function addPlacedTarball_ (p, pkgData, uid, gid, resolvedSum, cb) { } function addTmpTarball (tgz, pkgData, shasum, cb) { - assert(typeof cb === "function", "must have callback function") - assert(shasum, "must have shasum by now") + assert(typeof cb === 'function', 'must have callback function') + assert(shasum, 'must have shasum by now') - cb = inflight("addTmpTarball:" + tgz, cb) - if (!cb) return log.verbose("addTmpTarball", tgz, "already in flight; not adding") - log.verbose("addTmpTarball", tgz, "not in flight; adding") + cb = inflight('addTmpTarball:' + tgz, cb) + if (!cb) return log.verbose('addTmpTarball', tgz, 'already in flight; not adding') + log.verbose('addTmpTarball', tgz, 'not in flight; adding') // we already have the package info, so just move into place if (pkgData && pkgData.name && pkgData.version) { log.verbose( - "addTmpTarball", - "already have metadata; skipping unpack for", - pkgData.name + "@" + pkgData.version + 'addTmpTarball', + 'already have metadata; skipping unpack for', + pkgData.name + '@' + pkgData.version ) return addTmpTarball_(tgz, pkgData, shasum, cb) } @@ -108,31 +108,29 @@ function addTmpTarball (tgz, pkgData, shasum, cb) { // NOTE: we might not have any clue what we think it is, for example if the // user just did `npm install ./foo.tgz` - var target = tempFilename("unpack") + var target = tempFilename('unpack') getCacheStat(function (er, cs) { if (er) return cb(er) - log.verbose("addTmpTarball", "validating metadata from", tgz) + log.verbose('addTmpTarball', 'validating metadata from', tgz) tar.unpack(tgz, target, null, null, cs.uid, cs.gid, function (unpackEr, data) { // cleanup the extracted package and move on with the metadata rimraf(target, function () { if (unpackEr) return cb(unpackEr) // check that this is what we expected. if (!data.name) { - return cb(new Error("No name provided")) - } - else if (pkgData.name && data.name !== pkgData.name) { - return cb(new Error("Invalid Package: expected " + pkgData.name + - " but found " + data.name)) + return cb(new Error('No name provided')) + } else if (pkgData.name && data.name !== pkgData.name) { + return cb(new Error('Invalid Package: expected ' + pkgData.name + + ' but found ' + data.name)) } if (!data.version) { - return cb(new Error("No version provided")) - } - else if (pkgData.version && data.version !== pkgData.version) { - return cb(new Error("Invalid Package: expected " + - pkgData.name + "@" + pkgData.version + - " but found " + data.name + "@" + data.version)) + return cb(new Error('No version provided')) + } else if (pkgData.version && data.version !== pkgData.version) { + return cb(new Error('Invalid Package: expected ' + + pkgData.name + '@' + pkgData.version + + ' but found ' + data.name + '@' + data.version)) } addTmpTarball_(tgz, data, shasum, cb) @@ -142,15 +140,15 @@ function addTmpTarball (tgz, pkgData, shasum, cb) { } function addTmpTarball_ (tgz, data, shasum, cb) { - assert(typeof cb === "function", "must have callback function") + assert(typeof cb === 'function', 'must have callback function') cb = once(cb) - assert(data.name, "should have package name by now") - assert(data.version, "should have package version by now") + assert(data.name, 'should have package name by now') + assert(data.version, 'should have package version by now') var root = cachedPackageRoot(data) - var pkg = path.resolve(root, "package") - var target = path.resolve(root, "package.tgz") + var pkg = path.resolve(root, 'package') + var target = path.resolve(root, 'package.tgz') getCacheStat(function (er, cs) { if (er) return cb(er) mkdir(pkg, function (er, created) { @@ -166,12 +164,12 @@ function addTmpTarball_ (tgz, data, shasum, cb) { var read = fs.createReadStream(tgz) var write = writeStream(target, { mode: npm.modes.file }) var fin = cs.uid && cs.gid ? chown : done - read.on("error", cb).pipe(write).on("error", cb).on("close", fin) + read.on('error', cb).pipe(write).on('error', cb).on('close', fin) }) }) - function done() { + function done () { data._shasum = data._shasum || shasum cb(null, data) } diff --git a/lib/cache/add-local.js b/lib/cache/add-local.js index dbe55ddc2..075ca5fc6 100644 --- a/lib/cache/add-local.js +++ b/lib/cache/add-local.js @@ -1,46 +1,45 @@ -var assert = require("assert") - , path = require("path") - , mkdir = require("mkdirp") - , chownr = require("chownr") - , pathIsInside = require("path-is-inside") - , readJson = require("read-package-json") - , log = require("npmlog") - , npm = require("../npm.js") - , tar = require("../utils/tar.js") - , deprCheck = require("../utils/depr-check.js") - , getCacheStat = require("./get-stat.js") - , cachedPackageRoot = require("./cached-package-root.js") - , addLocalTarball = require("./add-local-tarball.js") - , sha = require("sha") - , inflight = require("inflight") - , lifecycle = require("../utils/lifecycle.js") - , iferr = require("iferr") +var assert = require('assert') +var path = require('path') +var mkdir = require('mkdirp') +var chownr = require('chownr') +var pathIsInside = require('path-is-inside') +var readJson = require('read-package-json') +var log = require('npmlog') +var npm = require('../npm.js') +var tar = require('../utils/tar.js') +var deprCheck = require('../utils/depr-check.js') +var getCacheStat = require('./get-stat.js') +var cachedPackageRoot = require('./cached-package-root.js') +var addLocalTarball = require('./add-local-tarball.js') +var sha = require('sha') +var inflight = require('inflight') +var lifecycle = require('../utils/lifecycle.js') +var iferr = require('iferr') module.exports = addLocal function addLocal (p, pkgData, cb_) { - assert(typeof p === "object", "must have spec info") - assert(typeof cb === "function", "must have callback") + assert(typeof p === 'object', 'must have spec info') + assert(typeof cb === 'function', 'must have callback') pkgData = pkgData || {} function cb (er, data) { if (er) { - log.error("addLocal", "Could not install %s", p.spec) + log.error('addLocal', 'Could not install %s', p.spec) return cb_(er) } if (data && !data._fromHosted) { - data._from = path.relative(npm.prefix, p.spec) || "." + data._from = path.relative(npm.prefix, p.spec) || '.' var resolved = path.relative(npm.prefix, p.spec) - if (resolved) data._resolved = "file:"+resolved + if (resolved) data._resolved = 'file:' + resolved } return cb_(er, data) } - if (p.type === "directory") { + if (p.type === 'directory') { addLocalDirectory(p.spec, pkgData, null, cb) - } - else { + } else { addLocalTarball(p.spec, pkgData, null, cb) } } @@ -48,33 +47,34 @@ function addLocal (p, pkgData, cb_) { // At this point, if shasum is set, it's something that we've already // read and checked. Just stashing it in the data at this point. function addLocalDirectory (p, pkgData, shasum, cb) { - assert(pkgData, "must pass package data") - assert(typeof cb === "function", "must have callback") + assert(pkgData, 'must pass package data') + assert(typeof cb === 'function', 'must have callback') // if it's a folder, then read the package.json, // tar it to the proper place, and add the cache tar - if (pathIsInside(p, npm.cache)) return cb(new Error( - "Adding a cache directory to the cache will make the world implode.")) + if (pathIsInside(p, npm.cache)) { + return cb(new Error( + 'Adding a cache directory to the cache will make the world implode.' + )) + } - readJson(path.join(p, "package.json"), false, function (er, data) { + readJson(path.join(p, 'package.json'), false, function (er, data) { if (er) return cb(er) if (!data.name) { - return cb(new Error("No name provided in package.json")) - } - else if (pkgData.name && pkgData.name !== data.name) { + return cb(new Error('No name provided in package.json')) + } else if (pkgData.name && pkgData.name !== data.name) { return cb(new Error( - "Invalid package: expected " + pkgData.name + " but found " + data.name + 'Invalid package: expected ' + pkgData.name + ' but found ' + data.name )) } if (!data.version) { - return cb(new Error("No version provided in package.json")) - } - else if (pkgData.version && pkgData.version !== data.version) { + return cb(new Error('No version provided in package.json')) + } else if (pkgData.version && pkgData.version !== data.version) { return cb(new Error( - "Invalid package: expected " + pkgData.name + "@" + pkgData.version + - " but found " + data.name + "@" + data.version + 'Invalid package: expected ' + pkgData.name + '@' + pkgData.version + + ' but found ' + data.name + '@' + data.version )) } @@ -82,27 +82,26 @@ function addLocalDirectory (p, pkgData, shasum, cb) { // pack to {cache}/name/ver/package.tgz var root = cachedPackageRoot(data) - var tgz = path.resolve(root, "package.tgz") - var pj = path.resolve(root, "package/package.json") + var tgz = path.resolve(root, 'package.tgz') + var pj = path.resolve(root, 'package/package.json') var wrapped = inflight(tgz, next) - if (!wrapped) return log.verbose("addLocalDirectory", tgz, "already in flight; waiting") - log.verbose("addLocalDirectory", tgz, "not in flight; packing") + if (!wrapped) return log.verbose('addLocalDirectory', tgz, 'already in flight; waiting') + log.verbose('addLocalDirectory', tgz, 'not in flight; packing') getCacheStat(function (er, cs) { mkdir(path.dirname(pj), function (er, made) { if (er) return cb(er) var doPrePublish = !pathIsInside(p, npm.tmp) if (doPrePublish) { - lifecycle(data, "prepublish", p, iferr(cb, thenPack)) - } - else { + lifecycle(data, 'prepublish', p, iferr(cb, thenPack)) + } else { thenPack() } function thenPack () { tar.pack(tgz, p, data, function (er) { if (er) { - log.error("addLocalDirectory", "Could not pack", p, "to", tgz) + log.error('addLocalDirectory', 'Could not pack', p, 'to', tgz) return cb(er) } diff --git a/lib/cache/add-named.js b/lib/cache/add-named.js index b5eb2e06f..1acaf28fa 100644 --- a/lib/cache/add-named.js +++ b/lib/cache/add-named.js @@ -1,24 +1,23 @@ -var path = require("path") - , assert = require("assert") - , fs = require("graceful-fs") - , http = require("http") - , log = require("npmlog") - , semver = require("semver") - , readJson = require("read-package-json") - , url = require("url") - , npm = require("../npm.js") - , deprCheck = require("../utils/depr-check.js") - , inflight = require("inflight") - , addRemoteTarball = require("./add-remote-tarball.js") - , cachedPackageRoot = require("./cached-package-root.js") - , mapToRegistry = require("../utils/map-to-registry.js") - , pulseTillDone = require("../utils/pulse-till-done.js") - +var path = require('path') +var assert = require('assert') +var fs = require('graceful-fs') +var http = require('http') +var log = require('npmlog') +var semver = require('semver') +var readJson = require('read-package-json') +var url = require('url') +var npm = require('../npm.js') +var deprCheck = require('../utils/depr-check.js') +var inflight = require('inflight') +var addRemoteTarball = require('./add-remote-tarball.js') +var cachedPackageRoot = require('./cached-package-root.js') +var mapToRegistry = require('../utils/map-to-registry.js') +var pulseTillDone = require('../utils/pulse-till-done.js') module.exports = addNamed function getOnceFromRegistry (name, from, next, done) { - function fixName(err, data, json, resp) { + function fixName (err, data, json, resp) { // this is only necessary until npm/npm-registry-client#80 is fixed if (err && err.pkgid && err.pkgid !== name) { err.message = err.message.replace( @@ -33,21 +32,21 @@ function getOnceFromRegistry (name, from, next, done) { mapToRegistry(name, npm.config, function (er, uri, auth) { if (er) return done(er) - var key = "registry:" + uri + var key = 'registry:' + uri next = inflight(key, next) - if (!next) return log.verbose(from, key, "already in flight; waiting") - else log.verbose(from, key, "not in flight; fetching") + if (!next) return log.verbose(from, key, 'already in flight; waiting') + else log.verbose(from, key, 'not in flight; fetching') - npm.registry.get(uri, { auth : auth }, pulseTillDone("fetchRegistry", fixName)) + npm.registry.get(uri, { auth: auth }, pulseTillDone('fetchRegistry', fixName)) }) } function addNamed (name, version, data, cb_) { - assert(typeof name === "string", "must have module name") - assert(typeof cb_ === "function", "must have callback") + assert(typeof name === 'string', 'must have module name') + assert(typeof cb_ === 'function', 'must have callback') - var key = name + "@" + version - log.silly("addNamed", key) + var key = name + '@' + version + log.silly('addNamed', key) function cb (er, data) { if (data && !data._fromHosted) data._from = key @@ -67,29 +66,29 @@ function addNamed (name, version, data, cb_) { } function addNameTag (name, tag, data, cb) { - log.info("addNameTag", [name, tag]) + log.info('addNameTag', [name, tag]) var explicit = true if (!tag) { explicit = false - tag = npm.config.get("tag") + tag = npm.config.get('tag') } - getOnceFromRegistry(name, "addNameTag", next, cb) + getOnceFromRegistry(name, 'addNameTag', next, cb) function next (er, data, json, resp) { if (!er) er = errorResponse(name, resp) if (er) return cb(er) - log.silly("addNameTag", "next cb for", name, "with tag", tag) + log.silly('addNameTag', 'next cb for', name, 'with tag', tag) engineFilter(data) - if (data["dist-tags"] && data["dist-tags"][tag] - && data.versions[data["dist-tags"][tag]]) { - var ver = data["dist-tags"][tag] + if (data['dist-tags'] && data['dist-tags'][tag] && + data.versions[data['dist-tags'][tag]]) { + var ver = data['dist-tags'][tag] return addNamed(name, ver, data.versions[ver], cb) } if (!explicit && Object.keys(data.versions).length) { - return addNamed(name, "*", data, cb) + return addNamed(name, '*', data, cb) } er = installTargetsError(tag, data) @@ -99,17 +98,17 @@ function addNameTag (name, tag, data, cb) { function engineFilter (data) { var npmv = npm.version - , nodev = npm.config.get("node-version") - , strict = npm.config.get("engine-strict") + var nodev = npm.config.get('node-version') + var strict = npm.config.get('engine-strict') - if (!nodev || npm.config.get("force")) return data + if (!nodev || npm.config.get('force')) return data Object.keys(data.versions || {}).forEach(function (v) { var eng = data.versions[v].engines if (!eng) return if (!strict && !data.versions[v].engineStrict) return - if (eng.node && !semver.satisfies(nodev, eng.node, true) - || eng.npm && !semver.satisfies(npmv, eng.npm, true)) { + if (eng.node && !semver.satisfies(nodev, eng.node, true) || + eng.npm && !semver.satisfies(npmv, eng.npm, true)) { delete data.versions[v] } }) @@ -117,7 +116,7 @@ function engineFilter (data) { function addNameVersion (name, v, data, cb) { var ver = semver.valid(v, true) - if (!ver) return cb(new Error("Invalid version: "+v)) + if (!ver) return cb(new Error('Invalid version: ' + v)) var response @@ -126,7 +125,7 @@ function addNameVersion (name, v, data, cb) { return next() } - getOnceFromRegistry(name, "addNameVersion", setData, cb) + getOnceFromRegistry(name, 'addNameVersion', setData, cb) function setData (er, d, json, resp) { if (!er) { @@ -135,7 +134,7 @@ function addNameVersion (name, v, data, cb) { if (er) return cb(er) data = d && d.versions[ver] if (!data) { - er = new Error("version not found: "+name+"@"+ver) + er = new Error('version not found: ' + name + '@' + ver) er.package = name er.statusCode = 404 return cb(er) @@ -148,27 +147,30 @@ function addNameVersion (name, v, data, cb) { deprCheck(data) var dist = data.dist - if (!dist) return cb(new Error("No dist in "+data._id+" package")) + if (!dist) return cb(new Error('No dist in ' + data._id + ' package')) - if (!dist.tarball) return cb(new Error( - "No dist.tarball in " + data._id + " package")) + if (!dist.tarball) { + return cb(new Error( + 'No dist.tarball in ' + data._id + ' package' + )) + } - if ((response && response.statusCode !== 304) || npm.config.get("force")) { + if ((response && response.statusCode !== 304) || npm.config.get('force')) { return fetchit() } // we got cached data, so let's see if we have a tarball. - var pkgroot = cachedPackageRoot({name : name, version : ver}) - var pkgtgz = path.join(pkgroot, "package.tgz") - var pkgjson = path.join(pkgroot, "package", "package.json") + var pkgroot = cachedPackageRoot({ name: name, version: ver }) + var pkgtgz = path.join(pkgroot, 'package.tgz') + var pkgjson = path.join(pkgroot, 'package', 'package.json') fs.stat(pkgtgz, function (er) { if (!er) { readJson(pkgjson, function (er, data) { - if (er && er.code !== "ENOENT" && er.code !== "ENOTDIR") return cb(er) + if (er && er.code !== 'ENOENT' && er.code !== 'ENOTDIR') return cb(er) if (data) { - if (!data.name) return cb(new Error("No name provided")) - if (!data.version) return cb(new Error("No version provided")) + if (!data.name) return cb(new Error('No name provided')) + if (!data.version) return cb(new Error('No version provided')) // check the SHA of the package we have, to ensure it wasn't installed // from somewhere other than the registry (eg, a fork) @@ -200,8 +202,8 @@ function addNameVersion (name, v, data, cb) { // Only add non-shasum'ed packages if --forced. Only ancient things // would lack this for good reasons nowadays. - if (!dist.shasum && !npm.config.get("force")) { - return cb(new Error("package lacks shasum: " + data._id)) + if (!dist.shasum && !npm.config.get('force')) { + return cb(new Error('package lacks shasum: ' + data._id)) } addRemoteTarball(tb, data, dist.shasum, auth, cb) @@ -212,15 +214,17 @@ function addNameVersion (name, v, data, cb) { function addNameRange (name, range, data, cb) { range = semver.validRange(range, true) - if (range === null) return cb(new Error( - "Invalid version range: " + range - )) + if (range === null) { + return cb(new Error( + 'Invalid version range: ' + range + )) + } - log.silly("addNameRange", {name:name, range:range, hasData:!!data}) + log.silly('addNameRange', { name: name, range: range, hasData: !!data }) if (data) return next() - getOnceFromRegistry(name, "addNameRange", setData, cb) + getOnceFromRegistry(name, 'addNameRange', setData, cb) function setData (er, d, json, resp) { if (!er) { @@ -232,18 +236,20 @@ function addNameRange (name, range, data, cb) { } function next () { - log.silly( "addNameRange", "number 2" - , {name:name, range:range, hasData:!!data}) + log.silly( + 'addNameRange', + 'number 2', { name: name, range: range, hasData: !!data } + ) engineFilter(data) - log.silly("addNameRange", "versions" + log.silly('addNameRange', 'versions' , [data.name, Object.keys(data.versions || {})]) // if the tagged version satisfies, then use that. - var tagged = data["dist-tags"][npm.config.get("tag")] - if (tagged - && data.versions[tagged] - && semver.satisfies(tagged, range, true)) { + var tagged = data['dist-tags'][npm.config.get('tag')] + if (tagged && + data.versions[tagged] && + semver.satisfies(tagged, range, true)) { return addNamed(name, tagged, data.versions[tagged], cb) } @@ -261,20 +267,19 @@ function addNameRange (name, range, data, cb) { } function installTargetsError (requested, data) { - var targets = Object.keys(data["dist-tags"]).filter(function (f) { + var targets = Object.keys(data['dist-tags']).filter(function (f) { return (data.versions || {}).hasOwnProperty(f) }).concat(Object.keys(data.versions || {})) - requested = data.name + (requested ? "@'" + requested + "'" : "") + requested = data.name + (requested ? "@'" + requested + "'" : '') targets = targets.length - ? "Valid install targets:\n" + JSON.stringify(targets) + "\n" - : "No valid targets found.\n" - + "Perhaps not compatible with your version of node?" + ? 'Valid install targets:\n' + JSON.stringify(targets) + '\n' + : 'No valid targets found.\n' + + 'Perhaps not compatible with your version of node?' - var er = new Error( "No compatible version found: " - + requested + "\n" + targets) - er.code = "ETARGET" + var er = new Error('No compatible version found: ' + requested + '\n' + targets) + er.code = 'ETARGET' return er } @@ -283,7 +288,7 @@ function errorResponse (name, response) { if (response.statusCode >= 400) { er = new Error(http.STATUS_CODES[response.statusCode]) er.statusCode = response.statusCode - er.code = "E" + er.statusCode + er.code = 'E' + er.statusCode er.pkgid = name } return er diff --git a/lib/cache/add-remote-git.js b/lib/cache/add-remote-git.js index e3863c7f7..d34981b6f 100644 --- a/lib/cache/add-remote-git.js +++ b/lib/cache/add-remote-git.js @@ -118,7 +118,7 @@ function tryClone (from, combinedURL, silent, cb) { // ensure that similarly-named remotes don't collide var cachedRemote = uniqueFilename(remotes, combinedURL.replace(/[^a-zA-Z0-9]+/g, '-'), cloneURL) var repoID = path.relative(remotes, cachedRemote) - var cachedRemote = path.join(remotes, repoID) + cachedRemote = path.join(remotes, repoID) cb = inflight(repoID, cb) if (!cb) { diff --git a/lib/cache/add-remote-tarball.js b/lib/cache/add-remote-tarball.js index dd49b5f54..aaa768acb 100644 --- a/lib/cache/add-remote-tarball.js +++ b/lib/cache/add-remote-tarball.js @@ -1,22 +1,22 @@ -var mkdir = require("mkdirp") - , assert = require("assert") - , log = require("npmlog") - , path = require("path") - , sha = require("sha") - , retry = require("retry") - , createWriteStream = require("fs-write-stream-atomic") - , npm = require("../npm.js") - , inflight = require("inflight") - , addLocalTarball = require("./add-local-tarball.js") - , cacheFile = require("npm-cache-filename") - , rimraf = require("rimraf") - , pulseTillDone = require("../utils/pulse-till-done.js") +var mkdir = require('mkdirp') +var assert = require('assert') +var log = require('npmlog') +var path = require('path') +var sha = require('sha') +var retry = require('retry') +var createWriteStream = require('fs-write-stream-atomic') +var npm = require('../npm.js') +var inflight = require('inflight') +var addLocalTarball = require('./add-local-tarball.js') +var cacheFile = require('npm-cache-filename') +var rimraf = require('rimraf') +var pulseTillDone = require('../utils/pulse-till-done.js') module.exports = addRemoteTarball function addRemoteTarball (u, pkgData, shasum, auth, cb_) { - assert(typeof u === "string", "must have module URL") - assert(typeof cb_ === "function", "must have callback") + assert(typeof u === 'string', 'must have module URL') + assert(typeof cb_ === 'function', 'must have callback') function cb (er, data) { if (data) { @@ -28,8 +28,8 @@ function addRemoteTarball (u, pkgData, shasum, auth, cb_) { } cb_ = inflight(u, cb_) - if (!cb_) return log.verbose("addRemoteTarball", u, "already in flight; waiting") - log.verbose("addRemoteTarball", u, "not in flight; adding") + if (!cb_) return log.verbose('addRemoteTarball', u, 'already in flight; waiting') + log.verbose('addRemoteTarball', u, 'not in flight; adding') // XXX Fetch direct to cache location, store tarballs under // ${cache}/registry.npmjs.org/pkg/-/pkg-1.2.3.tgz @@ -46,7 +46,7 @@ function addRemoteTarball (u, pkgData, shasum, auth, cb_) { }) } - log.verbose("addRemoteTarball", [u, shasum]) + log.verbose('addRemoteTarball', [u, shasum]) mkdir(path.dirname(tmp), function (er) { if (er) return cb(er) addRemoteTarball_(u, tmp, shasum, auth, next) @@ -57,21 +57,24 @@ function addRemoteTarball_ (u, tmp, shasum, auth, cb) { // Tuned to spread 3 attempts over about a minute. // See formula at <https://github.com/tim-kos/node-retry>. var operation = retry.operation({ - retries: npm.config.get("fetch-retries") - , factor: npm.config.get("fetch-retry-factor") - , minTimeout: npm.config.get("fetch-retry-mintimeout") - , maxTimeout: npm.config.get("fetch-retry-maxtimeout") + retries: npm.config.get('fetch-retries'), + factor: npm.config.get('fetch-retry-factor'), + minTimeout: npm.config.get('fetch-retry-mintimeout'), + maxTimeout: npm.config.get('fetch-retry-maxtimeout') }) operation.attempt(function (currentAttempt) { - log.info("retry", "fetch attempt " + currentAttempt - + " at " + (new Date()).toLocaleTimeString()) + log.info( + 'retry', + 'fetch attempt', currentAttempt, + 'at', (new Date()).toLocaleTimeString() + ) fetchAndShaCheck(u, tmp, shasum, auth, function (er, response, shasum) { // Only retry on 408, 5xx or no `response`. var sc = response && response.statusCode var statusRetry = !sc || (sc === 408 || sc >= 500) if (er && statusRetry && operation.retry(er)) { - log.warn("retry", "will retry, error on last attempt: " + er) + log.warn('retry', 'will retry, error on last attempt: ' + er) return } cb(er, response, shasum) @@ -80,35 +83,35 @@ function addRemoteTarball_ (u, tmp, shasum, auth, cb) { } function fetchAndShaCheck (u, tmp, shasum, auth, cb) { - cb = pulseTillDone("fetchTarball", cb) - npm.registry.fetch(u, { auth : auth }, function (er, response) { + cb = pulseTillDone('fetchTarball', cb) + npm.registry.fetch(u, { auth: auth }, function (er, response) { if (er) { - log.error("fetch failed", u) + log.error('fetch failed', u) return cb(er, response) } - var tarball = createWriteStream(tmp, { mode : npm.modes.file }) - tarball.on("error", function (er) { + var tarball = createWriteStream(tmp, { mode: npm.modes.file }) + tarball.on('error', function (er) { cb(er) tarball.destroy() }) - tarball.on("finish", function () { + tarball.on('finish', function () { if (!shasum) { // Well, we weren't given a shasum, so at least sha what we have // in case we want to compare it to something else later return sha.get(tmp, function (er, shasum) { - log.silly("fetchAndShaCheck", "shasum", shasum) + log.silly('fetchAndShaCheck', 'shasum', shasum) cb(er, response, shasum) }) } // validate that the url we just downloaded matches the expected shasum. - log.silly("fetchAndShaCheck", "shasum", shasum) + log.silly('fetchAndShaCheck', 'shasum', shasum) sha.check(tmp, shasum, function (er) { if (er && er.message) { // add original filename for better debuggability - er.message = er.message + "\n" + "From: " + u + er.message = er.message + '\n' + 'From: ' + u } return cb(er, response, shasum) }) diff --git a/lib/cache/cached-package-root.js b/lib/cache/cached-package-root.js index 7163314a8..b47fac6c9 100644 --- a/lib/cache/cached-package-root.js +++ b/lib/cache/cached-package-root.js @@ -1,14 +1,14 @@ -var assert = require("assert") -var resolve = require("path").resolve +var assert = require('assert') +var resolve = require('path').resolve -var npm = require("../npm.js") +var npm = require('../npm.js') module.exports = getCacheRoot function getCacheRoot (data) { - assert(data, "must pass package metadata") - assert(data.name, "package metadata must include name") - assert(data.version, "package metadata must include version") + assert(data, 'must pass package metadata') + assert(data.name, 'package metadata must include name') + assert(data.version, 'package metadata must include version') return resolve(npm.cache, data.name, data.version) } diff --git a/lib/cache/caching-client.js b/lib/cache/caching-client.js index ec8eb8e16..faf748b1f 100644 --- a/lib/cache/caching-client.js +++ b/lib/cache/caching-client.js @@ -1,30 +1,30 @@ module.exports = CachingRegistryClient -var path = require("path") - , fs = require("graceful-fs") - , url = require("url") - , assert = require("assert") - , inherits = require("util").inherits - -var RegistryClient = require("npm-registry-client") - , npm = require("../npm.js") - , log = require("npmlog") - , getCacheStat = require("./get-stat.js") - , cacheFile = require("npm-cache-filename") - , mkdirp = require("mkdirp") - , rimraf = require("rimraf") - , chownr = require("chownr") - , writeFile = require("write-file-atomic") +var path = require('path') +var fs = require('graceful-fs') +var url = require('url') +var assert = require('assert') +var inherits = require('util').inherits + +var RegistryClient = require('npm-registry-client') +var npm = require('../npm.js') +var log = require('npmlog') +var getCacheStat = require('./get-stat.js') +var cacheFile = require('npm-cache-filename') +var mkdirp = require('mkdirp') +var rimraf = require('rimraf') +var chownr = require('chownr') +var writeFile = require('write-file-atomic') function CachingRegistryClient (config) { RegistryClient.call(this, adaptConfig(config)) - this._mapToCache = cacheFile(config.get("cache")) + this._mapToCache = cacheFile(config.get('cache')) // swizzle in our custom cache invalidation logic this._request = this.request - this.request = this._invalidatingRequest - this.get = get + this.request = this._invalidatingRequest + this.get = get } inherits(CachingRegistryClient, RegistryClient) @@ -34,7 +34,7 @@ CachingRegistryClient.prototype._invalidatingRequest = function (uri, params, cb var args = arguments var method = params.method - if (method !== "HEAD" && method !== "GET") { + if (method !== 'HEAD' && method !== 'GET') { var invalidated = client._mapToCache(uri) // invalidate cache // @@ -43,7 +43,7 @@ CachingRegistryClient.prototype._invalidatingRequest = function (uri, params, cb // thinking that it didn't work when it did. // Note that failure is an acceptable option here, since the only // result will be a stale cache for some helper commands. - log.verbose("request", "invalidating", invalidated, "on", method) + log.verbose('request', 'invalidating', invalidated, 'on', method) return rimraf(invalidated, function () { cb.apply(undefined, args) }) @@ -54,23 +54,23 @@ CachingRegistryClient.prototype._invalidatingRequest = function (uri, params, cb } function get (uri, params, cb) { - assert(typeof uri === "string", "must pass registry URI to get") - assert(params && typeof params === "object", "must pass params to get") - assert(typeof cb === "function", "must pass callback to get") + assert(typeof uri === 'string', 'must pass registry URI to get') + assert(params && typeof params === 'object', 'must pass params to get') + assert(typeof cb === 'function', 'must pass callback to get') var parsed = url.parse(uri) assert( - parsed.protocol === "http:" || parsed.protocol === "https:", - "must have a URL that starts with http: or https:" + parsed.protocol === 'http:' || parsed.protocol === 'https:', + 'must have a URL that starts with http: or https:' ) - var cacheBase = cacheFile(npm.config.get("cache"))(uri) - var cachePath = path.join(cacheBase, ".cache.json") + var cacheBase = cacheFile(npm.config.get('cache'))(uri) + var cachePath = path.join(cacheBase, '.cache.json') // If the GET is part of a write operation (PUT or DELETE), then // skip past the cache entirely, but still save the results. if (uri.match(/\?write=true$/)) { - log.verbose("get", "GET as part of write; not caching result") + log.verbose('get', 'GET as part of write; not caching result') return get_.call(this, uri, cachePath, params, cb) } @@ -80,8 +80,7 @@ function get (uri, params, cb) { fs.readFile(cachePath, function (er, data) { try { data = JSON.parse(data) - } - catch (ex) { + } catch (ex) { data = null } @@ -90,8 +89,7 @@ function get (uri, params, cb) { get_.call(client, uri, cachePath, params, cb) }) - } - else { + } else { get_.call(client, uri, cachePath, params, cb) } }) @@ -99,16 +97,16 @@ function get (uri, params, cb) { function get_ (uri, cachePath, params, cb) { var staleOk = params.staleOk === undefined ? false : params.staleOk - , timeout = params.timeout === undefined ? -1 : params.timeout - , data = params.data - , stat = params.stat - , etag - , lastModified - - timeout = Math.min(timeout, npm.config.get("cache-max") || 0) - timeout = Math.max(timeout, npm.config.get("cache-min") || -Infinity) + var timeout = params.timeout === undefined ? -1 : params.timeout + var data = params.data + var stat = params.stat + var etag + var lastModified + + timeout = Math.min(timeout, npm.config.get('cache-max') || 0) + timeout = Math.max(timeout, npm.config.get('cache-min') || -Infinity) if (process.env.COMP_CWORD !== undefined && - process.env.COMP_LINE !== undefined && + process.env.COMP_LINE !== undefined && process.env.COMP_POINT !== undefined) { timeout = Math.max(timeout, 60000) } @@ -118,19 +116,19 @@ function get_ (uri, cachePath, params, cb) { if (data._lastModified) lastModified = data._lastModified if (stat && timeout && timeout > 0) { - if ((Date.now() - stat.mtime.getTime())/1000 < timeout) { - log.verbose("get", uri, "not expired, no request") + if ((Date.now() - stat.mtime.getTime()) / 1000 < timeout) { + log.verbose('get', uri, 'not expired, no request') delete data._etag delete data._lastModified - return cb(null, data, JSON.stringify(data), { statusCode : 304 }) + return cb(null, data, JSON.stringify(data), { statusCode: 304 }) } if (staleOk) { - log.verbose("get", uri, "staleOk, background update") + log.verbose('get', uri, 'staleOk, background update') delete data._etag delete data._lastModified process.nextTick( - cb.bind(null, null, data, JSON.stringify(data), { statusCode : 304 } ) + cb.bind(null, null, data, JSON.stringify(data), { statusCode: 304 }) ) cb = function () {} } @@ -138,10 +136,10 @@ function get_ (uri, cachePath, params, cb) { } var options = { - etag : etag, - lastModified : lastModified, - follow : params.follow, - auth : params.auth + etag: etag, + lastModified: lastModified, + follow: params.follow, + auth: params.auth } this.request(uri, options, function (er, remoteData, raw, response) { // if we get an error talking to the registry, but we have it @@ -152,15 +150,15 @@ function get_ (uri, cachePath, params, cb) { } if (response) { - log.silly("get", "cb", [response.statusCode, response.headers]) + log.silly('get', 'cb', [response.statusCode, response.headers]) if (response.statusCode === 304 && (etag || lastModified)) { remoteData = data - log.verbose(etag ? "etag" : "lastModified", uri+" from cache") + log.verbose(etag ? 'etag' : 'lastModified', uri + ' from cache') } } data = remoteData - if (!data) er = er || new Error("failed to fetch from registry: " + uri) + if (!data) er = er || new Error('failed to fetch from registry: ' + uri) if (er) return cb(er, data, raw, response) @@ -174,7 +172,7 @@ function get_ (uri, cachePath, params, cb) { } function saveToCache (cachePath, data, saved) { - log.verbose("get", "saving", data.name, "to", cachePath) + log.verbose('get', 'saving', data.name, 'to', cachePath) getCacheStat(function (er, st) { mkdirp(path.dirname(cachePath), function (er, made) { if (er) return saved() @@ -192,26 +190,26 @@ function get_ (uri, cachePath, params, cb) { function adaptConfig (config) { return { - proxy : { - http : config.get("proxy"), - https : config.get("https-proxy"), - localAddress : config.get("local-address") + proxy: { + http: config.get('proxy'), + https: config.get('https-proxy'), + localAddress: config.get('local-address') }, - ssl : { - certificate : config.get("cert"), - key : config.get("key"), - ca : config.get("ca"), - strict : config.get("strict-ssl") + ssl: { + certificate: config.get('cert'), + key: config.get('key'), + ca: config.get('ca'), + strict: config.get('strict-ssl') }, - retry : { - retries : config.get("fetch-retries"), - factor : config.get("fetch-retry-factor"), - minTimeout : config.get("fetch-retry-mintimeout"), - maxTimeout : config.get("fetch-retry-maxtimeout") + retry: { + retries: config.get('fetch-retries'), + factor: config.get('fetch-retry-factor'), + minTimeout: config.get('fetch-retry-mintimeout'), + maxTimeout: config.get('fetch-retry-maxtimeout') }, - userAgent : config.get("user-agent"), - log : log, - defaultTag : config.get("tag"), - couchToken : config.get("_token") + userAgent: config.get('user-agent'), + log: log, + defaultTag: config.get('tag'), + couchToken: config.get('_token') } } diff --git a/lib/completion.js b/lib/completion.js index 7ae7e4742..e9a838d48 100644 --- a/lib/completion.js +++ b/lib/completion.js @@ -1,117 +1,114 @@ module.exports = completion -completion.usage = "source <(npm completion)" - -var npm = require("./npm.js") - , npmconf = require("./config/core.js") - , configDefs = npmconf.defs - , configTypes = configDefs.types - , shorthands = configDefs.shorthands - , nopt = require("nopt") - , configNames = Object.keys(configTypes).filter(function (e) { - return e.charAt(0) !== "_" +completion.usage = 'source <(npm completion)' + +var npm = require('./npm.js') +var npmconf = require('./config/core.js') +var configDefs = npmconf.defs +var configTypes = configDefs.types +var shorthands = configDefs.shorthands +var nopt = require('nopt') +var configNames = Object.keys(configTypes).filter(function (e) { + return e.charAt(0) !== '_' }) - , shorthandNames = Object.keys(shorthands) - , allConfs = configNames.concat(shorthandNames) - , once = require("once") - +var shorthandNames = Object.keys(shorthands) +var allConfs = configNames.concat(shorthandNames) +var once = require('once') completion.completion = function (opts, cb) { if (opts.w > 3) return cb() - var fs = require("graceful-fs") - , path = require("path") - , bashExists = null - , zshExists = null - fs.stat(path.resolve(process.env.HOME, ".bashrc"), function (er) { + var fs = require('graceful-fs') + var path = require('path') + var bashExists = null + var zshExists = null + fs.stat(path.resolve(process.env.HOME, '.bashrc'), function (er) { bashExists = !er next() }) - fs.stat(path.resolve(process.env.HOME, ".zshrc"), function (er) { + fs.stat(path.resolve(process.env.HOME, '.zshrc'), function (er) { zshExists = !er next() }) function next () { if (zshExists === null || bashExists === null) return var out = [] - if (zshExists) out.push("~/.zshrc") - if (bashExists) out.push("~/.bashrc") - if (opts.w === 2) out = out.map(function (m) { - return [">>", m] - }) + if (zshExists) out.push('~/.zshrc') + if (bashExists) out.push('~/.bashrc') + if (opts.w === 2) { + out = out.map(function (m) { + return ['>>', m] + }) + } cb(null, out) } } function completion (args, cb) { - if (process.platform === "win32") { - var e = new Error("npm completion not supported on windows") - e.code = "ENOTSUP" - e.errno = require("constants").ENOTSUP + if (process.platform === 'win32') { + var e = new Error('npm completion not supported on windows') + e.code = 'ENOTSUP' + e.errno = require('constants').ENOTSUP return cb(e) } // if the COMP_* isn't in the env, then just dump the script. - if (process.env.COMP_CWORD === undefined - ||process.env.COMP_LINE === undefined - ||process.env.COMP_POINT === undefined - ) return dumpScript(cb) + if (process.env.COMP_CWORD === undefined || + process.env.COMP_LINE === undefined || + process.env.COMP_POINT === undefined) { + return dumpScript(cb) + } console.error(process.env.COMP_CWORD) console.error(process.env.COMP_LINE) console.error(process.env.COMP_POINT) - //console.log("abracadabrasauce\nabracad cat monger") - //if (Math.random() * 3 < 1) console.log("man\\ bear\\ pig") - //else if (Math.random() * 3 < 1) - // console.log("porkchop\\ sandwiches\nporkman") - //else console.log("encephylophagy") - // get the partial line and partial word, // if the point isn't at the end. // ie, tabbing at: npm foo b|ar var w = +process.env.COMP_CWORD - , words = args.map(unescape) - , word = words[w] - , line = process.env.COMP_LINE - , point = +process.env.COMP_POINT - , partialLine = line.substr(0, point) - , partialWords = words.slice(0, w) + var words = args.map(unescape) + var word = words[w] + var line = process.env.COMP_LINE + var point = +process.env.COMP_POINT + var partialLine = line.substr(0, point) + var partialWords = words.slice(0, w) // figure out where in that last word the point is. var partialWord = args[w] - , i = partialWord.length - while (partialWord.substr(0, i) !== partialLine.substr(-1*i) && i > 0) { - i -- + var i = partialWord.length + while (partialWord.substr(0, i) !== partialLine.substr(-1 * i) && i > 0) { + i-- } partialWord = unescape(partialWord.substr(0, i)) partialWords.push(partialWord) - var opts = { words : words - , w : w - , word : word - , line : line - , lineLength : line.length - , point : point - , partialLine : partialLine - , partialWords : partialWords - , partialWord : partialWord - , raw: args - } + var opts = { + words: words, + w: w, + word: word, + line: line, + lineLength: line.length, + point: point, + partialLine: partialLine, + partialWords: partialWords, + partialWord: partialWord, + raw: args + } cb = wrapCb(cb, opts) console.error(opts) - if (partialWords.slice(0, -1).indexOf("--") === -1) { - if (word.charAt(0) === "-") return configCompl(opts, cb) - if (words[w - 1] - && words[w - 1].charAt(0) === "-" - && !isFlag(words[w - 1])) { + if (partialWords.slice(0, -1).indexOf('--') === -1) { + if (word.charAt(0) === '-') return configCompl(opts, cb) + if (words[w - 1] && + words[w - 1].charAt(0) === '-' && + !isFlag(words[w - 1])) { // awaiting a value for a non-bool config. // don't even try to do this for now - console.error("configValueCompl") + console.error('configValueCompl') return configValueCompl(opts, cb) } } @@ -143,20 +140,20 @@ function completion (args, cb) { } function dumpScript (cb) { - var fs = require("graceful-fs") - , path = require("path") - , p = path.resolve(__dirname, "utils/completion.sh") + var fs = require('graceful-fs') + var path = require('path') + var p = path.resolve(__dirname, 'utils/completion.sh') // The Darwin patch below results in callbacks first for the write and then // for the error handler, so make sure we only call our callback once. cb = once(cb) - fs.readFile(p, "utf8", function (er, d) { + fs.readFile(p, 'utf8', function (er, d) { if (er) return cb(er) - d = d.replace(/^\#\!.*?\n/, "") + d = d.replace(/^\#\!.*?\n/, '') process.stdout.write(d, function () { cb() }) - process.stdout.on("error", function (er) { + process.stdout.on('error', function (er) { // Darwin is a real dick sometimes. // // This is necessary because the "source" or "." program in @@ -167,7 +164,7 @@ function dumpScript (cb) { // Really, one should not be tossing away EPIPE errors, or any // errors, so casually. But, without this, `. <(npm completion)` // can never ever work on OS X. - if (er.errno === "EPIPE") er = null + if (er.errno === 'EPIPE') er = null cb(er) }) @@ -175,59 +172,65 @@ function dumpScript (cb) { } function unescape (w) { - if (w.charAt(0) === "\"") return w.replace(/^"|"$/g, "") - else return w.replace(/\\ /g, " ") + if (w.charAt(0) === '\'') return w.replace(/^'|'$/g, '') + else return w.replace(/\\ /g, ' ') } function escape (w) { if (!w.match(/\s+/)) return w - return "\"" + w + "\"" + return '\'' + w + '\'' } // The command should respond with an array. Loop over that, // wrapping quotes around any that have spaces, and writing // them to stdout. Use console.log, not the outfd config. // If any of the items are arrays, then join them with a space. -// Ie, returning ["a", "b c", ["d", "e"]] would allow it to expand -// to: "a", "b c", or "d" "e" -function wrapCb (cb, opts) { return function (er, compls) { - if (!Array.isArray(compls)) compls = compls ? [compls] : [] - compls = compls.map(function (c) { - if (Array.isArray(c)) c = c.map(escape).join(" ") - else c = escape(c) - return c - }) - if (opts.partialWord) compls = compls.filter(function (c) { - return c.indexOf(opts.partialWord) === 0 - }) - console.error([er && er.stack, compls, opts.partialWord]) - if (er || compls.length === 0) return cb(er) +// Ie, returning ['a', 'b c', ['d', 'e']] would allow it to expand +// to: 'a', 'b c', or 'd' 'e' +function wrapCb (cb, opts) { + return function (er, compls) { + if (!Array.isArray(compls)) compls = compls ? [compls] : [] + compls = compls.map(function (c) { + if (Array.isArray(c)) c = c.map(escape).join(' ') + else c = escape(c) + return c + }) - console.log(compls.join("\n")) - cb() -}} + if (opts.partialWord) { + compls = compls.filter(function (c) { + return c.indexOf(opts.partialWord) === 0 + }) + } + + console.error([er && er.stack, compls, opts.partialWord]) + if (er || compls.length === 0) return cb(er) + + console.log(compls.join('\n')) + cb() + } +} // the current word has a dash. Return the config names, // with the same number of dashes as the current word has. function configCompl (opts, cb) { var word = opts.word - , split = word.match(/^(-+)((?:no-)*)(.*)$/) - , dashes = split[1] - , no = split[2] - , flags = configNames.filter(isFlag) + var split = word.match(/^(-+)((?:no-)*)(.*)$/) + var dashes = split[1] + var no = split[2] + var flags = configNames.filter(isFlag) console.error(flags) return cb(null, allConfs.map(function (c) { return dashes + c }).concat(flags.map(function (f) { - return dashes + (no || "no-") + f + return dashes + (no || 'no-') + f }))) } // expand with the valid values of various config values. // not yet implemented. function configValueCompl (opts, cb) { - console.error("configValue", opts) + console.error('configValue', opts) return cb(null, []) } @@ -235,8 +238,8 @@ function configValueCompl (opts, cb) { function isFlag (word) { // shorthands never take args. var split = word.match(/^(-*)((?:no-)+)?(.*)$/) - , no = split[2] - , conf = split[3] + var no = split[2] + var conf = split[3] return no || configTypes[conf] === Boolean || shorthands[conf] } diff --git a/lib/config.js b/lib/config.js index c79cdc5b8..305e6bc8a 100644 --- a/lib/config.js +++ b/lib/config.js @@ -1,46 +1,47 @@ module.exports = config -config.usage = "npm config set <key> <value>" - + "\nnpm config get [<key>]" - + "\nnpm config delete <key>" - + "\nnpm config list" - + "\nnpm config edit" - + "\nnpm set <key> <value>" - + "\nnpm get [<key>]" +config.usage = 'npm config set <key> <value>' + + '\nnpm config get [<key>]' + + '\nnpm config delete <key>' + + '\nnpm config list' + + '\nnpm config edit' + + '\nnpm set <key> <value>' + + '\nnpm get [<key>]' -var log = require("npmlog") - , npm = require("./npm.js") - , npmconf = require("./config/core.js") - , fs = require("graceful-fs") - , writeFileAtomic = require("write-file-atomic") - , types = npmconf.defs.types - , ini = require("ini") - , editor = require("editor") - , os = require("os") - , umask = require("./utils/umask") +var log = require('npmlog') +var npm = require('./npm.js') +var npmconf = require('./config/core.js') +var fs = require('graceful-fs') +var writeFileAtomic = require('write-file-atomic') +var types = npmconf.defs.types +var ini = require('ini') +var editor = require('editor') +var os = require('os') +var umask = require('./utils/umask') config.completion = function (opts, cb) { var argv = opts.conf.argv.remain - if (argv[1] !== "config") argv.unshift("config") + if (argv[1] !== 'config') argv.unshift('config') if (argv.length === 2) { - var cmds = ["get", "set", "delete", "ls", "rm", "edit"] - if (opts.partialWord !== "l") cmds.push("list") + var cmds = ['get', 'set', 'delete', 'ls', 'rm', 'edit'] + if (opts.partialWord !== 'l') cmds.push('list') return cb(null, cmds) } var action = argv[2] switch (action) { - case "set": + case 'set': // todo: complete with valid values, if possible. if (argv.length > 3) return cb(null, []) // fallthrough - case "get": - case "delete": - case "rm": + /*eslint no-fallthrough:0*/ + case 'get': + case 'delete': + case 'rm': return cb(null, Object.keys(types)) - case "edit": - case "list": case "ls": + case 'edit': + case 'list': case 'ls': return cb(null, []) default: return cb(null, []) } @@ -52,87 +53,87 @@ config.completion = function (opts, cb) { function config (args, cb) { var action = args.shift() switch (action) { - case "set": return set(args[0], args[1], cb) - case "get": return get(args[0], cb) - case "delete": case "rm": case "del": return del(args[0], cb) - case "list": case "ls": return list(cb) - case "edit": return edit(cb) + case 'set': return set(args[0], args[1], cb) + case 'get': return get(args[0], cb) + case 'delete': case 'rm': case 'del': return del(args[0], cb) + case 'list': case 'ls': return list(cb) + case 'edit': return edit(cb) default: return unknown(action, cb) } } function edit (cb) { - var e = npm.config.get("editor") - , which = npm.config.get("global") ? "global" : "user" - , f = npm.config.get(which + "config") - if (!e) return cb(new Error("No EDITOR config or environ set.")) + var e = npm.config.get('editor') + var which = npm.config.get('global') ? 'global' : 'user' + var f = npm.config.get(which + 'config') + if (!e) return cb(new Error('No EDITOR config or environ set.')) npm.config.save(which, function (er) { if (er) return cb(er) - fs.readFile(f, "utf8", function (er, data) { - if (er) data = "" - data = [ ";;;;" - , "; npm "+(npm.config.get("global") ? - "globalconfig" : "userconfig")+" file" - , "; this is a simple ini-formatted file" - , "; lines that start with semi-colons are comments." - , "; read `npm help config` for help on the various options" - , ";;;;" - , "" - , data - ].concat( [ ";;;;" - , "; all options with default values" - , ";;;;" - ] - ) - .concat(Object.keys(npmconf.defaults).reduce(function (arr, key) { + fs.readFile(f, 'utf8', function (er, data) { + if (er) data = '' + data = [ + ';;;;', + '; npm ' + (npm.config.get('global') ? + 'globalconfig' : 'userconfig') + ' file', + '; this is a simple ini-formatted file', + '; lines that start with semi-colons are comments.', + '; read `npm help config` for help on the various options', + ';;;;', + '', + data + ].concat([ + ';;;;', + '; all options with default values', + ';;;;' + ]).concat(Object.keys(npmconf.defaults).reduce(function (arr, key) { var obj = {} obj[key] = npmconf.defaults[key] - if (key === "logstream") return arr + if (key === 'logstream') return arr return arr.concat( ini.stringify(obj) - .replace(/\n$/m, "") - .replace(/^/g, "; ") - .replace(/\n/g, "\n; ") - .split("\n")) + .replace(/\n$/m, '') + .replace(/^/g, '; ') + .replace(/\n/g, '\n; ') + .split('\n')) }, [])) - .concat([""]) + .concat(['']) .join(os.EOL) - writeFileAtomic - ( f - , data - , function (er) { - if (er) return cb(er) - editor(f, { editor: e }, cb) - } - ) + writeFileAtomic( + f, + data, + function (er) { + if (er) return cb(er) + editor(f, { editor: e }, cb) + } + ) }) }) } function del (key, cb) { - if (!key) return cb(new Error("no key provided")) - var where = npm.config.get("global") ? "global" : "user" + if (!key) return cb(new Error('no key provided')) + var where = npm.config.get('global') ? 'global' : 'user' npm.config.del(key, where) npm.config.save(where, cb) } function set (key, val, cb) { if (key === undefined) { - return unknown("", cb) + return unknown('', cb) } if (val === undefined) { - if (key.indexOf("=") !== -1) { - var k = key.split("=") + if (key.indexOf('=') !== -1) { + var k = key.split('=') key = k.shift() - val = k.join("=") + val = k.join('=') } else { - val = "" + val = '' } } key = key.trim() val = val.trim() - log.info("config", "set %j %j", key, val) - var where = npm.config.get("global") ? "global" : "user" + log.info('config', 'set %j %j', key, val) + var where = npm.config.get('global') ? 'global' : 'user' if (key.match(/umask/)) val = umask.fromString(val) npm.config.set(key, val, where) npm.config.save(where, cb) @@ -140,8 +141,8 @@ function set (key, val, cb) { function get (key, cb) { if (!key) return list(cb) - if (!public(key)) { - return cb(new Error("---sekretz---")) + if (!publicVar(key)) { + return cb(new Error('---sekretz---')) } var val = npm.config.get(key) if (key.match(/umask/)) val = umask.toString(val) @@ -153,133 +154,129 @@ function sort (a, b) { return a > b ? 1 : -1 } -function public (k) { - return !(k.charAt(0) === "_" || - k.indexOf(":_") !== -1 || +function publicVar (k) { + return !(k.charAt(0) === '_' || + k.indexOf(':_') !== -1 || types[k] !== types[k]) } function getKeys (data) { - return Object.keys(data).filter(public).sort(sort) + return Object.keys(data).filter(publicVar).sort(sort) } function list (cb) { - var msg = "" - , long = npm.config.get("long") + var msg = '' + var long = npm.config.get('long') var cli = npm.config.sources.cli.data - , cliKeys = getKeys(cli) + var cliKeys = getKeys(cli) if (cliKeys.length) { - msg += "; cli configs\n" + msg += '; cli configs\n' cliKeys.forEach(function (k) { - if (cli[k] && typeof cli[k] === "object") return - if (k === "argv") return - msg += k + " = " + JSON.stringify(cli[k]) + "\n" + if (cli[k] && typeof cli[k] === 'object') return + if (k === 'argv') return + msg += k + ' = ' + JSON.stringify(cli[k]) + '\n' }) - msg += "\n" + msg += '\n' } // env configs var env = npm.config.sources.env.data - , envKeys = getKeys(env) + var envKeys = getKeys(env) if (envKeys.length) { - msg += "; environment configs\n" + msg += '; environment configs\n' envKeys.forEach(function (k) { if (env[k] !== npm.config.get(k)) { if (!long) return - msg += "; " + k + " = " + JSON.stringify(env[k]) - + " (overridden)\n" - } else msg += k + " = " + JSON.stringify(env[k]) + "\n" + msg += '; ' + k + ' = ' + + JSON.stringify(env[k]) + ' (overridden)\n' + } else msg += k + ' = ' + JSON.stringify(env[k]) + '\n' }) - msg += "\n" + msg += '\n' } // user config file var uconf = npm.config.sources.user.data - , uconfKeys = getKeys(uconf) + var uconfKeys = getKeys(uconf) if (uconfKeys.length) { - msg += "; userconfig " + npm.config.get("userconfig") + "\n" + msg += '; userconfig ' + npm.config.get('userconfig') + '\n' uconfKeys.forEach(function (k) { - var val = (k.charAt(0) === "_") - ? "---sekretz---" + var val = (k.charAt(0) === '_') + ? '---sekretz---' : JSON.stringify(uconf[k]) if (uconf[k] !== npm.config.get(k)) { if (!long) return - msg += "; " + k + " = " + val - + " (overridden)\n" - } else msg += k + " = " + val + "\n" + msg += '; ' + k + ' = ' + val + ' (overridden)\n' + } else msg += k + ' = ' + val + '\n' }) - msg += "\n" + msg += '\n' } // global config file var gconf = npm.config.sources.global.data - , gconfKeys = getKeys(gconf) + var gconfKeys = getKeys(gconf) if (gconfKeys.length) { - msg += "; globalconfig " + npm.config.get("globalconfig") + "\n" + msg += '; globalconfig ' + npm.config.get('globalconfig') + '\n' gconfKeys.forEach(function (k) { - var val = (k.charAt(0) === "_") - ? "---sekretz---" + var val = (k.charAt(0) === '_') + ? '---sekretz---' : JSON.stringify(gconf[k]) if (gconf[k] !== npm.config.get(k)) { if (!long) return - msg += "; " + k + " = " + val - + " (overridden)\n" - } else msg += k + " = " + val + "\n" + msg += '; ' + k + ' = ' + val + ' (overridden)\n' + } else msg += k + ' = ' + val + '\n' }) - msg += "\n" + msg += '\n' } // builtin config file var builtin = npm.config.sources.builtin || {} if (builtin && builtin.data) { var bconf = builtin.data - , bpath = builtin.path - , bconfKeys = getKeys(bconf) + var bpath = builtin.path + var bconfKeys = getKeys(bconf) if (bconfKeys.length) { - msg += "; builtin config " + bpath + "\n" + msg += '; builtin config ' + bpath + '\n' bconfKeys.forEach(function (k) { - var val = (k.charAt(0) === "_") - ? "---sekretz---" + var val = (k.charAt(0) === '_') + ? '---sekretz---' : JSON.stringify(bconf[k]) if (bconf[k] !== npm.config.get(k)) { if (!long) return - msg += "; " + k + " = " + val - + " (overridden)\n" - } else msg += k + " = " + val + "\n" + msg += '; ' + k + ' = ' + val + ' (overridden)\n' + } else msg += k + ' = ' + val + '\n' }) - msg += "\n" + msg += '\n' } } // only show defaults if --long if (!long) { - msg += "; node bin location = " + process.execPath + "\n" - + "; cwd = " + process.cwd() + "\n" - + "; HOME = " + process.env.HOME + "\n" - + "; 'npm config ls -l' to show all defaults.\n" + msg += '; node bin location = ' + process.execPath + '\n' + + '; cwd = ' + process.cwd() + '\n' + + '; HOME = ' + process.env.HOME + '\n' + + '; "npm config ls -l" to show all defaults.\n' console.log(msg) return cb() } var defaults = npmconf.defaults - , defKeys = getKeys(defaults) - msg += "; default values\n" + var defKeys = getKeys(defaults) + msg += '; default values\n' defKeys.forEach(function (k) { - if (defaults[k] && typeof defaults[k] === "object") return + if (defaults[k] && typeof defaults[k] === 'object') return var val = JSON.stringify(defaults[k]) if (defaults[k] !== npm.config.get(k)) { - msg += "; " + k + " = " + val - + " (overridden)\n" - } else msg += k + " = " + val + "\n" + msg += '; ' + k + ' = ' + val + ' (overridden)\n' + } else msg += k + ' = ' + val + '\n' }) - msg += "\n" + msg += '\n' console.log(msg) return cb() } function unknown (action, cb) { - cb("Usage:\n" + config.usage) + cb('Usage:\n' + config.usage) } diff --git a/lib/config/clear-credentials-by-uri.js b/lib/config/clear-credentials-by-uri.js index 88131f7ad..13c356605 100644 --- a/lib/config/clear-credentials-by-uri.js +++ b/lib/config/clear-credentials-by-uri.js @@ -1,16 +1,16 @@ -var assert = require("assert") +var assert = require('assert') -var toNerfDart = require("./nerf-dart.js") +var toNerfDart = require('./nerf-dart.js') module.exports = clearCredentialsByURI function clearCredentialsByURI (uri) { - assert(uri && typeof uri === "string", "registry URL is required") + assert(uri && typeof uri === 'string', 'registry URL is required') var nerfed = toNerfDart(uri) - this.del(nerfed + ":_authToken", "user") - this.del(nerfed + ":_password", "user") - this.del(nerfed + ":username", "user") - this.del(nerfed + ":email", "user") + this.del(nerfed + ':_authToken', 'user') + this.del(nerfed + ':_password', 'user') + this.del(nerfed + ':username', 'user') + this.del(nerfed + ':email', 'user') } diff --git a/lib/config/core.js b/lib/config/core.js index f11a98dfb..0c6d3ecdb 100644 --- a/lib/config/core.js +++ b/lib/config/core.js @@ -1,16 +1,15 @@ - -var CC = require("config-chain").ConfigChain -var inherits = require("inherits") -var configDefs = require("./defaults.js") +var CC = require('config-chain').ConfigChain +var inherits = require('inherits') +var configDefs = require('./defaults.js') var types = configDefs.types -var once = require("once") -var fs = require("fs") -var path = require("path") -var nopt = require("nopt") -var ini = require("ini") +var once = require('once') +var fs = require('fs') +var path = require('path') +var nopt = require('nopt') +var ini = require('ini') var Umask = configDefs.Umask -var mkdirp = require("mkdirp") -var umask = require("../utils/umask") +var mkdirp = require('mkdirp') +var umask = require('../utils/umask') exports.load = load exports.Conf = Conf @@ -19,11 +18,11 @@ exports.rootConf = null exports.usingBuiltin = false exports.defs = configDefs -Object.defineProperty(exports, "defaults", { get: function () { +Object.defineProperty(exports, 'defaults', { get: function () { return configDefs.defaults }, enumerable: true }) -Object.defineProperty(exports, "types", { get: function () { +Object.defineProperty(exports, 'types', { get: function () { return configDefs.types }, enumerable: true }) @@ -34,20 +33,19 @@ var myUid = process.env.SUDO_UID !== undefined var myGid = process.env.SUDO_GID !== undefined ? process.env.SUDO_GID : (process.getgid && process.getgid()) - var loading = false var loadCbs = [] function load () { var cli, builtin, cb - for (var i = 0; i < arguments.length; i++) + for (var i = 0; i < arguments.length; i++) { switch (typeof arguments[i]) { - case "string": builtin = arguments[i]; break - case "object": cli = arguments[i]; break - case "function": cb = arguments[i]; break + case 'string': builtin = arguments[i]; break + case 'object': cli = arguments[i]; break + case 'function': cb = arguments[i]; break } + } - if (!cb) - cb = function () {} + if (!cb) cb = function () {} if (exports.loaded) { var ret = exports.loaded @@ -59,17 +57,17 @@ function load () { } // either a fresh object, or a clone of the passed in obj - if (!cli) + if (!cli) { cli = {} - else + } else { cli = Object.keys(cli).reduce(function (c, k) { c[k] = cli[k] return c }, {}) + } loadCbs.push(cb) - if (loading) - return + if (loading) return loading = true @@ -87,28 +85,28 @@ function load () { // check for a builtin if provided. exports.usingBuiltin = !!builtin var rc = exports.rootConf = new Conf() - if (builtin) - rc.addFile(builtin, "builtin") - else - rc.add({}, "builtin") + if (builtin) { + rc.addFile(builtin, 'builtin') + } else { + rc.add({}, 'builtin') + } - rc.on("load", function () { + rc.on('load', function () { load_(builtin, rc, cli, cb) }) - rc.on("error", cb) + rc.on('error', cb) } -function load_(builtin, rc, cli, cb) { +function load_ (builtin, rc, cli, cb) { var defaults = configDefs.defaults var conf = new Conf(rc) conf.usingBuiltin = !!builtin - conf.add(cli, "cli") + conf.add(cli, 'cli') conf.addEnv() - conf.loadPrefix(function(er) { - if (er) - return cb(er) + conf.loadPrefix(function (er) { + if (er) return cb(er) // If you're doing `npm --userconfig=~/foo.npmrc` then you'd expect // that ~/.npmrc won't override the stuff in ~/foo.npmrc (or, indeed @@ -126,24 +124,24 @@ function load_(builtin, rc, cli, cb) { // the default or resolved userconfig value. npm will log a "verbose" // message about this when it happens, but it is a rare enough edge case // that we don't have to be super concerned about it. - var projectConf = path.resolve(conf.localPrefix, ".npmrc") - var defaultUserConfig = rc.get("userconfig") - var resolvedUserConfig = conf.get("userconfig") - if (!conf.get("global") && + var projectConf = path.resolve(conf.localPrefix, '.npmrc') + var defaultUserConfig = rc.get('userconfig') + var resolvedUserConfig = conf.get('userconfig') + if (!conf.get('global') && projectConf !== defaultUserConfig && projectConf !== resolvedUserConfig) { - conf.addFile(projectConf, "project") - conf.once("load", afterPrefix) + conf.addFile(projectConf, 'project') + conf.once('load', afterPrefix) } else { - conf.add({}, "project") + conf.add({}, 'project') afterPrefix() } }) - function afterPrefix() { - conf.addFile(conf.get("userconfig"), "user") - conf.once("error", cb) - conf.once("load", afterUser) + function afterPrefix () { + conf.addFile(conf.get('userconfig'), 'user') + conf.once('error', cb) + conf.once('load', afterUser) } function afterUser () { @@ -152,11 +150,11 @@ function load_(builtin, rc, cli, cb) { // Eg, `npm config get globalconfig --prefix ~/local` should // return `~/local/etc/npmrc` // annoying humans and their expectations! - if (conf.get("prefix")) { - var etc = path.resolve(conf.get("prefix"), "etc") - mkdirp(etc, function (err) { - defaults.globalconfig = path.resolve(etc, "npmrc") - defaults.globalignorefile = path.resolve(etc, "npmignore") + if (conf.get('prefix')) { + var etc = path.resolve(conf.get('prefix'), 'etc') + mkdirp(etc, function () { + defaults.globalconfig = path.resolve(etc, 'npmrc') + defaults.globalignorefile = path.resolve(etc, 'npmignore') afterUserContinuation() }) } else { @@ -164,25 +162,24 @@ function load_(builtin, rc, cli, cb) { } } - function afterUserContinuation() { - conf.addFile(conf.get("globalconfig"), "global") + function afterUserContinuation () { + conf.addFile(conf.get('globalconfig'), 'global') // move the builtin into the conf stack now. conf.root = defaults - conf.add(rc.shift(), "builtin") - conf.once("load", function () { + conf.add(rc.shift(), 'builtin') + conf.once('load', function () { conf.loadExtras(afterExtras) }) } - function afterExtras(er) { - if (er) - return cb(er) + function afterExtras (er) { + if (er) return cb(er) // warn about invalid bits. validate(conf) - var cafile = conf.get("cafile") + var cafile = conf.get('cafile') if (cafile) { return conf.loadCAFile(cafile, finalize) @@ -191,7 +188,7 @@ function load_(builtin, rc, cli, cb) { finalize() } - function finalize(er) { + function finalize (er) { if (er) { return cb(er) } @@ -208,36 +205,35 @@ function load_(builtin, rc, cli, cb) { // 4. Can inherit from another Conf object, using it as the base. inherits(Conf, CC) function Conf (base) { - if (!(this instanceof Conf)) - return new Conf(base) + if (!(this instanceof Conf)) return new Conf(base) CC.apply(this) - if (base) - if (base instanceof Conf) + if (base) { + if (base instanceof Conf) { this.root = base.list[0] || base.root - else + } else { this.root = base - else + } + } else { this.root = configDefs.defaults + } } -Conf.prototype.loadPrefix = require("./load-prefix.js") -Conf.prototype.loadCAFile = require("./load-cafile.js") -Conf.prototype.loadUid = require("./load-uid.js") -Conf.prototype.setUser = require("./set-user.js") -Conf.prototype.findPrefix = require("./find-prefix.js") -Conf.prototype.getCredentialsByURI = require("./get-credentials-by-uri.js") -Conf.prototype.setCredentialsByURI = require("./set-credentials-by-uri.js") -Conf.prototype.clearCredentialsByURI = require("./clear-credentials-by-uri.js") - -Conf.prototype.loadExtras = function(cb) { - this.setUser(function(er) { - if (er) - return cb(er) - this.loadUid(function(er) { - if (er) - return cb(er) +Conf.prototype.loadPrefix = require('./load-prefix.js') +Conf.prototype.loadCAFile = require('./load-cafile.js') +Conf.prototype.loadUid = require('./load-uid.js') +Conf.prototype.setUser = require('./set-user.js') +Conf.prototype.findPrefix = require('./find-prefix.js') +Conf.prototype.getCredentialsByURI = require('./get-credentials-by-uri.js') +Conf.prototype.setCredentialsByURI = require('./set-credentials-by-uri.js') +Conf.prototype.clearCredentialsByURI = require('./clear-credentials-by-uri.js') + +Conf.prototype.loadExtras = function (cb) { + this.setUser(function (er) { + if (er) return cb(er) + this.loadUid(function (er) { + if (er) return cb(er) // Without prefix, nothing will ever work mkdirp(this.prefix, cb) }.bind(this)) @@ -247,17 +243,17 @@ Conf.prototype.loadExtras = function(cb) { Conf.prototype.save = function (where, cb) { var target = this.sources[where] if (!target || !(target.path || target.source) || !target.data) { - if (where !== "builtin") - var er = new Error("bad save target: " + where) + var er + if (where !== 'builtin') er = new Error('bad save target: ' + where) if (cb) { process.nextTick(cb.bind(null, er)) return this } - return this.emit("error", er) + return this.emit('error', er) } if (target.source) { - var pref = target.prefix || "" + var pref = target.prefix || '' Object.keys(target.data).forEach(function (k) { target.source[pref + k] = target.data[k] }) @@ -267,11 +263,29 @@ Conf.prototype.save = function (where, cb) { var data = ini.stringify(target.data) + var then = function then (er) { + if (er) return done(er) + + fs.chmod(target.path, mode, done) + } + + var done = function done (er) { + if (er) { + if (cb) return cb(er) + else return this.emit('error', er) + } + this._saving -- + if (this._saving === 0) { + if (cb) cb() + this.emit('save') + } + } + then = then.bind(this) done = done.bind(this) this._saving ++ - var mode = where === "user" ? "0600" : "0666" + var mode = where === 'user' ? '0600' : '0666' if (!data.trim()) { fs.unlink(target.path, function () { // ignore the possible error (e.g. the file doesn't exist) @@ -279,57 +293,40 @@ Conf.prototype.save = function (where, cb) { }) } else { mkdirp(path.dirname(target.path), function (er) { - if (er) - return then(er) - fs.writeFile(target.path, data, "utf8", function (er) { - if (er) - return then(er) - if (where === "user" && myUid && myGid) + if (er) return then(er) + fs.writeFile(target.path, data, 'utf8', function (er) { + if (er) return then(er) + if (where === 'user' && myUid && myGid) { + fs.chown(target.path, +myUid, +myGid, then) - else + } else { then() + } }) }) } - function then (er) { - if (er) - return done(er) - fs.chmod(target.path, mode, done) - } - - function done (er) { - if (er) { - if (cb) return cb(er) - else return this.emit("error", er) - } - this._saving -- - if (this._saving === 0) { - if (cb) cb() - this.emit("save") - } - } - return this } Conf.prototype.addFile = function (file, name) { name = name || file - var marker = {__source__:name} - this.sources[name] = { path: file, type: "ini" } + var marker = { __source__: name } + this.sources[name] = { path: file, type: 'ini' } this.push(marker) this._await() - fs.readFile(file, "utf8", function (er, data) { - if (er) // just ignore missing files. - return this.add({}, marker) - this.addString(data, file, "ini", marker) + fs.readFile(file, 'utf8', function (er, data) { + // just ignore missing files. + if (er) return this.add({}, marker) + + this.addString(data, file, 'ini', marker) }.bind(this)) return this } // always ini files. Conf.prototype.parse = function (content, file) { - return CC.prototype.parse.call(this, content, file, "ini") + return CC.prototype.parse.call(this, content, file, 'ini') } Conf.prototype.add = function (data, marker) { @@ -337,9 +334,8 @@ Conf.prototype.add = function (data, marker) { Object.keys(data).forEach(function (k) { data[k] = parseField(data[k], k) }) - } - catch (e) { - this.emit("error", e) + } catch (e) { + this.emit('error', e) return this } return CC.prototype.add.call(this, data, marker) @@ -351,82 +347,77 @@ Conf.prototype.addEnv = function (env) { Object.keys(env) .filter(function (k) { return k.match(/^npm_config_/i) }) .forEach(function (k) { - if (!env[k]) - return + if (!env[k]) return // leave first char untouched, even if - // it is a "_" - convert all other to "-" + // it is a '_' - convert all other to '-' var p = k.toLowerCase() - .replace(/^npm_config_/, "") - .replace(/(?!^)_/g, "-") + .replace(/^npm_config_/, '') + .replace(/(?!^)_/g, '-') conf[p] = env[k] }) - return CC.prototype.addEnv.call(this, "", conf, "env") + return CC.prototype.addEnv.call(this, '', conf, 'env') } function parseField (f, k) { - if (typeof f !== "string" && !(f instanceof String)) - return f + if (typeof f !== 'string' && !(f instanceof String)) return f // type can be an array or single thing. var typeList = [].concat(types[k]) - var isPath = -1 !== typeList.indexOf(path) - var isBool = -1 !== typeList.indexOf(Boolean) - var isString = -1 !== typeList.indexOf(String) - var isUmask = -1 !== typeList.indexOf(Umask) - var isNumber = -1 !== typeList.indexOf(Number) + var isPath = typeList.indexOf(path) !== -1 + var isBool = typeList.indexOf(Boolean) !== -1 + var isString = typeList.indexOf(String) !== -1 + var isUmask = typeList.indexOf(Umask) !== -1 + var isNumber = typeList.indexOf(Number) !== -1 - f = (""+f).trim() + f = ('' + f).trim() if (f.match(/^".*"$/)) { try { f = JSON.parse(f) - } - catch (e) { - throw new Error("Failed parsing JSON config key " + k + ": " + f) + } catch (e) { + throw new Error('Failed parsing JSON config key ' + k + ': ' + f) } } - if (isBool && !isString && f === "") - return true + if (isBool && !isString && f === '') return true switch (f) { - case "true": return true - case "false": return false - case "null": return null - case "undefined": return undefined + case 'true': return true + case 'false': return false + case 'null': return null + case 'undefined': return undefined } f = envReplace(f) if (isPath) { - var homePattern = process.platform === "win32" ? /^~(\/|\\)/ : /^~\// + var homePattern = process.platform === 'win32' ? /^~(\/|\\)/ : /^~\// if (f.match(homePattern) && process.env.HOME) { f = path.resolve(process.env.HOME, f.substr(2)) } f = path.resolve(f) } - if (isUmask) - f = umask.fromString(f) + if (isUmask) f = umask.fromString(f) - if (isNumber && !isNaN(f)) - f = +f + if (isNumber && !isNaN(f)) f = +f return f } function envReplace (f) { - if (typeof f !== "string" || !f) return f + if (typeof f !== 'string' || !f) return f // replace any ${ENV} values with the appropriate environ. var envExpr = /(\\*)\$\{([^}]+)\}/g return f.replace(envExpr, function (orig, esc, name) { esc = esc.length && esc.length % 2 - if (esc) - return orig - if (undefined === process.env[name]) - throw new Error("Failed to replace env in config: "+orig) + if (esc) return orig + if (undefined === process.env[name]) { + throw new Error('Failed to replace env in config: ' + orig) + } + return process.env[name] }) } diff --git a/lib/config/defaults.js b/lib/config/defaults.js index 4f3c27ca3..133b8a09a 100644 --- a/lib/config/defaults.js +++ b/lib/config/defaults.js @@ -1,24 +1,23 @@ // defaults, types, and shorthands. - -var path = require("path") - , url = require("url") - , Stream = require("stream").Stream - , semver = require("semver") - , stableFamily = semver.parse(process.version) - , nopt = require("nopt") - , os = require("os") - , osenv = require("osenv") - , umask = require("../utils/umask") - , hasUnicode = require("has-unicode") +var path = require('path') +var url = require('url') +var Stream = require('stream').Stream +var semver = require('semver') +var stableFamily = semver.parse(process.version) +var nopt = require('nopt') +var os = require('os') +var osenv = require('osenv') +var umask = require('../utils/umask') +var hasUnicode = require('has-unicode') var log try { - log = require("npmlog") + log = require('npmlog') } catch (er) { - var util = require("util") + var util = require('util') log = { warn: function (m) { - console.warn(m + " " + util.format.apply(util, [].slice.call(arguments, 1))) + console.warn(m + ' ' + util.format.apply(util, [].slice.call(arguments, 1))) } } } @@ -43,7 +42,7 @@ nopt.typeDefs.Stream = { type: Stream, validate: validateStream } nopt.typeDefs.Umask = { type: Umask, validate: validateUmask } nopt.invalidHandler = function (k, val, type) { - log.warn("invalid config", k + "=" + JSON.stringify(val)) + log.warn('invalid config', k + '=' + JSON.stringify(val)) if (Array.isArray(type)) { if (type.indexOf(url) !== -1) type = url @@ -52,25 +51,25 @@ nopt.invalidHandler = function (k, val, type) { switch (type) { case Umask: - log.warn("invalid config", "Must be umask, octal number in range 0000..0777") + log.warn('invalid config', 'Must be umask, octal number in range 0000..0777') break case url: - log.warn("invalid config", "Must be a full url with 'http://'") + log.warn('invalid config', "Must be a full url with 'http://'") break case path: - log.warn("invalid config", "Must be a valid filesystem path") + log.warn('invalid config', 'Must be a valid filesystem path') break case Number: - log.warn("invalid config", "Must be a numeric value") + log.warn('invalid config', 'Must be a numeric value') break case Stream: - log.warn("invalid config", "Must be an instance of the Stream class") + log.warn('invalid config', 'Must be an instance of the Stream class') break } } if (!stableFamily || (+stableFamily.minor % 2)) stableFamily = null -else stableFamily = stableFamily.major + "." + stableFamily.minor +else stableFamily = stableFamily.major + '.' + stableFamily.minor var defaults @@ -80,20 +79,19 @@ var home = osenv.home() var uidOrPid = process.getuid ? process.getuid() : process.pid if (home) process.env.HOME = home -else home = path.resolve(temp, "npm-" + uidOrPid) +else home = path.resolve(temp, 'npm-' + uidOrPid) -var cacheExtra = process.platform === "win32" ? "npm-cache" : ".npm" -var cacheRoot = process.platform === "win32" && process.env.APPDATA || home +var cacheExtra = process.platform === 'win32' ? 'npm-cache' : '.npm' +var cacheRoot = process.platform === 'win32' && process.env.APPDATA || home var cache = path.resolve(cacheRoot, cacheExtra) - var globalPrefix -Object.defineProperty(exports, "defaults", {get: function () { +Object.defineProperty(exports, 'defaults', {get: function () { if (defaults) return defaults if (process.env.PREFIX) { globalPrefix = process.env.PREFIX - } else if (process.platform === "win32") { + } else if (process.platform === 'win32') { // c:\node\node.exe --> prefix=c:\node\ globalPrefix = path.dirname(process.execPath) } else { @@ -107,214 +105,216 @@ Object.defineProperty(exports, "defaults", {get: function () { } defaults = { - access : null - , "always-auth" : false - - , "bin-links" : true - , browser : null - - , ca: null - , cafile: null - - , cache : cache - - , "cache-lock-stale": 60000 - , "cache-lock-retries": 10 - , "cache-lock-wait": 10000 - - , "cache-max": Infinity - , "cache-min": 10 - - , cert: null - - , color : true - , depth: Infinity - , description : true - , dev : false - , "dry-run" : false - , editor : osenv.editor() - , "engine-strict": false - , force : false - - , "fetch-retries": 2 - , "fetch-retry-factor": 10 - , "fetch-retry-mintimeout": 10000 - , "fetch-retry-maxtimeout": 60000 - - , git: "git" - , "git-tag-version": true - - , global : false - , globalconfig : path.resolve(globalPrefix, "etc", "npmrc") - , group : process.platform === "win32" ? 0 - : process.env.SUDO_GID || (process.getgid && process.getgid()) - , heading: "npm" - , "if-present": false - , "ignore-scripts": false - , "init-module": path.resolve(home, ".npm-init.js") - , "init-author-name" : "" - , "init-author-email" : "" - , "init-author-url" : "" - , "init-version": "1.0.0" - , "init-license": "ISC" - , json: false - , key: null - , link: false - , "local-address" : undefined - , loglevel : "warn" - , logstream : process.stderr - , long : false - , message : "%s" - , "node-version" : process.version - , npat : false - , "onload-script" : false - , optional: true - , parseable : false - , prefix : globalPrefix - , production: process.env.NODE_ENV === "production" - , "proprietary-attribs": true - , proxy : null - , "https-proxy" : null - , "user-agent" : "npm/{npm-version} " - + "node/{node-version} " - + "{platform} " - + "{arch}" - , "rebuild-bundle" : true - , registry : "https://registry.npmjs.org/" - , rollback : true - , save : false - , "save-bundle": false - , "save-dev" : false - , "save-exact" : false - , "save-optional" : false - , "save-prefix": "^" - , scope : "" - , searchopts: "" - , searchexclude: null - , searchsort: "name" - , shell : osenv.shell() - , shrinkwrap: true - , "sign-git-tag": false - , "strict-ssl": true - , tag : "latest" - , "tag-version-prefix" : "v" - , tmp : temp - , unicode : hasUnicode() - , "unsafe-perm" : process.platform === "win32" - || process.platform === "cygwin" - || !( process.getuid && process.setuid - && process.getgid && process.setgid ) - || process.getuid() !== 0 - , usage : false - , user : process.platform === "win32" ? 0 : "nobody" - , userconfig : path.resolve(home, ".npmrc") - , umask: process.umask ? process.umask() : umask.fromString("022") - , version : false - , versions : false - , viewer: process.platform === "win32" ? "browser" : "man" - - , _exit : true + access: null, + 'always-auth': false, + + 'bin-links': true, + browser: null, + + ca: null, + cafile: null, + + cache: cache, + + 'cache-lock-stale': 60000, + 'cache-lock-retries': 10, + 'cache-lock-wait': 10000, + + 'cache-max': Infinity, + 'cache-min': 10, + + cert: null, + + color: true, + depth: Infinity, + description: true, + dev: false, + 'dry-run': false, + editor: osenv.editor(), + 'engine-strict': false, + force: false, + + 'fetch-retries': 2, + 'fetch-retry-factor': 10, + 'fetch-retry-mintimeout': 10000, + 'fetch-retry-maxtimeout': 60000, + + git: 'git', + 'git-tag-version': true, + + global: false, + globalconfig: path.resolve(globalPrefix, 'etc', 'npmrc'), + group: process.platform === 'win32' ? 0 + : process.env.SUDO_GID || (process.getgid && process.getgid()), + heading: 'npm', + 'if-present': false, + 'ignore-scripts': false, + 'init-module': path.resolve(home, '.npm-init.js'), + 'init-author-name': '', + 'init-author-email': '', + 'init-author-url': '', + 'init-version': '1.0.0', + 'init-license': 'ISC', + json: false, + key: null, + link: false, + 'local-address': undefined, + loglevel: 'warn', + logstream: process.stderr, + long: false, + message: '%s', + 'node-version': process.version, + npat: false, + 'onload-script': false, + optional: true, + parseable: false, + prefix: globalPrefix, + production: process.env.NODE_ENV === 'production', + 'proprietary-attribs': true, + proxy: null, + 'https-proxy': null, + 'user-agent': 'npm/{npm-version} ' + + 'node/{node-version} ' + + '{platform} ' + + '{arch}', + 'rebuild-bundle': true, + registry: 'https://registry.npmjs.org/', + rollback: true, + save: false, + 'save-bundle': false, + 'save-dev': false, + 'save-exact': false, + 'save-optional': false, + 'save-prefix': '^', + scope: '', + searchopts: '', + searchexclude: null, + searchsort: 'name', + shell: osenv.shell(), + shrinkwrap: true, + 'sign-git-tag': false, + 'strict-ssl': true, + tag: 'latest', + 'tag-version-prefix': 'v', + tmp: temp, + unicode: hasUnicode(), + 'unsafe-perm': process.platform === 'win32' || + process.platform === 'cygwin' || + !(process.getuid && process.setuid && + process.getgid && process.setgid) || + process.getuid() !== 0, + usage: false, + user: process.platform === 'win32' ? 0 : 'nobody', + userconfig: path.resolve(home, '.npmrc'), + umask: process.umask ? process.umask() : umask.fromString('022'), + version: false, + versions: false, + viewer: process.platform === 'win32' ? 'browser' : 'man', + + _exit: true } return defaults }}) -exports.types = - { access : [null, "restricted", "public"] - , "always-auth" : Boolean - , "bin-links": Boolean - , browser : [null, String] - , ca: [null, String, Array] - , cafile : path - , cache : path - , "cache-lock-stale": Number - , "cache-lock-retries": Number - , "cache-lock-wait": Number - , "cache-max": Number - , "cache-min": Number - , cert: [null, String] - , color : ["always", Boolean] - , depth : Number - , description : Boolean - , dev : Boolean - , "dry-run" : Boolean - , editor : String - , "engine-strict": Boolean - , force : Boolean - , "fetch-retries": Number - , "fetch-retry-factor": Number - , "fetch-retry-mintimeout": Number - , "fetch-retry-maxtimeout": Number - , git: String - , "git-tag-version": Boolean - , global : Boolean - , globalconfig : path - , group : [Number, String] - , "https-proxy" : [null, url] - , "user-agent" : String - , "heading": String - , "if-present": Boolean - , "ignore-scripts": Boolean - , "init-module": path - , "init-author-name" : String - , "init-author-email" : String - , "init-author-url" : ["", url] - , "init-license": String - , "init-version": semver - , json: Boolean - , key: [null, String] - , link: Boolean +exports.types = { + access: [null, 'restricted', 'public'], + 'always-auth': Boolean, + 'bin-links': Boolean, + browser: [null, String], + ca: [null, String, Array], + cafile: path, + cache: path, + 'cache-lock-stale': Number, + 'cache-lock-retries': Number, + 'cache-lock-wait': Number, + 'cache-max': Number, + 'cache-min': Number, + cert: [null, String], + color: ['always', Boolean], + depth: Number, + description: Boolean, + dev: Boolean, + 'dry-run': Boolean, + editor: String, + 'engine-strict': Boolean, + force: Boolean, + 'fetch-retries': Number, + 'fetch-retry-factor': Number, + 'fetch-retry-mintimeout': Number, + 'fetch-retry-maxtimeout': Number, + git: String, + 'git-tag-version': Boolean, + global: Boolean, + globalconfig: path, + group: [Number, String], + 'https-proxy': [null, url], + 'user-agent': String, + 'heading': String, + 'if-present': Boolean, + 'ignore-scripts': Boolean, + 'init-module': path, + 'init-author-name': String, + 'init-author-email': String, + 'init-author-url': ['', url], + 'init-license': String, + 'init-version': semver, + json: Boolean, + key: [null, String], + link: Boolean, // local-address must be listed as an IP for a local network interface // must be IPv4 due to node bug - , "local-address" : getLocalAddresses() - , loglevel : ["silent", "error", "warn", "http", "info", "verbose", "silly"] - , logstream : Stream - , long : Boolean - , message: String - , "node-version" : [null, semver] - , npat : Boolean - , "onload-script" : [null, String] - , optional: Boolean - , parseable : Boolean - , prefix: path - , production: Boolean - , "proprietary-attribs": Boolean - , proxy : [null, false, url] // allow proxy to be disabled explicitly - , "rebuild-bundle" : Boolean - , registry : [null, url] - , rollback : Boolean - , save : Boolean - , "save-bundle": Boolean - , "save-dev" : Boolean - , "save-exact" : Boolean - , "save-optional" : Boolean - , "save-prefix": String - , scope : String - , searchopts : String - , searchexclude: [null, String] - , searchsort: [ "name", "-name" - , "description", "-description" - , "author", "-author" - , "date", "-date" - , "keywords", "-keywords" ] - , shell : String - , shrinkwrap: Boolean - , "sign-git-tag": Boolean - , "strict-ssl": Boolean - , tag : String - , tmp : path - , unicode : Boolean - , "unsafe-perm" : Boolean - , usage : Boolean - , user : [Number, String] - , userconfig : path - , umask: Umask - , version : Boolean - , "tag-version-prefix" : String - , versions : Boolean - , viewer: String - , _exit : Boolean - } + 'local-address': getLocalAddresses(), + loglevel: ['silent', 'error', 'warn', 'http', 'info', 'verbose', 'silly'], + logstream: Stream, + long: Boolean, + message: String, + 'node-version': [null, semver], + npat: Boolean, + 'onload-script': [null, String], + optional: Boolean, + parseable: Boolean, + prefix: path, + production: Boolean, + 'proprietary-attribs': Boolean, + proxy: [null, false, url], // allow proxy to be disabled explicitly + 'rebuild-bundle': Boolean, + registry: [null, url], + rollback: Boolean, + save: Boolean, + 'save-bundle': Boolean, + 'save-dev': Boolean, + 'save-exact': Boolean, + 'save-optional': Boolean, + 'save-prefix': String, + scope: String, + searchopts: String, + searchexclude: [null, String], + searchsort: [ + 'name', '-name', + 'description', '-description', + 'author', '-author', + 'date', '-date', + 'keywords', '-keywords' + ], + shell: String, + shrinkwrap: Boolean, + 'sign-git-tag': Boolean, + 'strict-ssl': Boolean, + tag: String, + tmp: path, + unicode: Boolean, + 'unsafe-perm': Boolean, + usage: Boolean, + user: [Number, String], + userconfig: path, + umask: Umask, + version: Boolean, + 'tag-version-prefix': String, + versions: Boolean, + viewer: String, + _exit: Boolean +} function getLocalAddresses () { var interfaces @@ -339,41 +339,41 @@ function getLocalAddresses () { }, []).concat(undefined) } -exports.shorthands = - { s : ["--loglevel", "silent"] - , d : ["--loglevel", "info"] - , dd : ["--loglevel", "verbose"] - , ddd : ["--loglevel", "silly"] - , noreg : ["--no-registry"] - , N : ["--no-registry"] - , reg : ["--registry"] - , "no-reg" : ["--no-registry"] - , silent : ["--loglevel", "silent"] - , verbose : ["--loglevel", "verbose"] - , quiet: ["--loglevel", "warn"] - , q: ["--loglevel", "warn"] - , h : ["--usage"] - , H : ["--usage"] - , "?" : ["--usage"] - , help : ["--usage"] - , v : ["--version"] - , f : ["--force"] - , gangster : ["--force"] - , gangsta : ["--force"] - , desc : ["--description"] - , "no-desc" : ["--no-description"] - , "local" : ["--no-global"] - , l : ["--long"] - , m : ["--message"] - , p : ["--parseable"] - , porcelain : ["--parseable"] - , g : ["--global"] - , S : ["--save"] - , D : ["--save-dev"] - , E : ["--save-exact"] - , O : ["--save-optional"] - , y : ["--yes"] - , n : ["--no-yes"] - , B : ["--save-bundle"] - , C : ["--prefix"] - } +exports.shorthands = { + s: ['--loglevel', 'silent'], + d: ['--loglevel', 'info'], + dd: ['--loglevel', 'verbose'], + ddd: ['--loglevel', 'silly'], + noreg: ['--no-registry'], + N: ['--no-registry'], + reg: ['--registry'], + 'no-reg': ['--no-registry'], + silent: ['--loglevel', 'silent'], + verbose: ['--loglevel', 'verbose'], + quiet: ['--loglevel', 'warn'], + q: ['--loglevel', 'warn'], + h: ['--usage'], + H: ['--usage'], + '?': ['--usage'], + help: ['--usage'], + v: ['--version'], + f: ['--force'], + gangster: ['--force'], + gangsta: ['--force'], + desc: ['--description'], + 'no-desc': ['--no-description'], + 'local': ['--no-global'], + l: ['--long'], + m: ['--message'], + p: ['--parseable'], + porcelain: ['--parseable'], + g: ['--global'], + S: ['--save'], + D: ['--save-dev'], + E: ['--save-exact'], + O: ['--save-optional'], + y: ['--yes'], + n: ['--no-yes'], + B: ['--save-bundle'], + C: ['--prefix'] +} diff --git a/lib/config/find-prefix.js b/lib/config/find-prefix.js index bb00cd6b1..58f5cc804 100644 --- a/lib/config/find-prefix.js +++ b/lib/config/find-prefix.js @@ -2,8 +2,8 @@ module.exports = findPrefix -var fs = require("fs") -var path = require("path") +var fs = require('fs') +var path = require('path') function findPrefix (p, cb_) { function cb (er, p) { @@ -17,7 +17,7 @@ function findPrefix (p, cb_) { // walk up until we hopefully find one. // if none anywhere, then use cwd. var walkedUp = false - while (path.basename(p) === "node_modules") { + while (path.basename(p) === 'node_modules') { p = path.dirname(p) walkedUp = true } @@ -27,8 +27,8 @@ function findPrefix (p, cb_) { } function findPrefix_ (p, original, cb) { - if (p === "/" - || (process.platform === "win32" && p.match(/^[a-zA-Z]:(\\|\/)?$/))) { + if (p === '/' || + (process.platform === 'win32' && p.match(/^[a-zA-Z]:(\\|\/)?$/))) { return cb(null, original) } fs.readdir(p, function (er, files) { @@ -36,15 +36,15 @@ function findPrefix_ (p, original, cb) { // unless the prefix was simply a non // existent directory. if (er && p === original) { - if (er.code === "ENOENT") return cb(null, original); + if (er.code === 'ENOENT') return cb(null, original) return cb(er) } // walked up too high or something. if (er) return cb(null, original) - if (files.indexOf("node_modules") !== -1 - || files.indexOf("package.json") !== -1) { + if (files.indexOf('node_modules') !== -1 || + files.indexOf('package.json') !== -1) { return cb(null, p) } diff --git a/lib/config/get-credentials-by-uri.js b/lib/config/get-credentials-by-uri.js index 26a7f4317..a073a594a 100644 --- a/lib/config/get-credentials-by-uri.js +++ b/lib/config/get-credentials-by-uri.js @@ -1,27 +1,27 @@ -var assert = require("assert") +var assert = require('assert') -var toNerfDart = require("./nerf-dart.js") +var toNerfDart = require('./nerf-dart.js') module.exports = getCredentialsByURI function getCredentialsByURI (uri) { - assert(uri && typeof uri === "string", "registry URL is required") + assert(uri && typeof uri === 'string', 'registry URL is required') var nerfed = toNerfDart(uri) - var defnerf = toNerfDart(this.get("registry")) + var defnerf = toNerfDart(this.get('registry')) // hidden class micro-optimization var c = { - scope : nerfed, - token : undefined, - password : undefined, - username : undefined, - email : undefined, - auth : undefined, - alwaysAuth : undefined + scope: nerfed, + token: undefined, + password: undefined, + username: undefined, + email: undefined, + auth: undefined, + alwaysAuth: undefined } - if (this.get(nerfed + ":_authToken")) { - c.token = this.get(nerfed + ":_authToken") + if (this.get(nerfed + ':_authToken')) { + c.token = this.get(nerfed + ':_authToken') // the bearer token is enough, don't confuse things return c } @@ -30,43 +30,43 @@ function getCredentialsByURI (uri) { // registry, if set. // // XXX(isaacs): Remove when npm 1.4 is no longer relevant - var authDef = this.get("_auth") - var userDef = this.get("username") - var passDef = this.get("_password") + var authDef = this.get('_auth') + var userDef = this.get('username') + var passDef = this.get('_password') if (authDef && !(userDef && passDef)) { - authDef = new Buffer(authDef, "base64").toString() - authDef = authDef.split(":") + authDef = new Buffer(authDef, 'base64').toString() + authDef = authDef.split(':') userDef = authDef.shift() - passDef = authDef.join(":") + passDef = authDef.join(':') } - if (this.get(nerfed + ":_password")) { - c.password = new Buffer(this.get(nerfed + ":_password"), "base64").toString("utf8") + if (this.get(nerfed + ':_password')) { + c.password = new Buffer(this.get(nerfed + ':_password'), 'base64').toString('utf8') } else if (nerfed === defnerf && passDef) { c.password = passDef } - if (this.get(nerfed + ":username")) { - c.username = this.get(nerfed + ":username") + if (this.get(nerfed + ':username')) { + c.username = this.get(nerfed + ':username') } else if (nerfed === defnerf && userDef) { c.username = userDef } - if (this.get(nerfed + ":email")) { - c.email = this.get(nerfed + ":email") - } else if (this.get("email")) { - c.email = this.get("email") + if (this.get(nerfed + ':email')) { + c.email = this.get(nerfed + ':email') + } else if (this.get('email')) { + c.email = this.get('email') } - if (this.get(nerfed + ":always-auth") !== undefined) { - var val = this.get(nerfed + ":always-auth") - c.alwaysAuth = val === "false" ? false : !!val - } else if (this.get("always-auth") !== undefined) { - c.alwaysAuth = this.get("always-auth") + if (this.get(nerfed + ':always-auth') !== undefined) { + var val = this.get(nerfed + ':always-auth') + c.alwaysAuth = val === 'false' ? false : !!val + } else if (this.get('always-auth') !== undefined) { + c.alwaysAuth = this.get('always-auth') } if (c.username && c.password) { - c.auth = new Buffer(c.username + ":" + c.password).toString("base64") + c.auth = new Buffer(c.username + ':' + c.password).toString('base64') } return c diff --git a/lib/config/load-cafile.js b/lib/config/load-cafile.js index cc63615ff..1bf9cc490 100644 --- a/lib/config/load-cafile.js +++ b/lib/config/load-cafile.js @@ -1,14 +1,13 @@ module.exports = loadCAFile -var fs = require("fs") +var fs = require('fs') -function loadCAFile(cafilePath, cb) { - if (!cafilePath) - return process.nextTick(cb) +function loadCAFile (cafilePath, cb) { + if (!cafilePath) return process.nextTick(cb) - fs.readFile(cafilePath, "utf8", afterCARead.bind(this)) + fs.readFile(cafilePath, 'utf8', afterCARead.bind(this)) - function afterCARead(er, cadata) { + function afterCARead (er, cadata) { if (er) { // previous cafile no longer exists, so just continue on gracefully @@ -16,19 +15,19 @@ function loadCAFile(cafilePath, cb) { return cb(er) } - var delim = "-----END CERTIFICATE-----" + var delim = '-----END CERTIFICATE-----' var output output = cadata .split(delim) - .filter(function(xs) { + .filter(function (xs) { return !!xs.trim() }) - .map(function(xs) { + .map(function (xs) { return xs.trimLeft() + delim }) - this.set("ca", output) + this.set('ca', output) cb(null) } } diff --git a/lib/config/load-prefix.js b/lib/config/load-prefix.js index 39d076fb7..01a925280 100644 --- a/lib/config/load-prefix.js +++ b/lib/config/load-prefix.js @@ -1,43 +1,43 @@ module.exports = loadPrefix -var findPrefix = require("./find-prefix.js") -var path = require("path") +var findPrefix = require('./find-prefix.js') +var path = require('path') function loadPrefix (cb) { var cli = this.list[0] - Object.defineProperty(this, "prefix", - { set : function (prefix) { - var g = this.get("global") - this[g ? "globalPrefix" : "localPrefix"] = prefix - }.bind(this) - , get : function () { - var g = this.get("global") + Object.defineProperty(this, 'prefix', + { set: function (prefix) { + var g = this.get('global') + this[g ? 'globalPrefix' : 'localPrefix'] = prefix + }.bind(this), + get: function () { + var g = this.get('global') return g ? this.globalPrefix : this.localPrefix - }.bind(this) - , enumerable : true + }.bind(this), + enumerable: true }) - Object.defineProperty(this, "globalPrefix", - { set : function (prefix) { - this.set("prefix", prefix) - }.bind(this) - , get : function () { - return path.resolve(this.get("prefix")) - }.bind(this) - , enumerable : true + Object.defineProperty(this, 'globalPrefix', + { set: function (prefix) { + this.set('prefix', prefix) + }.bind(this), + get: function () { + return path.resolve(this.get('prefix')) + }.bind(this), + enumerable: true }) var p - Object.defineProperty(this, "localPrefix", - { set : function (prefix) { p = prefix }, - get : function () { return p } - , enumerable: true }) + Object.defineProperty(this, 'localPrefix', + { set: function (prefix) { p = prefix }, + get: function () { return p }, + enumerable: true }) // try to guess at a good node_modules location. // If we are *explicitly* given a prefix on the cli, then // always use that. otherwise, infer local prefix from cwd. - if (Object.prototype.hasOwnProperty.call(cli, "prefix")) { + if (Object.prototype.hasOwnProperty.call(cli, 'prefix')) { p = path.resolve(cli.prefix) process.nextTick(cb) } else { diff --git a/lib/config/load-uid.js b/lib/config/load-uid.js index 3ca798773..859eac749 100644 --- a/lib/config/load-uid.js +++ b/lib/config/load-uid.js @@ -1,14 +1,14 @@ module.exports = loadUid -var getUid = require("uid-number") +var getUid = require('uid-number') // Call in the context of a npmconf object function loadUid (cb) { // if we're not in unsafe-perm mode, then figure out who // to run stuff as. Do this first, to support `npm update npm -g` - if (!this.get("unsafe-perm")) { - getUid(this.get("user"), this.get("group"), cb) + if (!this.get('unsafe-perm')) { + getUid(this.get('user'), this.get('group'), cb) } else { process.nextTick(cb) } diff --git a/lib/config/nerf-dart.js b/lib/config/nerf-dart.js index 07c817500..8d2bdd26e 100644 --- a/lib/config/nerf-dart.js +++ b/lib/config/nerf-dart.js @@ -1,4 +1,4 @@ -var url = require("url") +var url = require('url') module.exports = toNerfDart @@ -11,7 +11,7 @@ module.exports = toNerfDart * * @returns {String} A nerfed URL. */ -function toNerfDart(uri) { +function toNerfDart (uri) { var parsed = url.parse(uri) delete parsed.protocol delete parsed.auth @@ -19,5 +19,5 @@ function toNerfDart(uri) { delete parsed.search delete parsed.hash - return url.resolve(url.format(parsed), ".") + return url.resolve(url.format(parsed), '.') } diff --git a/lib/config/set-credentials-by-uri.js b/lib/config/set-credentials-by-uri.js index 31eab4479..74211380d 100644 --- a/lib/config/set-credentials-by-uri.js +++ b/lib/config/set-credentials-by-uri.js @@ -1,42 +1,39 @@ -var assert = require("assert") +var assert = require('assert') -var toNerfDart = require("./nerf-dart.js") +var toNerfDart = require('./nerf-dart.js') module.exports = setCredentialsByURI function setCredentialsByURI (uri, c) { - assert(uri && typeof uri === "string", "registry URL is required") - assert(c && typeof c === "object", "credentials are required") + assert(uri && typeof uri === 'string', 'registry URL is required') + assert(c && typeof c === 'object', 'credentials are required') var nerfed = toNerfDart(uri) if (c.token) { - this.set(nerfed + ":_authToken", c.token, "user") - this.del(nerfed + ":_password", "user") - this.del(nerfed + ":username", "user") - this.del(nerfed + ":email", "user") - this.del(nerfed + ":always-auth", "user") - } - else if (c.username || c.password || c.email) { - assert(c.username, "must include username") - assert(c.password, "must include password") - assert(c.email, "must include email address") - - this.del(nerfed + ":_authToken", "user") - - var encoded = new Buffer(c.password, "utf8").toString("base64") - this.set(nerfed + ":_password", encoded, "user") - this.set(nerfed + ":username", c.username, "user") - this.set(nerfed + ":email", c.email, "user") + this.set(nerfed + ':_authToken', c.token, 'user') + this.del(nerfed + ':_password', 'user') + this.del(nerfed + ':username', 'user') + this.del(nerfed + ':email', 'user') + this.del(nerfed + ':always-auth', 'user') + } else if (c.username || c.password || c.email) { + assert(c.username, 'must include username') + assert(c.password, 'must include password') + assert(c.email, 'must include email address') + + this.del(nerfed + ':_authToken', 'user') + + var encoded = new Buffer(c.password, 'utf8').toString('base64') + this.set(nerfed + ':_password', encoded, 'user') + this.set(nerfed + ':username', c.username, 'user') + this.set(nerfed + ':email', c.email, 'user') if (c.alwaysAuth !== undefined) { - this.set(nerfed + ":always-auth", c.alwaysAuth, "user") + this.set(nerfed + ':always-auth', c.alwaysAuth, 'user') + } else { + this.del(nerfed + ':always-auth', 'user') } - else { - this.del(nerfed + ":always-auth", "user") - } - } - else { - throw new Error("No credentials to set.") + } else { + throw new Error('No credentials to set.') } } diff --git a/lib/config/set-user.js b/lib/config/set-user.js index 4c207a679..14cc21d2e 100644 --- a/lib/config/set-user.js +++ b/lib/config/set-user.js @@ -1,9 +1,9 @@ module.exports = setUser -var assert = require("assert") -var path = require("path") -var fs = require("fs") -var mkdirp = require("mkdirp") +var assert = require('assert') +var path = require('path') +var fs = require('fs') +var mkdirp = require('mkdirp') function setUser (cb) { var defaultConf = this.root @@ -12,13 +12,13 @@ function setUser (cb) { // If global, leave it as-is. // If not global, then set the user to the owner of the prefix folder. // Just set the default, so it can be overridden. - if (this.get("global")) return cb() + if (this.get('global')) return cb() if (process.env.SUDO_UID) { defaultConf.user = +(process.env.SUDO_UID) return cb() } - var prefix = path.resolve(this.get("prefix")) + var prefix = path.resolve(this.get('prefix')) mkdirp(prefix, function (er) { if (er) return cb(er) fs.stat(prefix, function (er, st) { diff --git a/lib/dedupe.js b/lib/dedupe.js index 28d1b12b9..95658aa94 100644 --- a/lib/dedupe.js +++ b/lib/dedupe.js @@ -70,7 +70,7 @@ Deduper.prototype.loadIdealTree = function (cb) { }], [this, this.finishTracker, 'loadAllDepsIntoIdealTree'], - [this, function (next) { recalculateMetadata(this.idealTree, log, next) } ], + [this, function (next) { recalculateMetadata(this.idealTree, log, next) }] ], cb) } diff --git a/lib/deprecate.js b/lib/deprecate.js index c90ad9027..ffc29c9c8 100644 --- a/lib/deprecate.js +++ b/lib/deprecate.js @@ -1,25 +1,25 @@ -var npm = require("./npm.js") - , mapToRegistry = require("./utils/map-to-registry.js") - , npa = require("npm-package-arg") +var npm = require('./npm.js') +var mapToRegistry = require('./utils/map-to-registry.js') +var npa = require('npm-package-arg') module.exports = deprecate -deprecate.usage = "npm deprecate <pkg>[@<version>] <message>" +deprecate.usage = 'npm deprecate <pkg>[@<version>] <message>' deprecate.completion = function (opts, cb) { // first, get a list of remote packages this user owns. // once we have a user account, then don't complete anything. if (opts.conf.argv.remain.length > 2) return cb() // get the list of packages by user - var path = "/-/by-user/" + var path = '/-/by-user/' mapToRegistry(path, npm.config, function (er, uri, c) { if (er) return cb(er) if (!(c && c.username)) return cb() var params = { - timeout : 60000, - auth : c + timeout: 60000, + auth: c } npm.registry.get(uri + c.username, params, function (er, list) { if (er) return cb() @@ -31,8 +31,8 @@ deprecate.completion = function (opts, cb) { function deprecate (args, cb) { var pkg = args[0] - , msg = args[1] - if (msg === undefined) return cb("Usage: " + deprecate.usage) + var msg = args[1] + if (msg === undefined) return cb('Usage: ' + deprecate.usage) // fetch the data and make sure it exists. var p = npa(pkg) @@ -41,9 +41,9 @@ function deprecate (args, cb) { if (er) return cb(er) var params = { - version : p.spec, - message : msg, - auth : auth + version: p.spec, + message: msg, + auth: auth } npm.registry.deprecate(uri, params, cb) }) diff --git a/lib/dist-tag.js b/lib/dist-tag.js index 48b40202f..d0bae9ab4 100644 --- a/lib/dist-tag.js +++ b/lib/dist-tag.js @@ -1,21 +1,21 @@ module.exports = distTag -var log = require("npmlog") -var npa = require("npm-package-arg") -var semver = require("semver") +var log = require('npmlog') +var npa = require('npm-package-arg') +var semver = require('semver') -var npm = require("./npm.js") -var mapToRegistry = require("./utils/map-to-registry.js") -var readLocalPkg = require("./utils/read-local-package.js") +var npm = require('./npm.js') +var mapToRegistry = require('./utils/map-to-registry.js') +var readLocalPkg = require('./utils/read-local-package.js') -distTag.usage = "npm dist-tag add <pkg>@<version> [<tag>]" - + "\nnpm dist-tag rm <pkg> <tag>" - + "\nnpm dist-tag ls [<pkg>]" +distTag.usage = 'npm dist-tag add <pkg>@<version> [<tag>]' + + '\nnpm dist-tag rm <pkg> <tag>' + + '\nnpm dist-tag ls [<pkg>]' distTag.completion = function (opts, cb) { var argv = opts.conf.argv.remain if (argv.length === 2) { - return cb(null, ["add", "rm", "ls"]) + return cb(null, ['add', 'rm', 'ls']) } switch (argv[2]) { @@ -27,29 +27,29 @@ distTag.completion = function (opts, cb) { function distTag (args, cb) { var cmd = args.shift() switch (cmd) { - case "add": case "a": case "set": case "s": + case 'add': case 'a': case 'set': case 's': return add(args[0], args[1], cb) - case "rm": case "r": case "del": case "d": case "remove": + case 'rm': case 'r': case 'del': case 'd': case 'remove': return remove(args[1], args[0], cb) - case "ls": case "l": case "sl": case "list": + case 'ls': case 'l': case 'sl': case 'list': return list(args[0], cb) default: - return cb("Usage:\n"+distTag.usage) + return cb('Usage:\n' + distTag.usage) } } function add (spec, tag, cb) { - var thing = npa(spec || "") + var thing = npa(spec || '') var pkg = thing.name var version = thing.rawSpec - var t = (tag || npm.config.get("tag")).trim() + var t = (tag || npm.config.get('tag')).trim() - log.verbose("dist-tag add", t, "to", pkg+"@"+version) + log.verbose('dist-tag add', t, 'to', pkg + '@' + version) - if (!pkg || !version || !t) return cb("Usage:\n"+distTag.usage) + if (!pkg || !version || !t) return cb('Usage:\n' + distTag.usage) if (semver.validRange(t)) { - var er = new Error("Tag name must not be a valid SemVer range: " + t) + var er = new Error('Tag name must not be a valid SemVer range: ' + t) return cb(er) } @@ -57,23 +57,23 @@ function add (spec, tag, cb) { if (er) return cb(er) if (tags[t] === version) { - log.warn("dist-tag add", t, "is already set to version", version) + log.warn('dist-tag add', t, 'is already set to version', version) return cb() } tags[t] = version mapToRegistry(pkg, npm.config, function (er, uri, auth, base) { var params = { - package : pkg, - distTag : t, - version : version, - auth : auth + 'package': pkg, + distTag: t, + version: version, + auth: auth } npm.registry.distTags.add(base, params, function (er) { if (er) return cb(er) - console.log("+"+t+": "+pkg+"@"+version) + console.log('+' + t + ': ' + pkg + '@' + version) cb() }) }) @@ -81,14 +81,14 @@ function add (spec, tag, cb) { } function remove (tag, pkg, cb) { - log.verbose("dist-tag del", tag, "from", pkg) + log.verbose('dist-tag del', tag, 'from', pkg) fetchTags(pkg, function (er, tags) { if (er) return cb(er) if (!tags[tag]) { - log.info("dist-tag del", tag, "is not a dist-tag on", pkg) - return cb(new Error(tag+" is not a dist-tag on "+pkg)) + log.info('dist-tag del', tag, 'is not a dist-tag on', pkg) + return cb(new Error(tag + ' is not a dist-tag on ' + pkg)) } var version = tags[tag] @@ -96,15 +96,15 @@ function remove (tag, pkg, cb) { mapToRegistry(pkg, npm.config, function (er, uri, auth, base) { var params = { - package : pkg, - distTag : tag, - auth : auth + 'package': pkg, + distTag: tag, + auth: auth } npm.registry.distTags.rm(base, params, function (er) { if (er) return cb(er) - console.log("-"+tag+": "+pkg+"@"+version) + console.log('-' + tag + ': ' + pkg + '@' + version) cb() }) }) @@ -112,20 +112,22 @@ function remove (tag, pkg, cb) { } function list (pkg, cb) { - if (!pkg) return readLocalPkg(function (er, pkg) { - if (er) return cb(er) - if (!pkg) return cb(distTag.usage) - list(pkg, cb) - }) + if (!pkg) { + return readLocalPkg(function (er, pkg) { + if (er) return cb(er) + if (!pkg) return cb(distTag.usage) + list(pkg, cb) + }) + } fetchTags(pkg, function (er, tags) { if (er) { - log.error("dist-tag ls", "Couldn't get dist-tag data for", pkg) + log.error('dist-tag ls', "Couldn't get dist-tag data for", pkg) return cb(er) } var msg = Object.keys(tags).map(function (k) { - return k+": "+tags[k] - }).sort().join("\n") + return k + ': ' + tags[k] + }).sort().join('\n') console.log(msg) cb(er, tags) }) @@ -136,13 +138,13 @@ function fetchTags (pkg, cb) { if (er) return cb(er) var params = { - package : pkg, - auth : auth + 'package': pkg, + auth: auth } npm.registry.distTags.fetch(base, params, function (er, tags) { if (er) return cb(er) if (!tags || !Object.keys(tags).length) { - return cb(new Error("No dist-tags found for " + pkg)) + return cb(new Error('No dist-tags found for ' + pkg)) } cb(null, tags) diff --git a/lib/docs.js b/lib/docs.js index e28fb3e7f..ea4bd5610 100644 --- a/lib/docs.js +++ b/lib/docs.js @@ -1,15 +1,12 @@ module.exports = docs -docs.usage = "npm docs <pkgname>" - + "\nnpm docs ." +docs.usage = 'npm docs <pkgname>' + + '\nnpm docs .' - -var npm = require("./npm.js") - , opener = require("opener") - , path = require("path") - , log = require("npmlog") - , mapToRegistry = require("./utils/map-to-registry.js") - , fetchPackageMetadata = require("./fetch-package-metadata.js") +var npm = require('./npm.js') +var opener = require('opener') +var log = require('npmlog') +var fetchPackageMetadata = require('./fetch-package-metadata.js') docs.completion = function (opts, cb) { // FIXME: there used to be registry completion here, but it stopped making @@ -17,13 +14,12 @@ docs.completion = function (opts, cb) { cb() } - function docs (args, cb) { - if (!args || !args.length) args = ["."] + if (!args || !args.length) args = ['.'] var pending = args.length - log.silly("docs",args) - args.forEach(function(proj) { - getDoc(proj, function(err) { + log.silly('docs', args) + args.forEach(function (proj) { + getDoc(proj, function (err) { if (err) { return cb(err) } @@ -33,11 +29,11 @@ function docs (args, cb) { } function getDoc (project, cb) { - log.silly("getDoc", project) - fetchPackageMetadata(project, ".", function (er, d) { + log.silly('getDoc', project) + fetchPackageMetadata(project, '.', function (er, d) { if (er) return cb(er) var url = d.homepage - if (! url) url = "https://www.npmjs.org/package/" + d.name - return opener(url, {command: npm.config.get("browser")}, cb) + if (!url) url = 'https://www.npmjs.org/package/' + d.name + return opener(url, {command: npm.config.get('browser')}, cb) }) } diff --git a/lib/edit.js b/lib/edit.js index a504b10d1..155db6fd9 100644 --- a/lib/edit.js +++ b/lib/edit.js @@ -2,24 +2,27 @@ // open the package folder in the $EDITOR module.exports = edit -edit.usage = "npm edit <pkg>[@<version>]" +edit.usage = 'npm edit <pkg>[@<version>]' -edit.completion = require("./utils/completion/installed-shallow.js") +edit.completion = require('./utils/completion/installed-shallow.js') -var npm = require("./npm.js") - , path = require("path") - , fs = require("graceful-fs") - , editor = require("editor") +var npm = require('./npm.js') +var path = require('path') +var fs = require('graceful-fs') +var editor = require('editor') function edit (args, cb) { var p = args[0] if (args.length !== 1 || !p) return cb(edit.usage) - var e = npm.config.get("editor") - if (!e) return cb(new Error( - "No editor set. Set the 'editor' config, or $EDITOR environ.")) - p = p.split("/") - .join("/node_modules/") - .replace(/(\/node_modules)+/, "/node_modules") + var e = npm.config.get('editor') + if (!e) { + return cb(new Error( + "No editor set. Set the 'editor' config, or $EDITOR environ." + )) + } + p = p.split('/') + .join('/node_modules/') + .replace(/(\/node_modules)+/, '/node_modules') var f = path.resolve(npm.dir, p) fs.lstat(f, function (er) { if (er) return cb(er) diff --git a/lib/explore.js b/lib/explore.js index 452be6d72..105ff84cc 100644 --- a/lib/explore.js +++ b/lib/explore.js @@ -3,32 +3,38 @@ module.exports = explore explore.usage = 'npm explore <pkg> [ -- <cmd>]' -explore.completion = require("./utils/completion/installed-shallow.js") +explore.completion = require('./utils/completion/installed-shallow.js') -var npm = require("./npm.js") - , spawn = require("./utils/spawn") - , path = require("path") - , fs = require("graceful-fs") - , log = require("npmlog") +var npm = require('./npm.js') +var spawn = require('./utils/spawn') +var path = require('path') +var fs = require('graceful-fs') function explore (args, cb) { if (args.length < 1 || !args[0]) return cb(explore.usage) var p = args.shift() - args = args.join(" ").trim() - if (args) args = ["-c", args] + args = args.join(' ').trim() + if (args) args = ['-c', args] else args = [] var cwd = path.resolve(npm.dir, p) - var sh = npm.config.get("shell") + var sh = npm.config.get('shell') fs.stat(cwd, function (er, s) { - if (er || !s.isDirectory()) return cb(new Error( - "It doesn't look like "+p+" is installed.")) - if (!args.length) console.log( - "\nExploring "+cwd+"\n"+ - "Type 'exit' or ^D when finished\n") + if (er || !s.isDirectory()) { + return cb(new Error( + "It doesn't look like " + p + ' is installed.' + )) + } - var shell = spawn(sh, args, { cwd: cwd, stdio: "inherit" }) - shell.on("close", function (er) { + if (!args.length) { + console.log( + '\nExploring ' + cwd + '\n' + + "Type 'exit' or ^D when finished\n" + ) + } + + var shell = spawn(sh, args, { cwd: cwd, stdio: 'inherit' }) + shell.on('close', function (er) { // only fail if non-interactive. if (!args.length) return cb() cb(er) diff --git a/lib/faq.js b/lib/faq.js index 912db0072..c9d88d301 100644 --- a/lib/faq.js +++ b/lib/faq.js @@ -1,8 +1,7 @@ - module.exports = faq -faq.usage = "npm faq" +faq.usage = 'npm faq' -var npm = require("./npm.js") +var npm = require('./npm.js') -function faq (args, cb) { npm.commands.help(["faq"], cb) } +function faq (args, cb) { npm.commands.help(['faq'], cb) } diff --git a/lib/fetch-package-metadata.js b/lib/fetch-package-metadata.js index 98ad9bb3f..049dfb25f 100644 --- a/lib/fetch-package-metadata.js +++ b/lib/fetch-package-metadata.js @@ -164,8 +164,7 @@ module.exports.addShrinkwrap = function addShrinkwrap (pkg, next) { if (er.code === 'ENOTTARBALL') { pkg._shrinkwrap = null return next() - } - else { + } else { return next(er) } } @@ -273,11 +272,9 @@ function untarStream (tarball, cb) { file.on('data', function OD (c) { if (hasGzipHeader(c)) { doGunzip() - } - else if (hasTarHeader(c)) { + } else if (hasTarHeader(c)) { doUntar() - } - else { + } else { dispose(file) var er = new Error('Non-gzip/tarball ' + tarball) er.code = 'ENOTTARBALL' @@ -288,7 +285,7 @@ function untarStream (tarball, cb) { cb(null, stream) }) - function doGunzip() { + function doGunzip () { var gunzip = stream.pipe(zlib.createGunzip()) gunzip.on('error', function (er) { er = new Error('Error extracting ' + tarball + ' archive: ' + er.message) @@ -300,7 +297,7 @@ function untarStream (tarball, cb) { doUntar() } - function doUntar() { + function doUntar () { var untar = stream.pipe(tar.Parse()) untar.on('error', function (er) { er = new Error('Error extracting ' + tarball + ' archive: ' + er.message) @@ -312,7 +309,7 @@ function untarStream (tarball, cb) { addClose() } - function addClose() { + function addClose () { stream.close = function () { tounpipe.forEach(dispose) diff --git a/lib/get.js b/lib/get.js index aa058002e..8dc805ec5 100644 --- a/lib/get.js +++ b/lib/get.js @@ -1,12 +1,12 @@ module.exports = get -get.usage = "npm get <key> <value> (See `npm config`)" +get.usage = 'npm get <key> <value> (See `npm config`)' -var npm = require("./npm.js") +var npm = require('./npm.js') get.completion = npm.commands.config.completion function get (args, cb) { - npm.commands.config(["get"].concat(args), cb) + npm.commands.config(['get'].concat(args), cb) } diff --git a/lib/help-search.js b/lib/help-search.js index d8553453b..16f389027 100644 --- a/lib/help-search.js +++ b/lib/help-search.js @@ -1,29 +1,29 @@ module.exports = helpSearch -var fs = require("graceful-fs") - , path = require("path") - , asyncMap = require("slide").asyncMap - , npm = require("./npm.js") - , glob = require("glob") - , color = require("ansicolors") +var fs = require('graceful-fs') +var path = require('path') +var asyncMap = require('slide').asyncMap +var npm = require('./npm.js') +var glob = require('glob') +var color = require('ansicolors') -helpSearch.usage = "npm help-search <text>" +helpSearch.usage = 'npm help-search <text>' function helpSearch (args, silent, cb) { - if (typeof cb !== "function") cb = silent, silent = false + if (typeof cb !== 'function') { + cb = silent + silent = false + } if (!args.length) return cb(helpSearch.usage) - var docPath = path.resolve(__dirname, "..", "doc") - return glob(docPath + "/*/*.md", function (er, files) { - if (er) - return cb(er) + var docPath = path.resolve(__dirname, '..', 'doc') + return glob(docPath + '/*/*.md', function (er, files) { + if (er) return cb(er) readFiles(files, function (er, data) { - if (er) - return cb(er) + if (er) return cb(er) searchFiles(args, data, function (er, results) { - if (er) - return cb(er) + if (er) return cb(er) formatResults(args, results, cb) }) }) @@ -52,8 +52,7 @@ function searchFiles (args, files, cb) { for (var a = 0, l = args.length; a < l && !match; a++) { match = data.toLowerCase().indexOf(args[a].toLowerCase()) !== -1 } - if (!match) - return + if (!match) return var lines = data.split(/\n+/) @@ -61,14 +60,14 @@ function searchFiles (args, files, cb) { // if the next line has a search term, then skip all 3 // otherwise, set the line to null. then remove the nulls. l = lines.length - for (var i = 0; i < l; i ++) { + for (var i = 0; i < l; i++) { var line = lines[i] - , nextLine = lines[i + 1] - , ll + var nextLine = lines[i + 1] + var ll match = false if (nextLine) { - for (a = 0, ll = args.length; a < ll && !match; a ++) { + for (a = 0, ll = args.length; a < ll && !match; a++) { match = nextLine.toLowerCase() .indexOf(args[a].toLowerCase()) !== -1 } @@ -80,12 +79,12 @@ function searchFiles (args, files, cb) { } match = false - for (a = 0, ll = args.length; a < ll && !match; a ++) { + for (a = 0, ll = args.length; a < ll && !match; a++) { match = line.toLowerCase().indexOf(args[a].toLowerCase()) !== -1 } if (match) { // skip over the next line - i ++ + i++ continue } @@ -94,7 +93,7 @@ function searchFiles (args, files, cb) { // now squish any string of nulls into a single null lines = lines.reduce(function (l, r) { - if (!(r === null && l[l.length-1] === null)) l.push(r) + if (!(r === null && l[l.length - 1] === null)) l.push(r) return l }, []) @@ -103,10 +102,10 @@ function searchFiles (args, files, cb) { // now see how many args were found at all. var found = {} - , totalHits = 0 + var totalHits = 0 lines.forEach(function (line) { args.forEach(function (arg) { - var hit = (line || "").toLowerCase() + var hit = (line || '').toLowerCase() .split(arg.toLowerCase()).length - 1 if (hit > 0) { found[arg] = (found[arg] || 0) + hit @@ -115,27 +114,28 @@ function searchFiles (args, files, cb) { }) }) - var cmd = "npm help " - if (path.basename(path.dirname(file)) === "api") { - cmd = "npm apihelp " + var cmd = 'npm help ' + if (path.basename(path.dirname(file)) === 'api') { + cmd = 'npm apihelp ' } - cmd += path.basename(file, ".md").replace(/^npm-/, "") - results.push({ file: file - , cmd: cmd - , lines: lines - , found: Object.keys(found) - , hits: found - , totalHits: totalHits - }) + cmd += path.basename(file, '.md').replace(/^npm-/, '') + results.push({ + file: file, + cmd: cmd, + lines: lines, + found: Object.keys(found), + hits: found, + totalHits: totalHits + }) }) // if only one result, then just show that help section. if (results.length === 1) { - return npm.commands.help([results[0].file.replace(/\.md$/, "")], cb) + return npm.commands.help([results[0].file.replace(/\.md$/, '')], cb) } if (results.length === 0) { - console.log("No results for " + args.map(JSON.stringify).join(" ")) + console.log('No results for ' + args.map(JSON.stringify).join(' ')) return cb() } @@ -161,25 +161,25 @@ function formatResults (args, results, cb) { var out = results.map(function (res) { var out = res.cmd - , r = Object.keys(res.hits).map(function (k) { - return k + ":" + res.hits[k] + var r = Object.keys(res.hits).map(function (k) { + return k + ':' + res.hits[k] }).sort(function (a, b) { return a > b ? 1 : -1 - }).join(" ") + }).join(' ') out += ((new Array(Math.max(1, cols - out.length - r.length))) - .join(" ")) + r + .join(' ')) + r - if (!npm.config.get("long")) return out + if (!npm.config.get('long')) return out - out = "\n\n" + out - + "\n" + (new Array(cols)).join("—") + "\n" - + res.lines.map(function (line, i) { - if (line === null || i > 3) return "" - for (var out = line, a = 0, l = args.length; a < l; a ++) { + out = '\n\n' + out + '\n' + + (new Array(cols)).join('—') + '\n' + + res.lines.map(function (line, i) { + if (line === null || i > 3) return '' + for (var out = line, a = 0, l = args.length; a < l; a++) { var finder = out.toLowerCase().split(args[a].toLowerCase()) - , newOut = "" - , p = 0 + var newOut = '' + var p = 0 finder.forEach(function (f) { newOut += out.substr(p, f.length) @@ -193,16 +193,16 @@ function formatResults (args, results, cb) { } return newOut - }).join("\n").trim() + }).join('\n').trim() return out - }).join("\n") - - if (results.length && !npm.config.get("long")) { - out = "Top hits for "+(args.map(JSON.stringify).join(" ")) - + "\n" + (new Array(cols)).join("—") + "\n" - + out - + "\n" + (new Array(cols)).join("—") + "\n" - + "(run with -l or --long to see more context)" + }).join('\n') + + if (results.length && !npm.config.get('long')) { + out = 'Top hits for ' + (args.map(JSON.stringify).join(' ')) + '\n' + + (new Array(cols)).join('—') + '\n' + + out + '\n' + + (new Array(cols)).join('—') + '\n' + + '(run with -l or --long to see more context)' } console.log(out.trim()) diff --git a/lib/help.js b/lib/help.js index 481a07169..a954ae814 100644 --- a/lib/help.js +++ b/lib/help.js @@ -6,15 +6,15 @@ help.completion = function (opts, cb) { getSections(cb) } -var path = require("path") - , spawn = require("./utils/spawn") - , npm = require("./npm.js") - , log = require("npmlog") - , opener = require("opener") - , glob = require("glob") +var path = require('path') +var spawn = require('./utils/spawn') +var npm = require('./npm.js') +var log = require('npmlog') +var opener = require('opener') +var glob = require('glob') function help (args, cb) { - var argv = npm.config.get("argv").cooked + var argv = npm.config.get('argv').cooked var argnum = 0 if (args.length === 2 && ~~args[0]) { @@ -23,54 +23,53 @@ function help (args, cb) { // npm help foo bar baz: search topics if (args.length > 1 && args[0]) { - return npm.commands["help-search"](args, argnum, cb) + return npm.commands['help-search'](args, argnum, cb) } var section = npm.deref(args[0]) || args[0] // npm help <noargs>: show basic usage if (!section) { - var valid = argv[0] === "help" ? 0 : 1 + var valid = argv[0] === 'help' ? 0 : 1 return npmUsage(valid, cb) } - // npm <cmd> -h: show command usage - if ( npm.config.get("usage") - && npm.commands[section] - && npm.commands[section].usage - ) { - npm.config.set("loglevel", "silent") - log.level = "silent" + if (npm.config.get('usage') && + npm.commands[section] && + npm.commands[section].usage) { + npm.config.set('loglevel', 'silent') + log.level = 'silent' console.log(npm.commands[section].usage) return cb() } // npm apihelp <section>: Prefer section 3 over section 1 - var apihelp = argv.length && -1 !== argv[0].indexOf("api") + var apihelp = argv.length && argv[0].indexOf('api') !== -1 var pref = apihelp ? [3, 1, 5, 7] : [1, 3, 5, 7] - if (argnum) + if (argnum) { pref = [ argnum ].concat(pref.filter(function (n) { return n !== argnum })) + } // npm help <section>: Try to find the path - var manroot = path.resolve(__dirname, "..", "man") + var manroot = path.resolve(__dirname, '..', 'man') // legacy - if (section === "global") section = "folders" - else if (section === "json") section = "package.json" + if (section === 'global') section = 'folders' + else if (section === 'json') section = 'package.json' // find either /section.n or /npm-section.n // The glob is used in the glob. The regexp is used much // further down. Globs and regexps are different - var compextglob = ".+(gz|bz2|lzma|[FYzZ]|xz)" - var compextre = "\\.(gz|bz2|lzma|[FYzZ]|xz)$" - var f = "+(npm-" + section + "|" + section + ").[0-9]?(" + compextglob + ")" - return glob(manroot + "/*/" + f, function (er, mans) { + var compextglob = '.+(gz|bz2|lzma|[FYzZ]|xz)' + var compextre = '\\.(gz|bz2|lzma|[FYzZ]|xz)$' + var f = '+(npm-' + section + '|' + section + ').[0-9]?(' + compextglob + ')' + return glob(manroot + '/*/' + f, function (er, mans) { if (er) return cb(er) - if (!mans.length) return npm.commands["help-search"](args, cb) + if (!mans.length) return npm.commands['help-search'](args, cb) mans = mans.map(function (man) { var ext = path.extname(man) @@ -102,83 +101,83 @@ function pickMan (mans, pref_) { function viewMan (man, cb) { var nre = /([0-9]+)$/ var num = man.match(nre)[1] - var section = path.basename(man, "." + num) + var section = path.basename(man, '.' + num) // at this point, we know that the specified man page exists - var manpath = path.join(__dirname, "..", "man") - , env = {} + var manpath = path.join(__dirname, '..', 'man') + var env = {} Object.keys(process.env).forEach(function (i) { env[i] = process.env[i] }) env.MANPATH = manpath - var viewer = npm.config.get("viewer") + var viewer = npm.config.get('viewer') var conf switch (viewer) { - case "woman": - var a = ["-e", "(woman-find-file \"" + man + "\")"] - conf = { env: env, stdio: "inherit" } - var woman = spawn("emacsclient", a, conf) - woman.on("close", cb) + case 'woman': + var a = ['-e', '(woman-find-file \'' + man + '\')'] + conf = { env: env, stdio: 'inherit' } + var woman = spawn('emacsclient', a, conf) + woman.on('close', cb) break - case "browser": - opener(htmlMan(man), { command: npm.config.get("browser") }, cb) + case 'browser': + opener(htmlMan(man), { command: npm.config.get('browser') }, cb) break default: - conf = { env: env, stdio: "inherit" } - var manProcess = spawn("man", [num, section], conf) - manProcess.on("close", cb) + conf = { env: env, stdio: 'inherit' } + var manProcess = spawn('man', [num, section], conf) + manProcess.on('close', cb) break } } function htmlMan (man) { var sect = +man.match(/([0-9]+)$/)[1] - var f = path.basename(man).replace(/([0-9]+)$/, "html") + var f = path.basename(man).replace(/([0-9]+)$/, 'html') switch (sect) { case 1: - sect = "cli" + sect = 'cli' break case 3: - sect = "api" + sect = 'api' break case 5: - sect = "files" + sect = 'files' break case 7: - sect = "misc" + sect = 'misc' break default: - throw new Error("invalid man section: " + sect) + throw new Error('invalid man section: ' + sect) } - return path.resolve(__dirname, "..", "html", "doc", sect, f) + return path.resolve(__dirname, '..', 'html', 'doc', sect, f) } function npmUsage (valid, cb) { - npm.config.set("loglevel", "silent") - log.level = "silent" - console.log( - [ "\nUsage: npm <command>" - , "" - , "where <command> is one of:" - , npm.config.get("long") ? usages() - : " " + wrap(Object.keys(npm.commands)) - , "" - , "npm <cmd> -h quick help on <cmd>" - , "npm -l display full usage info" - , "npm faq commonly asked questions" - , "npm help <term> search for help on <term>" - , "npm help npm involved overview" - , "" - , "Specify configs in the ini-formatted file:" - , " " + npm.config.get("userconfig") - , "or on the command line via: npm <command> --key value" - , "Config info can be viewed via: npm help config" - , "" - , "npm@" + npm.version + " " + path.dirname(__dirname) - ].join("\n")) + npm.config.set('loglevel', 'silent') + log.level = 'silent' + console.log([ + '\nUsage: npm <command>', + '', + 'where <command> is one of:', + npm.config.get('long') ? usages() + : ' ' + wrap(Object.keys(npm.commands)), + '', + 'npm <cmd> -h quick help on <cmd>', + 'npm -l display full usage info', + 'npm faq commonly asked questions', + 'npm help <term> search for help on <term>', + 'npm help npm involved overview', + '', + 'Specify configs in the ini-formatted file:', + ' ' + npm.config.get('userconfig'), + 'or on the command line via: npm <command> --key value', + 'Config info can be viewed via: npm help config', + '', + 'npm@' + npm.version + ' ' + path.dirname(__dirname) + ].join('\n')) cb(valid) } @@ -188,50 +187,50 @@ function usages () { return Object.keys(npm.commands).filter(function (c) { return c === npm.deref(c) }).reduce(function (set, c) { - set.push([c, npm.commands[c].usage || ""]) + set.push([c, npm.commands[c].usage || '']) maxLen = Math.max(maxLen, c.length) return set }, []).map(function (item) { var c = item[0] - , usage = item[1] - return "\n " + c + (new Array(maxLen - c.length + 2).join(" ")) - + (usage.split("\n") - .join("\n" + (new Array(maxLen + 6).join(" ")))) - }).join("\n") + var usage = item[1] + return '\n ' + + c + (new Array(maxLen - c.length + 2).join(' ')) + + (usage.split('\n').join('\n' + (new Array(maxLen + 6).join(' ')))) + }).join('\n') } - function wrap (arr) { - var out = [""] - , l = 0 - , line + var out = [''] + var l = 0 + var line line = process.stdout.columns - if (!line) + if (!line) { line = 60 - else + } else { line = Math.min(60, Math.max(line - 16, 24)) + } - arr.sort(function (a,b) { return a<b?-1:1 }) + arr.sort(function (a, b) { return a < b ? -1 : 1 }) .forEach(function (c) { if (out[l].length + c.length + 2 < line) { - out[l] += ", "+c + out[l] += ', ' + c } else { - out[l++] += "," + out[l++] += ',' out[l] = c } }) - return out.join("\n ").substr(2) + return out.join('\n ').substr(2) } function getSections (cb) { - var g = path.resolve(__dirname, "../man/man[0-9]/*.[0-9]") + var g = path.resolve(__dirname, '../man/man[0-9]/*.[0-9]') glob(g, function (er, files) { - if (er) - return cb(er) + if (er) return cb(er) + cb(null, Object.keys(files.reduce(function (acc, file) { - file = path.basename(file).replace(/\.[0-9]+$/, "") - file = file.replace(/^npm-/, "") + file = path.basename(file).replace(/\.[0-9]+$/, '') + file = file.replace(/^npm-/, '') acc[file] = true return acc }, { help: true }))) diff --git a/lib/init.js b/lib/init.js index c4fe80735..e3eb3d40d 100644 --- a/lib/init.js +++ b/lib/init.js @@ -1,40 +1,39 @@ - // initialize a package.json file module.exports = init -var log = require("npmlog") - , npm = require("./npm.js") - , initJson = require("init-package-json") +var log = require('npmlog') +var npm = require('./npm.js') +var initJson = require('init-package-json') -init.usage = "npm init [--force|-f|--yes|-y]" +init.usage = 'npm init [--force|-f|--yes|-y]' function init (args, cb) { var dir = process.cwd() log.pause() - var initFile = npm.config.get("init-module") + var initFile = npm.config.get('init-module') if (!initJson.yes(npm.config)) { - console.log( - ["This utility will walk you through creating a package.json file." - ,"It only covers the most common items, and tries to guess sensible defaults." - ,"" - ,"See `npm help json` for definitive documentation on these fields" - ,"and exactly what they do." - ,"" - ,"Use `npm install <pkg> --save` afterwards to install a package and" - ,"save it as a dependency in the package.json file." - ,"" - ,"Press ^C at any time to quit." - ].join("\n")) + console.log([ + 'This utility will walk you through creating a package.json file.', + 'It only covers the most common items, and tries to guess sensible defaults.', + '', + 'See `npm help json` for definitive documentation on these fields', + 'and exactly what they do.', + '', + 'Use `npm install <pkg> --save` afterwards to install a package and', + 'save it as a dependency in the package.json file.', + '', + 'Press ^C at any time to quit.' + ].join('\n')) } initJson(dir, initFile, npm.config, function (er, data) { log.resume() - log.silly("package data", data) - if (er && er.message === "canceled") { - log.warn("init", "canceled") + log.silly('package data', data) + if (er && er.message === 'canceled') { + log.warn('init', 'canceled') return cb(null, data) } - log.info("init", "written successfully") + log.info('init', 'written successfully') cb(er, data) }) } diff --git a/lib/install.js b/lib/install.js index 350b54c7a..d2e1e6e42 100644 --- a/lib/install.js +++ b/lib/install.js @@ -399,8 +399,7 @@ Installer.prototype.computeLinked = function (cb) { function safeJSONparse (data) { try { return JSON.parse(data) - } - catch (ex) { + } catch (ex) { return } } @@ -455,8 +454,7 @@ Installer.prototype.executeActions = function (cb) { chain(steps, function (er) { if (!er || self.rollback) { rimraf(staging, function () { cb(er) }) - } - else { + } else { cb(er) } }) diff --git a/lib/install/action/move.js b/lib/install/action/move.js index 841fbc155..57aa5f7fb 100644 --- a/lib/install/action/move.js +++ b/lib/install/action/move.js @@ -5,7 +5,6 @@ var chain = require('slide').chain var iferr = require('iferr') var rimraf = require('rimraf') var mkdirp = require('mkdirp') -var npm = require('../../npm.js') var rmStuff = require('../../unbuild.js').rmStuff var lifecycle = require('../../utils/lifecycle.js') var updatePackageJson = require('../update-package-json') @@ -33,12 +32,12 @@ function noerrors () { if (er) { log.warn('move', er) } - cb.apply(null, a) + cb.apply(null, args) }) } module.exports.rollback = function (buildpath, pkg, next) { - chian([ + chain([ [noerrors, mkdirp, path.resolve(pkg.fromPath, '..')], [noerrors, lifecycle, pkg.package, 'preuninstall', pkg.path, false, true], [noerrors, lifecycle, pkg.package, 'uninstall', pkg.path, false, true], @@ -47,7 +46,7 @@ module.exports.rollback = function (buildpath, pkg, next) { [noerrors, moveModuleOnly, pkg.path, pkg.fromPath], [noerrors, lifecycle, pkg.package, 'preinstall', pkg.fromPath, false, true], [noerrors, removeEmptyParents, path.resolve(pkg.path, '..')], - [noerrors, updatePackageJson, pkg, pkg.fromPath], + [noerrors, updatePackageJson, pkg, pkg.fromPath] ], next) } diff --git a/lib/install/actions.js b/lib/install/actions.js index f425efd65..a19cb1cb1 100644 --- a/lib/install/actions.js +++ b/lib/install/actions.js @@ -26,7 +26,6 @@ actions['update-linked'] = require('./action/update-linked.js') actions['global-install'] = require('./action/global-install.js') actions['global-link'] = require('./action/global-link.js') - // FIXME: We wrap actions like three ways to sunday here. // Rewrite this to only work one way. @@ -44,19 +43,19 @@ Object.keys(actions).forEach(function (actionName) { } }) -function andHandleOptionalDepErrors(pkg, next) { +function andHandleOptionalDepErrors (pkg, next) { return function (er) { if (!er) return next.apply(null, arguments) pkg.failed = true var anyFatal = pkg.directlyRequested || !pkg.parent - for (var ii=0; ii < pkg.requiredBy.length; ++ii) { + for (var ii = 0; ii < pkg.requiredBy.length; ++ii) { var parent = pkg.requiredBy[ii] var isFatal = failedDependency(parent, pkg) if (isFatal) anyFatal = true } if (anyFatal) return next.apply(null, arguments) - log.warn('install:'+pkg.package.name, "Couldn't install optional dependency:", er.message) - log.verbose('install:'+pkg.package.name, er.stack) + log.warn('install:' + pkg.package.name, "Couldn't install optional dependency:", er.message) + log.verbose('install:' + pkg.package.name, er.stack) next() } } diff --git a/lib/install/decompose-actions.js b/lib/install/decompose-actions.js index 2921fccba..b345ba5d0 100644 --- a/lib/install/decompose-actions.js +++ b/lib/install/decompose-actions.js @@ -1,9 +1,6 @@ 'use strict' -var fs = require('fs') -var path = require('path') var validate = require('aproba') var asyncMap = require('slide').asyncMap -var npm = require('../npm.js') module.exports = function (differences, decomposed, next) { validate('AAF', arguments) @@ -26,7 +23,7 @@ module.exports = function (differences, decomposed, next) { }, next) } -function addSteps(decomposed, pkg, done) { +function addSteps (decomposed, pkg, done) { decomposed.push(['fetch', pkg]) decomposed.push(['extract', pkg]) decomposed.push(['preinstall', pkg]) @@ -38,7 +35,7 @@ function addSteps(decomposed, pkg, done) { done() } -function moveSteps(decomposed, pkg, done) { +function moveSteps (decomposed, pkg, done) { decomposed.push(['move', pkg]) decomposed.push(['build', pkg]) decomposed.push(['install', pkg]) @@ -47,7 +44,7 @@ function moveSteps(decomposed, pkg, done) { done() } -function defaultSteps(decomposed, cmd, pkg, done) { +function defaultSteps (decomposed, cmd, pkg, done) { decomposed.push([cmd, pkg]) done() } diff --git a/lib/install/deps.js b/lib/install/deps.js index 98c094846..20b7eb30f 100644 --- a/lib/install/deps.js +++ b/lib/install/deps.js @@ -1,7 +1,7 @@ 'use strict' var assert = require('assert') -var fs = require('graceful-fs') var path = require('path') +var url = require('url') var semver = require('semver') var asyncMap = require('slide').asyncMap var chain = require('slide').chain @@ -42,23 +42,23 @@ function isDevDep (tree, name) { var devDeps = tree.package.devDependencies || {} var reqVer = devDeps[name] if (reqVer == null) return - return npa(name + "@" + reqVer) + return npa(name + '@' + reqVer) } function isProdDep (tree, name) { var deps = tree.package.dependencies || {} var reqVer = deps[name] if (reqVer == null) return false - return npa(name + "@" + reqVer) + return npa(name + '@' + reqVer) } var registryTypes = { range: true, version: true } -function doesChildVersionMatch(child, requested) { +function doesChildVersionMatch (child, requested) { if (child.fromShrinkwrap) return true var childReq = child.package._requested if (childReq) { - if (childReq.rawSpec == requested.rawSpec) return true + if (childReq.rawSpec === requested.rawSpec) return true if (childReq.type === requested.type && childReq.spec === requested.spec) return true } if (!registryTypes[requested.type]) return requested.rawSpec === child.package._from @@ -86,11 +86,6 @@ var recalculateMetadata = exports.recalculateMetadata = function (tree, log, nex } }) } - function deptospec (deps) { - return function (depname) { - return depname + '@' + deps[depname] - } - } function specs (deps) { return Object.keys(deps).map(function (depname) { return depname + '@' + deps[depname] }) } @@ -105,19 +100,15 @@ var recalculateMetadata = exports.recalculateMetadata = function (tree, log, nex ], function () { next(null, tree) }) } -function addRequiredDep(tree, child) { +function addRequiredDep (tree, child) { if (!isDep(tree, child)) return false - var name = isProdDep(tree, child.package.name) ? flatNameFromTree(tree) : "#DEV:"+flatNameFromTree(tree) + var name = isProdDep(tree, child.package.name) ? flatNameFromTree(tree) : '#DEV:' + flatNameFromTree(tree) child.package._requiredBy = union(child.package._requiredBy || [], [name]) child.requiredBy = union(child.requiredBy || [], [tree]) return true } -function matchingChild(tree, name) { - var matches = tree.children.filter(function (child) { return child.package.name === name }) - return matches[0] -} -function matchingDep(tree, name) { +function matchingDep (tree, name) { if (tree.package.dependencies[name]) return tree.package.dependencies[name] if (tree.package.devDependencies && tree.package.devDependencies[name]) return tree.package.devDependencies[name] return @@ -129,7 +120,7 @@ function packageRelativePath (tree) { return isLocal ? requested.spec : tree.path } -function getShrinkwrap(tree, name) { +function getShrinkwrap (tree, name) { return tree.package._shrinkwrap && tree.package._shrinkwrap.dependencies && tree.package._shrinkwrap.dependencies[name] } @@ -176,7 +167,7 @@ exports.loadRequestedDeps = function (args, tree, saveToDependencies, log, next) // For things the user asked to install, that aren't a dependency (or // won't be when we're done), flag it as "depending" on the user // themselves, so we don't remove it as a dep that no longer exists - if (! addRequiredDep(tree, child)) { + if (!addRequiredDep(tree, child)) { child.package._requiredBy = union(child.package._requiredBy, ['#USER']) child.directlyRequested = true } @@ -250,7 +241,7 @@ var failedDependency = exports.failedDependency = function (tree, name_pkg) { if (!tree.parent) return true - for (var ii=0; ii<tree.requiredBy.length; ++ii) { + for (var ii = 0; ii < tree.requiredBy.length; ++ii) { var requireParent = tree.requiredBy[ii] if (failedDependency(requireParent, tree.package)) { return true @@ -265,7 +256,7 @@ function andHandleOptionalErrors (log, tree, name, done) { validate('EOO', [er, child, childLog]) if (!er) return done(er, child, childLog) var isFatal = failedDependency(tree, name) - if (er && ! isFatal) { + if (er && !isFatal) { tree.children = tree.children.filter(function (child) { return child.package.name !== name }) log.warn('install', "Couldn't install optional dependency:", er.message) log.verbose('install', er.stack) @@ -420,7 +411,7 @@ var validatePeerDeps = exports.validatePeerDeps = function (tree, onInvalid) { if (!tree.package.peerDependencies) return Object.keys(tree.package.peerDependencies).forEach(function (pkgname) { var version = tree.package.peerDependencies[pkgname] - var match = findRequirement(tree, pkgname, npa(pkgname + "@" + version)) + var match = findRequirement(tree, pkgname, npa(pkgname + '@' + version)) if (!match) onInvalid(tree, pkgname, version) }) } @@ -439,7 +430,7 @@ var findRequirement = exports.findRequirement = function (tree, name, requested) return child.package.name === name && child.parent } var versionMatch = function (child) { - return doesChildVersionMatch(child, requested) + return doesChildVersionMatch(child, requested) } if (nameMatch(tree)) { // this *is* the module, but it doesn't match the version, so a diff --git a/lib/install/diff-trees.js b/lib/install/diff-trees.js index 3363e33c5..e52d950bf 100644 --- a/lib/install/diff-trees.js +++ b/lib/install/diff-trees.js @@ -62,7 +62,6 @@ function requiredByAllLinked (node) { var sortActions = module.exports.sortActions = function (differences) { var actions = {} differences.forEach(function (action) { - var cmd = action[0] var child = action[1] actions[child.package._location] = action }) @@ -107,16 +106,15 @@ function diffTrees (oldTree, newTree) { Object.keys(flatNewTree).forEach(function (path) { var pkg = flatNewTree[path] pkg.oldPkg = flatOldTree[path] - pkg.isInLink = (pkg.oldPkg && isLink(pkg.oldPkg.parent)) - || (pkg.parent && isLink(pkg.parent)) - || requiredByAllLinked(pkg) + pkg.isInLink = (pkg.oldPkg && isLink(pkg.oldPkg.parent)) || + (pkg.parent && isLink(pkg.parent)) || + requiredByAllLinked(pkg) if (pkg.fromBundle) return if (pkg.oldPkg) { if (!pkg.directlyRequested && pkgAreEquiv(pkg.oldPkg.package, pkg.package)) return if (!pkg.isInLink && (isLink(pkg.oldPkg) || isLink(pkg))) { differences.push(['update-linked', pkg]) - } - else { + } else { differences.push(['update', pkg]) } } else { diff --git a/lib/install/filter-invalid-actions.js b/lib/install/filter-invalid-actions.js index 311a60863..e844e0a3f 100644 --- a/lib/install/filter-invalid-actions.js +++ b/lib/install/filter-invalid-actions.js @@ -7,17 +7,17 @@ module.exports = function (top, differences, next) { validate('SAF', arguments) var action var keep = [] + /*eslint no-cond-assign:0*/ while (action = differences.shift()) { var cmd = action[0] var pkg = action[1] if (pkg.isInLink || pkg.parent.target) { log.warn('skippingAction', 'Module is inside a symlinked module: not running ' + cmd + ' ' + pkg.package._id + ' ' + path.relative(top, pkg.path)) - } - else { + } else { keep.push(action) } } differences.push.apply(differences, keep) next() -}
\ No newline at end of file +} diff --git a/lib/install/inflate-bundled.js b/lib/install/inflate-bundled.js index 913a05846..c27acd1dc 100644 --- a/lib/install/inflate-bundled.js +++ b/lib/install/inflate-bundled.js @@ -12,4 +12,4 @@ module.exports = function inflateBundled (parent, children) { child.isLink = child.isLink || parent.isLink || parent.target inflateBundled(child, child.children) }) -}
\ No newline at end of file +} diff --git a/lib/install/inflate-shrinkwrap.js b/lib/install/inflate-shrinkwrap.js index 128d44f57..dd32583f6 100644 --- a/lib/install/inflate-shrinkwrap.js +++ b/lib/install/inflate-shrinkwrap.js @@ -27,8 +27,8 @@ var inflateShrinkwrap = module.exports = function (tree, swdeps, finishInflating var child = onDisk[name] if (child && (child.fromShrinkwrap || (sw.resolved && child.package._resolved === sw.resolved) || - (sw.from && url.parse(sw.from).protocol && child.package._from == sw.from) || - child.package.version == sw.version)) { + (sw.from && url.parse(sw.from).protocol && child.package._from === sw.from) || + child.package.version === sw.version)) { if (!child.fromShrinkwrap) child.fromShrinkwrap = spec tree.children.push(child) return next() diff --git a/lib/install/logical-tree.js b/lib/install/logical-tree.js index f0faf6e78..1d9492bdf 100644 --- a/lib/install/logical-tree.js +++ b/lib/install/logical-tree.js @@ -4,7 +4,6 @@ var union = require('lodash.union') var without = require('lodash.without') var validate = require('aproba') var flattenTree = require('./flatten-tree.js') -var npm = require('../npm.js') var isExtraneous = require('./is-extraneous.js') var validateAllPeerDeps = require('./deps.js').validateAllPeerDeps @@ -21,7 +20,7 @@ var logicalTree = module.exports = function (tree) { var flat = flattenTree(newTree) function getNode (flatname) { - return flatname.substr(0,5) === '#DEV:' ? + return flatname.substr(0, 5) === '#DEV:' ? flat[flatname.substr(5)] : flat[flatname] } @@ -35,7 +34,7 @@ var logicalTree = module.exports = function (tree) { return parentNode.package.dependencies[node.package.name] || (parentNode.package.devDependencies && parentNode.package.devDependencies[node.package.name]) }) - var requiredBy = requiredByNames.map(getNode) + requiredBy = requiredByNames.map(getNode) node.requiredBy = requiredBy diff --git a/lib/install/prune-tree.js b/lib/install/prune-tree.js index 3a8e41d9f..eb3edf4f7 100644 --- a/lib/install/prune-tree.js +++ b/lib/install/prune-tree.js @@ -19,7 +19,7 @@ module.exports = function pruneTree (tree) { var child = flat[flatname] if (!child.parent) return child.package._requiredBy = (child.package._requiredBy || []).filter(function (req) { - var isDev = req.substr(0,4) === '#DEV' + var isDev = req.substr(0, 4) === '#DEV' if (req[0] === '#' && !isDev) return true if (flat[req]) return true if (!isDev) return false diff --git a/lib/install/save.js b/lib/install/save.js index 350480d66..9f649ccca 100644 --- a/lib/install/save.js +++ b/lib/install/save.js @@ -113,9 +113,9 @@ var getSaveType = exports.getSaveType = function (args) { validate('A', arguments) var nothingToSave = !args.length var globalInstall = npm.config.get('global') - var noSaveFlags = !npm.config.get('save') - && !npm.config.get('save-dev') - && !npm.config.get('save-optional') + var noSaveFlags = !npm.config.get('save') && + !npm.config.get('save-dev') && + !npm.config.get('save-optional') if (nothingToSave || globalInstall || noSaveFlags) return null if (npm.config.get('save-optional')) return 'optionalDependencies' @@ -127,7 +127,7 @@ function computeVersionSpec (child) { validate('O', arguments) var requested = child.package._requested if (!requested || requested.type === 'tag') { - requested = { + requested = { type: 'version', spec: child.package.version } diff --git a/lib/link.js b/lib/link.js index 7fe244977..b5d7f9d36 100644 --- a/lib/link.js +++ b/lib/link.js @@ -1,21 +1,21 @@ // link with no args: symlink the folder to the global location // link with package arg: symlink the global to the local -var npm = require("./npm.js") - , symlink = require("./utils/link.js") - , fs = require("graceful-fs") - , log = require("npmlog") - , asyncMap = require("slide").asyncMap - , chain = require("slide").chain - , path = require("path") - , build = require("./build.js") - , npa = require("npm-package-arg") +var npm = require('./npm.js') +var symlink = require('./utils/link.js') +var fs = require('graceful-fs') +var log = require('npmlog') +var asyncMap = require('slide').asyncMap +var chain = require('slide').chain +var path = require('path') +var build = require('./build.js') +var npa = require('npm-package-arg') module.exports = link -link.usage = "npm link (in package dir)" - + "\nnpm link [<@scope>/]<pkg>[@<version>]" - + "\n\nalias: npm ln" +link.usage = 'npm link (in package dir)' + + '\nnpm link [<@scope>/]<pkg>[@<version>]' + + '\n\nalias: npm ln' link.completion = function (opts, cb) { var dir = npm.globalDir @@ -27,33 +27,35 @@ link.completion = function (opts, cb) { } function link (args, cb) { - if (process.platform === "win32") { - var semver = require("semver") - if (!semver.satisfies(process.version, ">=0.7.9")) { - var msg = "npm link not supported on windows prior to node 0.7.9" - , e = new Error(msg) - e.code = "ENOTSUP" - e.errno = require("constants").ENOTSUP + if (process.platform === 'win32') { + var semver = require('semver') + if (!semver.satisfies(process.version, '>=0.7.9')) { + var msg = 'npm link not supported on windows prior to node 0.7.9' + var e = new Error(msg) + e.code = 'ENOTSUP' + e.errno = require('constants').ENOTSUP return cb(e) } } - if (npm.config.get("global")) { - return cb(new Error("link should never be --global.\n" - +"Please re-run this command with --local")) + if (npm.config.get('global')) { + return cb(new Error( + 'link should never be --global.\n' + + 'Please re-run this command with --local' + )) } - if (args.length === 1 && args[0] === ".") args = [] + if (args.length === 1 && args[0] === '.') args = [] if (args.length) return linkInstall(args, cb) linkPkg(npm.prefix, cb) } function linkInstall (pkgs, cb) { asyncMap(pkgs, function (pkg, cb) { - var t = path.resolve(npm.globalDir, "..") - , pp = path.resolve(npm.globalDir, pkg) - , rp = null - , target = path.resolve(npm.dir, pkg) + var t = path.resolve(npm.globalDir, '..') + var pp = path.resolve(npm.globalDir, pkg) + var rp = null + var target = path.resolve(npm.dir, pkg) function n (er, data) { if (er) return cb(er, data) @@ -69,7 +71,7 @@ function linkInstall (pkgs, cb) { // if it's a folder, a random not-installed thing, or not a scoped package, // then link or install it first - if (pkg[0] !== "@" && (pkg.indexOf("/") !== -1 || pkg.indexOf("\\") !== -1)) { + if (pkg[0] !== '@' && (pkg.indexOf('/') !== -1 || pkg.indexOf('\\') !== -1)) { return fs.lstat(path.resolve(pkg), function (er, st) { if (er || !st.isDirectory()) { npm.commands.install(t, pkg, n) @@ -89,7 +91,7 @@ function linkInstall (pkgs, cb) { next() } else { return fs.realpath(pp, function (er, real) { - if (er) log.warn("invalid symbolic link", pkg) + if (er) log.warn('invalid symbolic link', pkg) else rp = real next() }) @@ -97,40 +99,43 @@ function linkInstall (pkgs, cb) { }) function next () { - chain - ( [ [npm.commands, "unbuild", [target]] - , [function (cb) { - log.verbose("link", "symlinking %s to %s", pp, target) - cb() - }] - , [symlink, pp, target] + chain( + [ + [npm.commands, 'unbuild', [target]], + [function (cb) { + log.verbose('link', 'symlinking %s to %s', pp, target) + cb() + }], + [symlink, pp, target], // do run lifecycle scripts - full build here. - , rp && [build, [target]] - , [ resultPrinter, pkg, pp, target, rp ] ] - , cb ) + rp && [build, [target]], + [resultPrinter, pkg, pp, target, rp ] + ], + cb + ) } }, cb) } function linkPkg (folder, cb_) { var me = folder || npm.prefix - , readJson = require("read-package-json") + var readJson = require('read-package-json') - log.verbose("linkPkg", folder) + log.verbose('linkPkg', folder) - readJson(path.resolve(me, "package.json"), function (er, d) { + readJson(path.resolve(me, 'package.json'), function (er, d) { function cb (er) { return cb_(er, [[d && d._id, target, null, null]]) } if (er) return cb(er) if (!d.name) { - er = new Error("Package must have a name field to be linked") + er = new Error('Package must have a name field to be linked') return cb(er) } var target = path.resolve(npm.globalDir, d.name) symlink(me, target, false, true, function (er) { if (er) return cb(er) - log.verbose("link", "build target", target) + log.verbose('link', 'build target', target) // also install missing dependencies. npm.commands.install(me, [], function (er) { if (er) return cb(er) @@ -146,17 +151,20 @@ function linkPkg (folder, cb_) { } function resultPrinter (pkg, src, dest, rp, cb) { - if (typeof cb !== "function") cb = rp, rp = null + if (typeof cb !== 'function') { + cb = rp + rp = null + } var where = dest - rp = (rp || "").trim() - src = (src || "").trim() + rp = (rp || '').trim() + src = (src || '').trim() // XXX If --json is set, then look up the data from the package.json - if (npm.config.get("parseable")) { + if (npm.config.get('parseable')) { return parseableOutput(dest, rp || src, cb) } if (rp === src) rp = null log.clearProgress() - console.log(where + " -> " + src + (rp ? " -> " + rp: "")) + console.log(where + ' -> ' + src + (rp ? ' -> ' + rp : '')) log.showProgress() cb() } @@ -165,12 +173,12 @@ function parseableOutput (dest, rp, cb) { // XXX this should match ls --parseable and install --parseable // look up the data from package.json, format it the same way. // - // link is always effectively "long", since it doesn't help much to + // link is always effectively 'long', since it doesn't help much to // *just* print the target folder. // However, we don't actually ever read the version number, so // the second field is always blank. log.clearProgress() - console.log(dest + "::" + rp) + console.log(dest + '::' + rp) log.showProgress() cb() } diff --git a/lib/logout.js b/lib/logout.js index 6fefc28a6..c1ac2818e 100644 --- a/lib/logout.js +++ b/lib/logout.js @@ -1,36 +1,34 @@ module.exports = logout -var dezalgo = require("dezalgo") -var log = require("npmlog") +var dezalgo = require('dezalgo') +var log = require('npmlog') -var npm = require("./npm.js") -var mapToRegistry = require("./utils/map-to-registry.js") +var npm = require('./npm.js') +var mapToRegistry = require('./utils/map-to-registry.js') -logout.usage = "npm logout [--registry=<url>] [--scope=<@scope>]" +logout.usage = 'npm logout [--registry=<url>] [--scope=<@scope>]' function logout (args, cb) { cb = dezalgo(cb) - mapToRegistry("/", npm.config, function (err, uri, auth, normalized) { + mapToRegistry('/', npm.config, function (err, uri, auth, normalized) { if (err) return cb(err) if (auth.token) { - log.verbose("logout", "clearing session token for", normalized) + log.verbose('logout', 'clearing session token for', normalized) npm.registry.logout(normalized, { auth: auth }, function (err) { if (err) return cb(err) npm.config.clearCredentialsByURI(normalized) - npm.config.save("user", cb) + npm.config.save('user', cb) }) - } - else if (auth.username || auth.password) { - log.verbose("logout", "clearing user credentials for", normalized) + } else if (auth.username || auth.password) { + log.verbose('logout', 'clearing user credentials for', normalized) npm.config.clearCredentialsByURI(normalized) - npm.config.save("user", cb) - } - else { + npm.config.save('user', cb) + } else { cb(new Error( - "Not logged in to", normalized + ",", "so can't log out." + 'Not logged in to', normalized + ',', "so can't log out." )) } }) @@ -19,8 +19,8 @@ var npm = require('./npm.js') var logicalTree = require('./install/logical-tree.js') var recalculateMetadata = require('./install/deps.js').recalculateMetadata -ls.usage = "npm ls [[<@scope>/]<pkg> ...]" + - "\n\naliases: list, la, ll" +ls.usage = 'npm ls [[<@scope>/]<pkg> ...]' + + '\n\naliases: list, la, ll' ls.completion = require('./utils/completion/installed-deep.js') @@ -190,11 +190,11 @@ function getLite (data, noname) { return [d, { required: dep.requiredBy, missing: true }] } else if (dep.peerMissing) { lite.problems = lite.problems || [] - var p = 'peer dep missing: ' + + var pdm = 'peer dep missing: ' + d + '@' + dep.version + ', required by ' + data.name + '@' + data.version - lite.problems.push(p) + lite.problems.push(pdm) return [d, { required: dep, peerMissing: true }] } return [d, getLite(dep, true)] @@ -428,6 +428,6 @@ function makeParseable_ (data, long, dir, depth, parent, d) { ':' + (data.realPath !== data.path ? data.realPath : '') + (data.extraneous ? ':EXTRANEOUS' : '') + (data.invalid ? ':INVALID' : '') + - (data.peerInvalid ? ':PEERINVALID' : '') + (data.peerInvalid ? ':PEERINVALID' : '') + (data.peerMissing ? ':PEERINVALID:MISSING' : '') } diff --git a/lib/npm.js b/lib/npm.js index 67cc79876..180e3d4bf 100644 --- a/lib/npm.js +++ b/lib/npm.js @@ -1,446 +1,464 @@ -;(function(){ -// windows: running "npm blah" in this folder will invoke WSH, not node. -if (typeof WScript !== "undefined") { - WScript.echo("npm does not work when run\n" - +"with the Windows Scripting Host\n\n" - +"'cd' to a different directory,\n" - +"or type 'npm.cmd <args>',\n" - +"or type 'node npm <args>'.") - WScript.quit(1) - return -} - - -var EventEmitter = require("events").EventEmitter - , npm = module.exports = new EventEmitter() - , npmconf = require("./config/core.js") - , log = require("npmlog") - , fs = require("graceful-fs") - , path = require("path") - , abbrev = require("abbrev") - , which = require("which") - , CachingRegClient = require("./cache/caching-client.js") - -npm.config = { - loaded: false, - get: function() { - throw new Error('npm.load() required') - }, - set: function() { - throw new Error('npm.load() required') +;(function () { + // windows: running 'npm blah' in this folder will invoke WSH, not node. + /*globals WScript*/ + if (typeof WScript !== 'undefined') { + WScript.echo( + 'npm does not work when run\n' + + 'with the Windows Scripting Host\n\n' + + '"cd" to a different directory,\n' + + 'or type "npm.cmd <args>",\n' + + 'or type "node npm <args>".' + ) + WScript.quit(1) + return } -} -npm.commands = {} + var EventEmitter = require('events').EventEmitter + var npm = module.exports = new EventEmitter() + var npmconf = require('./config/core.js') + var log = require('npmlog') + var fs = require('graceful-fs') + var path = require('path') + var abbrev = require('abbrev') + var which = require('which') + var CachingRegClient = require('./cache/caching-client.js') + + npm.config = { + loaded: false, + get: function () { + throw new Error('npm.load() required') + }, + set: function () { + throw new Error('npm.load() required') + } + } -npm.rollbacks = [] + npm.commands = {} + + npm.rollbacks = [] -try { - // startup, ok to do this synchronously - var j = JSON.parse(fs.readFileSync( - path.join(__dirname, "../package.json"))+"") - npm.version = j.version -} catch (ex) { try { - log.info("error reading version", ex) - } catch (er) {} - npm.version = ex -} + // startup, ok to do this synchronously + var j = JSON.parse(fs.readFileSync( + path.join(__dirname, '../package.json')) + '') + npm.version = j.version + } catch (ex) { + try { + log.info('error reading version', ex) + } catch (er) {} + npm.version = ex + } + + var commandCache = {} -var commandCache = {} // short names for common things - , aliases = { "rm" : "uninstall" - , "r" : "uninstall" - , "un" : "uninstall" - , "unlink" : "uninstall" - , "remove" : "uninstall" - , "rb" : "rebuild" - , "list" : "ls" - , "la" : "ls" - , "ll" : "ls" - , "ln" : "link" - , "i" : "install" - , "isntall" : "install" - , "up" : "update" - , "upgrade" : "update" - , "c" : "config" - , "dist-tags" : "dist-tag" - , "info" : "view" - , "show" : "view" - , "find" : "search" - , "s" : "search" - , "se" : "search" - , "author" : "owner" - , "home" : "docs" - , "issues": "bugs" - , "unstar": "star" // same function - , "apihelp" : "help" - , "login": "adduser" - , "add-user": "adduser" - , "tst": "test" - , "t": "test" - , "find-dupes": "dedupe" - , "ddp": "dedupe" - , "v": "view" - , "verison": "version" - } - - , aliasNames = Object.keys(aliases) - // these are filenames in . - , cmdList = [ "install" - , "uninstall" - , "cache" - , "config" - , "set" - , "get" - , "update" - , "outdated" - , "prune" - , "pack" - , "dedupe" - - , "rebuild" - , "link" - - , "publish" - , "star" - , "stars" - , "tag" - , "adduser" - , "logout" - , "unpublish" - , "owner" - , "access" - , "deprecate" - , "shrinkwrap" - - , "help" - , "help-search" - , "ls" - , "search" - , "view" - , "init" - , "version" - , "edit" - , "explore" - , "docs" - , "repo" - , "bugs" - , "faq" - , "root" - , "prefix" - , "bin" - , "whoami" - , "dist-tag" - - , "test" - , "stop" - , "start" - , "restart" - , "run-script" - , "completion" - ] - , plumbing = [ "build" - , "unbuild" - , "xmas" - , "substack" - , "visnup" - ] - , littleGuys = [ "isntall" ] - , fullList = cmdList.concat(aliasNames).filter(function (c) { - return plumbing.indexOf(c) === -1 - }) - , abbrevs = abbrev(fullList) - -// we have our reasons -fullList = npm.fullList = fullList.filter(function (c) { - return littleGuys.indexOf(c) === -1 -}) - -Object.keys(abbrevs).concat(plumbing).forEach(function addCommand (c) { - Object.defineProperty(npm.commands, c, { get : function () { - if (!loaded) throw new Error( - "Call npm.load(config, cb) before using this command.\n"+ - "See the README.md or cli.js for example usage.") - var a = npm.deref(c) - if (c === "la" || c === "ll") { - npm.config.set("long", true) - } + var aliases = { + 'rm': 'uninstall', + 'r': 'uninstall', + 'un': 'uninstall', + 'unlink': 'uninstall', + 'remove': 'uninstall', + 'rb': 'rebuild', + 'list': 'ls', + 'la': 'ls', + 'll': 'ls', + 'ln': 'link', + 'i': 'install', + 'isntall': 'install', + 'up': 'update', + 'upgrade': 'update', + 'c': 'config', + 'dist-tags': 'dist-tag', + 'info': 'view', + 'show': 'view', + 'find': 'search', + 's': 'search', + 'se': 'search', + 'author': 'owner', + 'home': 'docs', + 'issues': 'bugs', + 'unstar': 'star', // same function + 'apihelp': 'help', + 'login': 'adduser', + 'add-user': 'adduser', + 'tst': 'test', + 't': 'test', + 'find-dupes': 'dedupe', + 'ddp': 'dedupe', + 'v': 'view', + 'verison': 'version' + } - npm.command = c - if (commandCache[a]) return commandCache[a] + var aliasNames = Object.keys(aliases) - var cmd = require(__dirname+"/"+a+".js") + // these are filenames in . + var cmdList = [ + 'install', + 'uninstall', + 'cache', + 'config', + 'set', + 'get', + 'update', + 'outdated', + 'prune', + 'pack', + 'dedupe', + + 'rebuild', + 'link', + + 'publish', + 'star', + 'stars', + 'tag', + 'adduser', + 'logout', + 'unpublish', + 'owner', + 'access', + 'deprecate', + 'shrinkwrap', + + 'help', + 'help-search', + 'ls', + 'search', + 'view', + 'init', + 'version', + 'edit', + 'explore', + 'docs', + 'repo', + 'bugs', + 'faq', + 'root', + 'prefix', + 'bin', + 'whoami', + 'dist-tag', + + 'test', + 'stop', + 'start', + 'restart', + 'run-script', + 'completion' + ] + var plumbing = [ + 'build', + 'unbuild', + 'xmas', + 'substack', + 'visnup' + ] + var littleGuys = [ 'isntall' ] + var fullList = cmdList.concat(aliasNames).filter(function (c) { + return plumbing.indexOf(c) === -1 + }) + var abbrevs = abbrev(fullList) + + // we have our reasons + fullList = npm.fullList = fullList.filter(function (c) { + return littleGuys.indexOf(c) === -1 + }) - commandCache[a] = function () { - var args = Array.prototype.slice.call(arguments, 0) - if (typeof args[args.length - 1] !== "function") { - args.push(defaultCb) + Object.keys(abbrevs).concat(plumbing).forEach(function addCommand (c) { + Object.defineProperty(npm.commands, c, { get: function () { + if (!loaded) { + throw new Error( + 'Call npm.load(config, cb) before using this command.\n' + + 'See the README.md or cli.js for example usage.' + ) } - if (args.length === 1) args.unshift([]) - - npm.registry.version = npm.version - if (!npm.registry.refer) { - npm.registry.refer = [a].concat(args[0]).map(function (arg) { - // exclude anything that might be a URL, path, or private module - // Those things will always have a slash in them somewhere - if (arg && arg.match && arg.match(/\/|\\/)) { - return "[REDACTED]" - } else { - return arg - } - }).filter(function (arg) { - return arg && arg.match - }).join(" ") + var a = npm.deref(c) + if (c === 'la' || c === 'll') { + npm.config.set('long', true) } - cmd.apply(npm, args) - } + npm.command = c + if (commandCache[a]) return commandCache[a] + + var cmd = require(__dirname + '/' + a + '.js') + + commandCache[a] = function () { + var args = Array.prototype.slice.call(arguments, 0) + if (typeof args[args.length - 1] !== 'function') { + args.push(defaultCb) + } + if (args.length === 1) args.unshift([]) + + npm.registry.version = npm.version + if (!npm.registry.refer) { + npm.registry.refer = [a].concat(args[0]).map(function (arg) { + // exclude anything that might be a URL, path, or private module + // Those things will always have a slash in them somewhere + if (arg && arg.match && arg.match(/\/|\\/)) { + return '[REDACTED]' + } else { + return arg + } + }).filter(function (arg) { + return arg && arg.match + }).join(' ') + } + + cmd.apply(npm, args) + } - Object.keys(cmd).forEach(function (k) { - commandCache[a][k] = cmd[k] - }) + Object.keys(cmd).forEach(function (k) { + commandCache[a][k] = cmd[k] + }) - return commandCache[a] - }, enumerable: fullList.indexOf(c) !== -1, configurable: true }) + return commandCache[a] + }, enumerable: fullList.indexOf(c) !== -1, configurable: true }) - // make css-case commands callable via camelCase as well - if (c.match(/\-([a-z])/)) { - addCommand(c.replace(/\-([a-z])/g, function (a, b) { - return b.toUpperCase() - })) - } -}) - -function defaultCb (er, data) { - log.disableProgress() - if (er) console.error(er.stack || er.message) - else console.log(data) -} - -npm.deref = function (c) { - if (!c) return "" - if (c.match(/[A-Z]/)) c = c.replace(/([A-Z])/g, function (m) { - return "-" + m.toLowerCase() - }) - if (plumbing.indexOf(c) !== -1) return c - var a = abbrevs[c] - if (aliases[a]) a = aliases[a] - return a -} - -var loaded = false - , loading = false - , loadErr = null - , loadListeners = [] - -function loadCb (er) { - loadListeners.forEach(function (cb) { - process.nextTick(cb.bind(npm, er, npm)) - }) - loadListeners.length = 0 -} - -npm.load = function (cli, cb_) { - if (!cb_ && typeof cli === "function") cb_ = cli , cli = {} - if (!cb_) cb_ = function () {} - if (!cli) cli = {} - loadListeners.push(cb_) - if (loaded || loadErr) return cb(loadErr) - if (loading) return - loading = true - var onload = true - - function cb (er) { - if (loadErr) return - loadErr = er - if (er) return cb_(er) - if (npm.config.get("force")) { - log.warn("using --force", "I sure hope you know what you are doing.") + // make css-case commands callable via camelCase as well + if (c.match(/\-([a-z])/)) { + addCommand(c.replace(/\-([a-z])/g, function (a, b) { + return b.toUpperCase() + })) } - npm.config.loaded = true - loaded = true - loadCb(loadErr = er) - if (onload = onload && npm.config.get("onload-script")) { - require(onload) - onload = false + }) + + function defaultCb (er, data) { + log.disableProgress() + if (er) console.error(er.stack || er.message) + else console.log(data) + } + + npm.deref = function (c) { + if (!c) return '' + if (c.match(/[A-Z]/)) { + c = c.replace(/([A-Z])/g, function (m) { + return '-' + m.toLowerCase() + }) } + if (plumbing.indexOf(c) !== -1) return c + var a = abbrevs[c] + if (aliases[a]) a = aliases[a] + return a } - log.pause() + var loaded = false + var loading = false + var loadErr = null + var loadListeners = [] - load(npm, cli, cb) -} + function loadCb (er) { + loadListeners.forEach(function (cb) { + process.nextTick(cb.bind(npm, er, npm)) + }) + loadListeners.length = 0 + } -function load (npm, cli, cb) { - which(process.argv[0], function (er, node) { - if (!er && node.toUpperCase() !== process.execPath.toUpperCase()) { - log.verbose("node symlink", node) - process.execPath = node - process.installPrefix = path.resolve(node, "..", "..") + npm.load = function (cli, cb_) { + if (!cb_ && typeof cli === 'function') { + cb_ = cli + cli = {} } - - // look up configs - //console.error("about to look up configs") - - var builtin = path.resolve(__dirname, "..", "npmrc") - npmconf.load(cli, builtin, function (er, config) { - if (er === config) er = null - - npm.config = config - if (er) return cb(er) - - // if the "project" config is not a filename, and we're - // not in global mode, then that means that it collided - // with either the default or effective userland config - if (!config.get("global") - && config.sources.project - && config.sources.project.type !== "ini") { - log.verbose("config" - , "Skipping project config: %s. " - + "(matches userconfig)" - , config.localPrefix + "/.npmrc") + if (!cb_) cb_ = function () {} + if (!cli) cli = {} + loadListeners.push(cb_) + if (loaded || loadErr) return cb(loadErr) + if (loading) return + loading = true + var onload = true + + function cb (er) { + if (loadErr) return + loadErr = er + if (er) return cb_(er) + if (npm.config.get('force')) { + log.warn('using --force', 'I sure hope you know what you are doing.') } - - // Include npm-version and node-version in user-agent - var ua = config.get("user-agent") || "" - ua = ua.replace(/\{node-version\}/gi, process.version) - ua = ua.replace(/\{npm-version\}/gi, npm.version) - ua = ua.replace(/\{platform\}/gi, process.platform) - ua = ua.replace(/\{arch\}/gi, process.arch) - config.set("user-agent", ua) - - var color = config.get("color") - - log.level = config.get("loglevel") - log.heading = config.get("heading") || "npm" - log.stream = config.get("logstream") - - switch (color) { - case "always": - log.enableColor() - npm.color = true - break - case false: - log.disableColor() - npm.color = false - break - default: - var tty = require("tty") - if (process.stdout.isTTY) npm.color = true - else if (!tty.isatty) npm.color = true - else if (tty.isatty(1)) npm.color = true - else npm.color = false - break + npm.config.loaded = true + loaded = true + loadCb(loadErr = er) + onload = onload && npm.config.get('onload-script') + if (onload) { + require(onload) + onload = false } + } - log.resume() - - // at this point the configs are all set. - // go ahead and spin up the registry client. - npm.registry = new CachingRegClient(npm.config) - - var umask = npm.config.get("umask") - npm.modes = { exec: 0777 & (~umask) - , file: 0666 & (~umask) - , umask: umask } + log.pause() - var gp = Object.getOwnPropertyDescriptor(config, "globalPrefix") - Object.defineProperty(npm, "globalPrefix", gp) + load(npm, cli, cb) + } - var lp = Object.getOwnPropertyDescriptor(config, "localPrefix") - Object.defineProperty(npm, "localPrefix", lp) + function load (npm, cli, cb) { + which(process.argv[0], function (er, node) { + if (!er && node.toUpperCase() !== process.execPath.toUpperCase()) { + log.verbose('node symlink', node) + process.execPath = node + process.installPrefix = path.resolve(node, '..', '..') + } - return cb(null, npm) + // look up configs + var builtin = path.resolve(__dirname, '..', 'npmrc') + npmconf.load(cli, builtin, function (er, config) { + if (er === config) er = null + + npm.config = config + if (er) return cb(er) + + // if the 'project' config is not a filename, and we're + // not in global mode, then that means that it collided + // with either the default or effective userland config + if (!config.get('global') && + config.sources.project && + config.sources.project.type !== 'ini') { + log.verbose( + 'config', + 'Skipping project config: %s. (matches userconfig)', + config.localPrefix + '/.npmrc' + ) + } + + // Include npm-version and node-version in user-agent + var ua = config.get('user-agent') || '' + ua = ua.replace(/\{node-version\}/gi, process.version) + ua = ua.replace(/\{npm-version\}/gi, npm.version) + ua = ua.replace(/\{platform\}/gi, process.platform) + ua = ua.replace(/\{arch\}/gi, process.arch) + config.set('user-agent', ua) + + var color = config.get('color') + + log.level = config.get('loglevel') + log.heading = config.get('heading') || 'npm' + log.stream = config.get('logstream') + + switch (color) { + case 'always': + log.enableColor() + npm.color = true + break + case false: + log.disableColor() + npm.color = false + break + default: + var tty = require('tty') + if (process.stdout.isTTY) npm.color = true + else if (!tty.isatty) npm.color = true + else if (tty.isatty(1)) npm.color = true + else npm.color = false + break + } + + log.resume() + + // at this point the configs are all set. + // go ahead and spin up the registry client. + npm.registry = new CachingRegClient(npm.config) + + var umask = npm.config.get('umask') + npm.modes = { + exec: parseInt('0777', 8) & (~umask), + file: parseInt('0666', 8) & (~umask), + umask: umask + } + + var gp = Object.getOwnPropertyDescriptor(config, 'globalPrefix') + Object.defineProperty(npm, 'globalPrefix', gp) + + var lp = Object.getOwnPropertyDescriptor(config, 'localPrefix') + Object.defineProperty(npm, 'localPrefix', lp) + + return cb(null, npm) + }) }) - }) -} + } -Object.defineProperty(npm, "prefix", - { get : function () { - return npm.config.get("global") ? npm.globalPrefix : npm.localPrefix - } - , set : function (r) { - var k = npm.config.get("global") ? "globalPrefix" : "localPrefix" - return npm[k] = r - } - , enumerable : true - }) + Object.defineProperty(npm, 'prefix', + { get: function () { + return npm.config.get('global') ? npm.globalPrefix : npm.localPrefix + }, + set: function (r) { + var k = npm.config.get('global') ? 'globalPrefix' : 'localPrefix' + npm[k] = r + return r + }, + enumerable: true + }) -Object.defineProperty(npm, "bin", - { get : function () { - if (npm.config.get("global")) return npm.globalBin - return path.resolve(npm.root, ".bin") - } - , enumerable : true - }) + Object.defineProperty(npm, 'bin', + { get: function () { + if (npm.config.get('global')) return npm.globalBin + return path.resolve(npm.root, '.bin') + }, + enumerable: true + }) -Object.defineProperty(npm, "globalBin", - { get : function () { - var b = npm.globalPrefix - if (process.platform !== "win32") b = path.resolve(b, "bin") - return b - } - }) + Object.defineProperty(npm, 'globalBin', + { get: function () { + var b = npm.globalPrefix + if (process.platform !== 'win32') b = path.resolve(b, 'bin') + return b + } + }) -Object.defineProperty(npm, "dir", - { get : function () { - if (npm.config.get("global")) return npm.globalDir - return path.resolve(npm.prefix, "node_modules") - } - , enumerable : true - }) + Object.defineProperty(npm, 'dir', + { get: function () { + if (npm.config.get('global')) return npm.globalDir + return path.resolve(npm.prefix, 'node_modules') + }, + enumerable: true + }) -Object.defineProperty(npm, "globalDir", - { get : function () { - return (process.platform !== "win32") - ? path.resolve(npm.globalPrefix, "lib", "node_modules") - : path.resolve(npm.globalPrefix, "node_modules") - } - , enumerable : true - }) + Object.defineProperty(npm, 'globalDir', + { get: function () { + return (process.platform !== 'win32') + ? path.resolve(npm.globalPrefix, 'lib', 'node_modules') + : path.resolve(npm.globalPrefix, 'node_modules') + }, + enumerable: true + }) -Object.defineProperty(npm, "root", - { get : function () { return npm.dir } }) + Object.defineProperty(npm, 'root', + { get: function () { return npm.dir } }) -Object.defineProperty(npm, "cache", - { get : function () { return npm.config.get("cache") } - , set : function (r) { return npm.config.set("cache", r) } - , enumerable : true - }) + Object.defineProperty(npm, 'cache', + { get: function () { return npm.config.get('cache') }, + set: function (r) { return npm.config.set('cache', r) }, + enumerable: true + }) -var tmpFolder -var rand = require("crypto").randomBytes(4).toString("hex") -Object.defineProperty(npm, "tmp", - { get : function () { - if (!tmpFolder) tmpFolder = "npm-" + process.pid + "-" + rand - return path.resolve(npm.config.get("tmp"), tmpFolder) - } - , enumerable : true - }) + var tmpFolder + var rand = require('crypto').randomBytes(4).toString('hex') + Object.defineProperty(npm, 'tmp', + { get: function () { + if (!tmpFolder) tmpFolder = 'npm-' + process.pid + '-' + rand + return path.resolve(npm.config.get('tmp'), tmpFolder) + }, + enumerable: true + }) -// the better to repl you with -Object.getOwnPropertyNames(npm.commands).forEach(function (n) { - if (npm.hasOwnProperty(n) || n === "config") return + // the better to repl you with + Object.getOwnPropertyNames(npm.commands).forEach(function (n) { + if (npm.hasOwnProperty(n) || n === 'config') return - Object.defineProperty(npm, n, { get: function () { - return function () { - var args = Array.prototype.slice.call(arguments, 0) - , cb = defaultCb + Object.defineProperty(npm, n, { get: function () { + return function () { + var args = Array.prototype.slice.call(arguments, 0) + var cb = defaultCb - if (args.length === 1 && Array.isArray(args[0])) { - args = args[0] - } + if (args.length === 1 && Array.isArray(args[0])) { + args = args[0] + } - if (typeof args[args.length - 1] === "function") { - cb = args.pop() + if (typeof args[args.length - 1] === 'function') { + cb = args.pop() + } + npm.commands[n](args, cb) } - npm.commands[n](args, cb) - } - }, enumerable: false, configurable: true }) -}) + }, enumerable: false, configurable: true }) + }) -if (require.main === module) { - require("../bin/npm-cli.js") -} + if (require.main === module) { + require('../bin/npm-cli.js') + } })() diff --git a/lib/outdated.js b/lib/outdated.js index 7ac4a9548..011a3dbbb 100644 --- a/lib/outdated.js +++ b/lib/outdated.js @@ -16,7 +16,7 @@ packages. module.exports = outdated -outdated.usage = "npm outdated [[<@scope>/]<pkg> ...]" +outdated.usage = 'npm outdated [[<@scope>/]<pkg> ...]' outdated.completion = require('./utils/completion/installed-deep.js') @@ -154,20 +154,6 @@ function ansiTrim (str) { return str.replace(r, '') } -function depToPrettyLocation (dep) { - var depname = dep.package.name - var parentLocation - - if (dep.requiredBy && dep.requiredBy.length > 1) { - parentLocation = '[ ' + dep.requiredBy.map(function (parent) { - return depToPrettyLocation(parent) - }).join(', ') + ' ]' - } else if (dep.requiredBy && dep.requiredBy.length) { - parentLocation = depToPrettyLocation(dep.requiredBy[0]) - } - return parentLocation ? parentLocation + ' > ' + depname : depname -} - function makeParseable (list) { return list.map(function (p) { var dep = p[0] @@ -223,7 +209,7 @@ function outdated_ (args, path, tree, parentHas, depth, cb) { var types = {} var pkg = tree.package - var deps = tree.children.filter(function(child){ return !isExtraneous(child) }) || [] + var deps = tree.children.filter(function (child) { return !isExtraneous(child) }) || [] deps.forEach(function (dep) { types[dep.package.name] = 'dependencies' @@ -275,16 +261,16 @@ function outdated_ (args, path, tree, parentHas, depth, cb) { types[dep.package.name] = 'optionalDependencies' }) } - var doUpdate = npm.config.get("dev") || ( - !npm.config.get("production") && + var doUpdate = npm.config.get('dev') || ( + !npm.config.get('production') && !Object.keys(parentHas).length && - !npm.config.get("global") + !npm.config.get('global') ) if (doUpdate) { Object.keys(pkg.devDependencies).forEach(function (k) { if (!(k in parentHas)) { deps[k] = pkg.devDependencies[k] - types[k] = "devDependencies" + types[k] = 'devDependencies' } }) } @@ -422,9 +408,10 @@ function shouldUpdate (args, tree, dep, has, req, depth, pkgpath, cb, type) { var dFromUrl = d._from && url.parse(d._from).protocol var cFromUrl = curr && curr.from && url.parse(curr.from).protocol - if (!curr || dFromUrl && cFromUrl && d._from !== curr.from - || d.version !== curr.version - || d.version !== l.version) { + if (!curr || + dFromUrl && cFromUrl && d._from !== curr.from || + d.version !== curr.version || + d.version !== l.version) { if (parsed.type === 'local') return updateLocalDeps(l.version) doIt(d.version, l.version) diff --git a/lib/owner.js b/lib/owner.js index 43076d877..f32f405dd 100644 --- a/lib/owner.js +++ b/lib/owner.js @@ -1,21 +1,21 @@ module.exports = owner -owner.usage = "npm owner add <user> [<@scope>/]<pkg>" - + "\nnpm owner rm <user> [<@scope>/]<pkg>" - + "\nnpm owner ls [<@scope>/]<pkg>" +owner.usage = 'npm owner add <user> [<@scope>/]<pkg>' + + '\nnpm owner rm <user> [<@scope>/]<pkg>' + + '\nnpm owner ls [<@scope>/]<pkg>' -var npm = require("./npm.js") - , log = require("npmlog") - , mapToRegistry = require("./utils/map-to-registry.js") - , readLocalPkg = require("./utils/read-local-package.js") +var npm = require('./npm.js') +var log = require('npmlog') +var mapToRegistry = require('./utils/map-to-registry.js') +var readLocalPkg = require('./utils/read-local-package.js') owner.completion = function (opts, cb) { var argv = opts.conf.argv.remain if (argv.length > 4) return cb() if (argv.length <= 2) { - var subs = ["add", "rm"] - if (opts.partialWord === "l") subs.push("ls") - else subs.push("ls", "list") + var subs = ['add', 'rm'] + if (opts.partialWord === 'l') subs.push('ls') + else subs.push('ls', 'list') return cb(null, subs) } @@ -25,44 +25,45 @@ owner.completion = function (opts, cb) { var un = encodeURIComponent(username) var byUser, theUser switch (argv[2]) { - case "ls": + case 'ls': // FIXME: there used to be registry completion here, but it stopped // making sense somewhere around 50,000 packages on the registry return cb() - case "rm": + case 'rm': if (argv.length > 3) { theUser = encodeURIComponent(argv[3]) - byUser = "-/by-user/" + theUser + "|" + un + byUser = '-/by-user/' + theUser + '|' + un return mapToRegistry(byUser, npm.config, function (er, uri, auth) { if (er) return cb(er) console.error(uri) - npm.registry.get(uri, { auth : auth }, function (er, d) { + npm.registry.get(uri, { auth: auth }, function (er, d) { if (er) return cb(er) // return the intersection return cb(null, d[theUser].filter(function (p) { // kludge for server adminery. - return un === "isaacs" || d[un].indexOf(p) === -1 + return un === 'isaacs' || d[un].indexOf(p) === -1 })) }) }) } // else fallthrough - case "add": + /*eslint no-fallthrough:0*/ + case 'add': if (argv.length > 3) { theUser = encodeURIComponent(argv[3]) - byUser = "-/by-user/" + theUser + "|" + un + byUser = '-/by-user/' + theUser + '|' + un return mapToRegistry(byUser, npm.config, function (er, uri, auth) { if (er) return cb(er) console.error(uri) - npm.registry.get(uri, { auth : auth }, function (er, d) { + npm.registry.get(uri, { auth: auth }, function (er, d) { console.error(uri, er || d) // return mine that they're not already on. if (er) return cb(er) var mine = d[un] || [] - , theirs = d[theUser] || [] + var theirs = d[theUser] || [] return cb(null, mine.filter(function (p) { return theirs.indexOf(p) === -1 })) @@ -70,10 +71,10 @@ owner.completion = function (opts, cb) { }) } // just list all users who aren't me. - return mapToRegistry("-/users", npm.config, function (er, uri, auth) { + return mapToRegistry('-/users', npm.config, function (er, uri, auth) { if (er) return cb(er) - npm.registry.get(uri, { auth : auth }, function (er, list) { + npm.registry.get(uri, { auth: auth }, function (er, list) { if (er) return cb() return cb(null, Object.keys(list).filter(function (n) { return n !== un @@ -90,34 +91,39 @@ owner.completion = function (opts, cb) { function owner (args, cb) { var action = args.shift() switch (action) { - case "ls": case "list": return ls(args[0], cb) - case "add": return add(args[0], args[1], cb) - case "rm": case "remove": return rm(args[0], args[1], cb) + case 'ls': case 'list': return ls(args[0], cb) + case 'add': return add(args[0], args[1], cb) + case 'rm': case 'remove': return rm(args[0], args[1], cb) default: return unknown(action, cb) } } function ls (pkg, cb) { - if (!pkg) return readLocalPkg(function (er, pkg) { - if (er) return cb(er) - if (!pkg) return cb(owner.usage) - ls(pkg, cb) - }) + if (!pkg) { + return readLocalPkg(function (er, pkg) { + if (er) return cb(er) + if (!pkg) return cb(owner.usage) + ls(pkg, cb) + }) + } mapToRegistry(pkg, npm.config, function (er, uri, auth) { if (er) return cb(er) - npm.registry.get(uri, { auth : auth }, function (er, data) { - var msg = "" + npm.registry.get(uri, { auth: auth }, function (er, data) { + var msg = '' if (er) { - log.error("owner ls", "Couldn't get owner data", pkg) + log.error('owner ls', "Couldn't get owner data", pkg) return cb(er) } var owners = data.maintainers - if (!owners || !owners.length) msg = "admin party!" - else msg = owners.map(function (o) { - return o.name + " <" + o.email + ">" - }).join("\n") + if (!owners || !owners.length) { + msg = 'admin party!' + } else { + msg = owners.map(function (o) { + return o.name + ' <' + o.email + '>' + }).join('\n') + } console.log(msg) cb(er, owners) }) @@ -126,20 +132,24 @@ function ls (pkg, cb) { function add (user, pkg, cb) { if (!user) return cb(owner.usage) - if (!pkg) return readLocalPkg(function (er, pkg) { - if (er) return cb(er) - if (!pkg) return cb(new Error(owner.usage)) - add(user, pkg, cb) - }) + if (!pkg) { + return readLocalPkg(function (er, pkg) { + if (er) return cb(er) + if (!pkg) return cb(new Error(owner.usage)) + add(user, pkg, cb) + }) + } - log.verbose("owner add", "%s to %s", user, pkg) + log.verbose('owner add', '%s to %s', user, pkg) mutate(pkg, user, function (u, owners) { if (!owners) owners = [] - for (var i = 0, l = owners.length; i < l; i ++) { + for (var i = 0, l = owners.length; i < l; i++) { var o = owners[i] if (o.name === u.name) { - log.info( "owner add" - , "Already a package owner: " + o.name + " <" + o.email + ">") + log.info( + 'owner add', + 'Already a package owner: ' + o.name + ' <' + o.email + '>' + ) return false } } @@ -149,58 +159,69 @@ function add (user, pkg, cb) { } function rm (user, pkg, cb) { - if (!pkg) return readLocalPkg(function (er, pkg) { - if (er) return cb(er) - if (!pkg) return cb(new Error(owner.usage)) - rm(user, pkg, cb) - }) + if (!pkg) { + return readLocalPkg(function (er, pkg) { + if (er) return cb(er) + if (!pkg) return cb(new Error(owner.usage)) + rm(user, pkg, cb) + }) + } - log.verbose("owner rm", "%s from %s", user, pkg) + log.verbose('owner rm', '%s from %s', user, pkg) mutate(pkg, user, function (u, owners) { var found = false - , m = owners.filter(function (o) { - var match = (o.name === user) - found = found || match - return !match - }) + var m = owners.filter(function (o) { + var match = (o.name === user) + found = found || match + return !match + }) + if (!found) { - log.info("owner rm", "Not a package owner: " + user) + log.info('owner rm', 'Not a package owner: ' + user) return false } - if (!m.length) return new Error( - "Cannot remove all owners of a package. Add someone else first.") + + if (!m.length) { + return new Error( + 'Cannot remove all owners of a package. Add someone else first.' + ) + } + return m }, cb) } function mutate (pkg, user, mutation, cb) { if (user) { - var byUser = "-/user/org.couchdb.user:" + user + var byUser = '-/user/org.couchdb.user:' + user mapToRegistry(byUser, npm.config, function (er, uri, auth) { if (er) return cb(er) - npm.registry.get(uri, { auth : auth }, mutate_) + npm.registry.get(uri, { auth: auth }, mutate_) }) } else { mutate_(null, null) } function mutate_ (er, u) { - if (!er && user && (!u || u.error)) er = new Error( - "Couldn't get user data for " + user + ": " + JSON.stringify(u)) + if (!er && user && (!u || u.error)) { + er = new Error( + "Couldn't get user data for " + user + ': ' + JSON.stringify(u) + ) + } if (er) { - log.error("owner mutate", "Error getting user data for %s", user) + log.error('owner mutate', 'Error getting user data for %s', user) return cb(er) } - if (u) u = { "name" : u.name, "email" : u.email } + if (u) u = { name: u.name, email: u.email } mapToRegistry(pkg, npm.config, function (er, uri, auth) { if (er) return cb(er) - npm.registry.get(uri, { auth : auth }, function (er, data) { + npm.registry.get(uri, { auth: auth }, function (er, data) { if (er) { - log.error("owner mutate", "Error getting package data for %s", pkg) + log.error('owner mutate', 'Error getting package data for %s', pkg) return cb(er) } @@ -213,32 +234,30 @@ function mutate (pkg, user, mutation, cb) { if (m instanceof Error) return cb(m) // error data = { - _id : data._id, - _rev : data._rev, - maintainers : m + _id: data._id, + _rev: data._rev, + maintainers: m } - var dataPath = pkg.replace("/", "%2f") + "/-rev/" + data._rev + var dataPath = pkg.replace('/', '%2f') + '/-rev/' + data._rev mapToRegistry(dataPath, npm.config, function (er, uri, auth) { if (er) return cb(er) var params = { - method : "PUT", - body : data, - auth : auth + method: 'PUT', + body: data, + auth: auth } npm.registry.request(uri, params, function (er, data) { if (!er && data.error) { - er = new Error("Failed to update package metadata: "+JSON.stringify(data)) + er = new Error('Failed to update package metadata: ' + JSON.stringify(data)) } if (er) { - log.error("owner mutate", "Failed to update package metadata") - } - else if (m.length > beforeMutation) { - console.log("+ %s (%s)", user, pkg) - } - else if (m.length < beforeMutation) { - console.log("- %s (%s)", user, pkg) + log.error('owner mutate', 'Failed to update package metadata') + } else if (m.length > beforeMutation) { + console.log('+ %s (%s)', user, pkg) + } else if (m.length < beforeMutation) { + console.log('- %s (%s)', user, pkg) } cb(er, data) @@ -250,5 +269,5 @@ function mutate (pkg, user, mutation, cb) { } function unknown (action, cb) { - cb("Usage: \n" + owner.usage) + cb('Usage: \n' + owner.usage) } diff --git a/lib/pack.js b/lib/pack.js index 1ccbd2e88..d596dd034 100644 --- a/lib/pack.js +++ b/lib/pack.js @@ -4,39 +4,42 @@ module.exports = pack -var npm = require("./npm.js") - , install = require("./install.js") - , cache = require("./cache.js") - , fs = require("graceful-fs") - , chain = require("slide").chain - , path = require("path") - , cwd = process.cwd() - , writeStream = require('fs-write-stream-atomic') - , cachedPackageRoot = require("./cache/cached-package-root.js") +var install = require('./install.js') +var cache = require('./cache.js') +var fs = require('graceful-fs') +var chain = require('slide').chain +var path = require('path') +var cwd = process.cwd() +var writeStream = require('fs-write-stream-atomic') +var cachedPackageRoot = require('./cache/cached-package-root.js') -pack.usage = "npm pack [[<@scope>/]<pkg>...]" +pack.usage = 'npm pack [[<@scope>/]<pkg>...]' // if it can be installed, it can be packed. pack.completion = install.completion function pack (args, silent, cb) { - if (typeof cb !== "function") cb = silent, silent = false + if (typeof cb !== 'function') { + cb = silent + silent = false + } - if (args.length === 0) args = ["."] + if (args.length === 0) args = ['.'] - chain(args.map(function (arg) { return function (cb) { - pack_(arg, cb) - }}), function (er, files) { - if (er || silent) return cb(er, files) - printFiles(files, cb) - }) + chain( + args.map(function (arg) { return function (cb) { pack_(arg, cb) } }), + function (er, files) { + if (er || silent) return cb(er, files) + printFiles(files, cb) + } + ) } function printFiles (files, cb) { files = files.map(function (file) { return path.relative(cwd, file) }) - console.log(files.join("\n")) + console.log(files.join('\n')) cb() } @@ -47,17 +50,17 @@ function pack_ (pkg, cb) { // scoped packages get special treatment var name = data.name - if (name[0] === "@") name = name.substr(1).replace(/\//g, "-") - var fname = name + "-" + data.version + ".tgz" + if (name[0] === '@') name = name.substr(1).replace(/\//g, '-') + var fname = name + '-' + data.version + '.tgz' - var cached = path.join(cachedPackageRoot(data), "package.tgz") - , from = fs.createReadStream(cached) - , to = writeStream(fname) - , errState = null + var cached = path.join(cachedPackageRoot(data), 'package.tgz') + var from = fs.createReadStream(cached) + var to = writeStream(fname) + var errState = null - from.on("error", cb_) - to.on("error", cb_) - to.on("close", cb_) + from.on('error', cb_) + to.on('error', cb_) + to.on('close', cb_) from.pipe(to) function cb_ (er) { diff --git a/lib/prefix.js b/lib/prefix.js index 58b2af3a7..42f61103f 100644 --- a/lib/prefix.js +++ b/lib/prefix.js @@ -1,11 +1,14 @@ module.exports = prefix -var npm = require("./npm.js") +var npm = require('./npm.js') -prefix.usage = "npm prefix [-g]" +prefix.usage = 'npm prefix [-g]' function prefix (args, silent, cb) { - if (typeof cb !== "function") cb = silent, silent = false + if (typeof cb !== 'function') { + cb = silent + silent = false + } if (!silent) console.log(npm.prefix) process.nextTick(cb.bind(this, null, npm.prefix)) } diff --git a/lib/prune.js b/lib/prune.js index 2f27fdf32..46373742f 100644 --- a/lib/prune.js +++ b/lib/prune.js @@ -2,28 +2,28 @@ module.exports = prune -prune.usage = "npm prune [[<@scope>/]<pkg>...] [--production]" +prune.usage = 'npm prune [[<@scope>/]<pkg>...] [--production]' -var readInstalled = require("read-installed") - , npm = require("./npm.js") - , path = require("path") - , readJson = require("read-package-json") - , log = require("npmlog") +var readInstalled = require('read-installed') +var npm = require('./npm.js') +var path = require('path') +var readJson = require('read-package-json') +var log = require('npmlog') -prune.completion = require("./utils/completion/installed-deep.js") +prune.completion = require('./utils/completion/installed-deep.js') function prune (args, cb) { - //check if is a valid package.json file - var jsonFile = path.resolve(npm.dir, "..", "package.json" ) + // check if is a valid package.json file + var jsonFile = path.resolve(npm.dir, '..', 'package.json') readJson(jsonFile, log.warn, function (er) { if (er) return cb(er) next() }) - function next() { + function next () { var opt = { - depth: npm.config.get("depth"), - dev: !npm.config.get("production") || npm.config.get("dev") + depth: npm.config.get('depth'), + dev: !npm.config.get('production') || npm.config.get('dev') } readInstalled(npm.prefix, opt, function (er, data) { if (er) return cb(er) @@ -39,11 +39,9 @@ function prune_ (args, data, cb) { function prunables (args, data, seen) { var deps = data.dependencies || {} return Object.keys(deps).map(function (d) { - if (typeof deps[d] !== "object" - || seen.indexOf(deps[d]) !== -1) return null + if (typeof deps[d] !== 'object' || seen.indexOf(deps[d]) !== -1) return null seen.push(deps[d]) - if (deps[d].extraneous - && (args.length === 0 || args.indexOf(d) !== -1)) { + if (deps[d].extraneous && (args.length === 0 || args.indexOf(d) !== -1)) { var extra = deps[d] delete deps[d] return extra.path @@ -51,6 +49,6 @@ function prunables (args, data, seen) { return prunables(args, deps[d], seen) }).filter(function (d) { return d !== null }) .reduce(function FLAT (l, r) { - return l.concat(Array.isArray(r) ? r.reduce(FLAT,[]) : r) + return l.concat(Array.isArray(r) ? r.reduce(FLAT, []) : r) }, []) } diff --git a/lib/publish.js b/lib/publish.js index 77db8cd43..08525c74a 100644 --- a/lib/publish.js +++ b/lib/publish.js @@ -1,23 +1,22 @@ module.exports = publish -var npm = require("./npm.js") - , log = require("npmlog") - , path = require("path") - , readJson = require("read-package-json") - , lifecycle = require("./utils/lifecycle.js") - , chain = require("slide").chain - , mapToRegistry = require("./utils/map-to-registry.js") - , cachedPackageRoot = require("./cache/cached-package-root.js") - , createReadStream = require("graceful-fs").createReadStream - , npa = require("npm-package-arg") - , semver = require('semver') - , getPublishConfig = require("./utils/get-publish-config.js") - -publish.usage = "npm publish [<tarball>|<folder>] [--tag <tag>] [--access <public|restricted>]" - - + "\n\nPublishes '.' if no argument supplied" - + "\n\nSets tag `latest` if no --tag specified" +var npm = require('./npm.js') +var log = require('npmlog') +var path = require('path') +var readJson = require('read-package-json') +var lifecycle = require('./utils/lifecycle.js') +var chain = require('slide').chain +var mapToRegistry = require('./utils/map-to-registry.js') +var cachedPackageRoot = require('./cache/cached-package-root.js') +var createReadStream = require('graceful-fs').createReadStream +var npa = require('npm-package-arg') +var semver = require('semver') +var getPublishConfig = require('./utils/get-publish-config.js') + +publish.usage = 'npm publish [<tarball>|<folder>] [--tag <tag>] [--access <public|restricted>]' + + "\n\nPublishes '.' if no argument supplied" + + '\n\nSets tag `latest` if no --tag specified' publish.completion = function (opts, cb) { // publish can complete to a folder with a package.json @@ -27,29 +26,29 @@ publish.completion = function (opts, cb) { } function publish (args, isRetry, cb) { - if (typeof cb !== "function") { + if (typeof cb !== 'function') { cb = isRetry isRetry = false } - if (args.length === 0) args = ["."] + if (args.length === 0) args = ['.'] if (args.length !== 1) return cb(publish.usage) - log.verbose("publish", args) + log.verbose('publish', args) var t = npm.config.get('tag').trim() if (semver.validRange(t)) { - var er = new Error("Tag name must not be a valid SemVer range: " + t) + var er = new Error('Tag name must not be a valid SemVer range: ' + t) return cb(er) } var arg = args[0] // if it's a local folder, then run the prepublish there, first. - readJson(path.resolve(arg, "package.json"), function (er, data) { - if (er && er.code !== "ENOENT" && er.code !== "ENOTDIR") return cb(er) + readJson(path.resolve(arg, 'package.json'), function (er, data) { + if (er && er.code !== 'ENOENT' && er.code !== 'ENOTDIR') return cb(er) if (data) { - if (!data.name) return cb(new Error("No name provided")) - if (!data.version) return cb(new Error("No version provided")) + if (!data.name) return cb(new Error('No name provided')) + if (!data.version) return cb(new Error('No version provided')) } // Error is OK. Could be publishing a URL or tarball, however, that means @@ -61,26 +60,29 @@ function publish (args, isRetry, cb) { } // didPre in this case means that we already ran the prepublish script, -// and that the "dir" is an actual directory, and not something silly +// and that the 'dir' is an actual directory, and not something silly // like a tarball or name@version thing. // That means that we can run publish/postpublish in the dir, rather than // in the cache dir. function cacheAddPublish (dir, didPre, isRetry, cb) { npm.commands.cache.add(dir, null, null, false, function (er, data) { if (er) return cb(er) - log.silly("publish", data) - var cachedir = path.resolve(cachedPackageRoot(data), "package") - chain([ !didPre && - [lifecycle, data, "prepublish", cachedir] - , [publish_, dir, data, isRetry, cachedir] - , [lifecycle, data, "publish", didPre ? dir : cachedir] - , [lifecycle, data, "postpublish", didPre ? dir : cachedir] ] - , cb ) + log.silly('publish', data) + var cachedir = path.resolve(cachedPackageRoot(data), 'package') + chain( + [ + !didPre && [lifecycle, data, 'prepublish', cachedir], + [publish_, dir, data, isRetry, cachedir], + [lifecycle, data, 'publish', didPre ? dir : cachedir], + [lifecycle, data, 'postpublish', didPre ? dir : cachedir] + ], + cb + ) }) } function publish_ (arg, data, isRetry, cachedir, cb) { - if (!data) return cb(new Error("no package.json file found")) + if (!data) return cb(new Error('no package.json file found')) var mappedConfig = getPublishConfig( data.publishConfig, @@ -90,51 +92,51 @@ function publish_ (arg, data, isRetry, cachedir, cb) { var config = mappedConfig.config var registry = mappedConfig.client - data._npmVersion = npm.version + data._npmVersion = npm.version data._nodeVersion = process.versions.node delete data.modules - if (data.private) return cb( - new Error( - "This package has been marked as private\n" + + if (data.private) { + return cb(new Error( + 'This package has been marked as private\n' + "Remove the 'private' field from the package.json to publish it." - ) - ) + )) + } mapToRegistry(data.name, config, function (er, registryURI, auth, registryBase) { if (er) return cb(er) - var tarballPath = cachedir + ".tgz" + var tarballPath = cachedir + '.tgz' // we just want the base registry URL in this case - log.verbose("publish", "registryBase", registryBase) - log.silly("publish", "uploading", tarballPath) + log.verbose('publish', 'registryBase', registryBase) + log.silly('publish', 'uploading', tarballPath) data._npmUser = { - name : auth.username, - email : auth.email + name: auth.username, + email: auth.email } var params = { - metadata : data, - body : createReadStream(tarballPath), - auth : auth + metadata: data, + body: createReadStream(tarballPath), + auth: auth } // registry-frontdoor cares about the access level, which is only // configurable for scoped packages - if (config.get("access")) { - if (!npa(data.name).scope && config.get("access") === "restricted") { + if (config.get('access')) { + if (!npa(data.name).scope && config.get('access') === 'restricted') { return cb(new Error("Can't restrict access to unscoped packages.")) } - params.access = config.get("access") + params.access = config.get('access') } registry.publish(registryBase, params, function (er) { - if (er && er.code === "EPUBLISHCONFLICT" && - npm.config.get("force") && !isRetry) { - log.warn("publish", "Forced publish over " + data._id) + if (er && er.code === 'EPUBLISHCONFLICT' && + npm.config.get('force') && !isRetry) { + log.warn('publish', 'Forced publish over ' + data._id) return npm.commands.unpublish([data._id], function (er) { // ignore errors. Use the force. Reach out with your feelings. // but if it fails again, then report the first error. @@ -144,7 +146,7 @@ function publish_ (arg, data, isRetry, cachedir, cb) { // report the unpublish error if this was a retry and unpublish failed if (er && isRetry && isRetry !== true) return cb(isRetry) if (er) return cb(er) - console.log("+ " + data._id) + console.log('+ ' + data._id) cb() }) }) diff --git a/lib/rebuild.js b/lib/rebuild.js index 53bd95cff..0e36c6361 100644 --- a/lib/rebuild.js +++ b/lib/rebuild.js @@ -1,27 +1,27 @@ module.exports = rebuild -var readInstalled = require("read-installed") - , semver = require("semver") - , log = require("npmlog") - , npm = require("./npm.js") - , npa = require("npm-package-arg") +var readInstalled = require('read-installed') +var semver = require('semver') +var log = require('npmlog') +var npm = require('./npm.js') +var npa = require('npm-package-arg') -rebuild.usage = "npm rebuild [[<@scope>/<name>]...]" +rebuild.usage = 'npm rebuild [[<@scope>/<name>]...]' -rebuild.completion = require("./utils/completion/installed-deep.js") +rebuild.completion = require('./utils/completion/installed-deep.js') function rebuild (args, cb) { - var opt = { depth: npm.config.get("depth"), dev: true } + var opt = { depth: npm.config.get('depth'), dev: true } readInstalled(npm.prefix, opt, function (er, data) { - log.info("readInstalled", typeof data) + log.info('readInstalled', typeof data) if (er) return cb(er) var set = filter(data, args) - , folders = Object.keys(set).filter(function (f) { - return f !== npm.prefix - }) + var folders = Object.keys(set).filter(function (f) { + return f !== npm.prefix + }) if (!folders.length) return cb() - log.silly("rebuild set", folders) + log.silly('rebuild set', folders) cleanBuild(folders, set, cb) }) } @@ -31,8 +31,8 @@ function cleanBuild (folders, set, cb) { if (er) return cb(er) log.clearProgress() console.log(folders.map(function (f) { - return set[f] + " " + f - }).join("\n")) + return set[f] + ' ' + f + }).join('\n')) log.showProgress() cb() }) @@ -47,11 +47,11 @@ function filter (data, args, set, seen) { var pass if (!args.length) pass = true // rebuild everything else if (data.name && data._id) { - for (var i = 0, l = args.length; i < l; i ++) { + for (var i = 0, l = args.length; i < l; i++) { var arg = args[i] - , nv = npa(arg) - , n = nv.name - , v = nv.rawSpec + var nv = npa(arg) + var n = nv.name + var v = nv.rawSpec if (n !== data.name) continue if (!semver.satisfies(data.version, v, true)) continue pass = true @@ -59,7 +59,7 @@ function filter (data, args, set, seen) { } } if (pass && data._id) { - log.verbose("rebuild", "path, id", [data.path, data._id]) + log.verbose('rebuild', 'path, id', [data.path, data._id]) set[data.path] = data._id } // need to also dive through kids, always. @@ -68,7 +68,7 @@ function filter (data, args, set, seen) { Object.keys(data.dependencies || {}).forEach(function (d) { // return var dep = data.dependencies[d] - if (typeof dep === "string") return + if (typeof dep === 'string') return filter(dep, args, set, seen) }) return set diff --git a/lib/repo.js b/lib/repo.js index bbafaec3c..4bd200aff 100644 --- a/lib/repo.js +++ b/lib/repo.js @@ -1,14 +1,12 @@ module.exports = repo -repo.usage = "npm repo [<pkg>]" +repo.usage = 'npm repo [<pkg>]' -var npm = require("./npm.js") - , opener = require("opener") - , hostedGitInfo = require("hosted-git-info") - , url_ = require("url") - , fetchPackageMetadata = require("./fetch-package-metadata.js") - , mapToRegistry = require("./utils/map-to-registry.js") - , registry = npm.registry +var npm = require('./npm.js') +var opener = require('opener') +var hostedGitInfo = require('hosted-git-info') +var url_ = require('url') +var fetchPackageMetadata = require('./fetch-package-metadata.js') repo.completion = function (opts, cb) { // FIXME: there used to be registry completion here, but it stopped making @@ -17,8 +15,8 @@ repo.completion = function (opts, cb) { } function repo (args, cb) { - var n = args.length ? args[0] : "." - fetchPackageMetadata(n, ".", function (er, d) { + var n = args.length ? args[0] : '.' + fetchPackageMetadata(n, '.', function (er, d) { if (er) return cb(er) getUrlAndOpen(d, cb) }) @@ -26,29 +24,28 @@ function repo (args, cb) { function getUrlAndOpen (d, cb) { var r = d.repository - if (!r) return cb(new Error("no repository")) + if (!r) return cb(new Error('no repository')) // XXX remove this when npm@v1.3.10 from node 0.10 is deprecated // from https://github.com/npm/npm-www/issues/418 var info = hostedGitInfo.fromUrl(r.url) - url = info ? info.browse() : unknownHostedUrl(r.url) + var url = info ? info.browse() : unknownHostedUrl(r.url) - if (!url) return cb(new Error("no repository: could not get url")) + if (!url) return cb(new Error('no repository: could not get url')) - opener(url, { command: npm.config.get("browser") }, cb) + opener(url, { command: npm.config.get('browser') }, cb) } function unknownHostedUrl (url) { try { - var idx = url.indexOf("@") + var idx = url.indexOf('@') if (idx !== -1) { - url = url.slice(idx+1).replace(/:([^\d]+)/, "/$1") + url = url.slice(idx + 1).replace(/:([^\d]+)/, '/$1') } url = url_.parse(url) - var protocol = url.protocol === "https:" - ? "https:" - : "http:" - return protocol + "//" + (url.host || "") + - url.path.replace(/\.git$/, "") - } - catch(e) {} + var protocol = url.protocol === 'https:' + ? 'https:' + : 'http:' + return protocol + '//' + (url.host || '') + + url.path.replace(/\.git$/, '') + } catch(e) {} } diff --git a/lib/restart.js b/lib/restart.js index 69c4b913d..601249fd6 100644 --- a/lib/restart.js +++ b/lib/restart.js @@ -1 +1 @@ -module.exports = require("./utils/lifecycle.js").cmd("restart") +module.exports = require('./utils/lifecycle.js').cmd('restart') diff --git a/lib/root.js b/lib/root.js index 9310bda92..958361d35 100644 --- a/lib/root.js +++ b/lib/root.js @@ -1,11 +1,14 @@ module.exports = root -var npm = require("./npm.js") +var npm = require('./npm.js') -root.usage = "npm root [-g]" +root.usage = 'npm root [-g]' function root (args, silent, cb) { - if (typeof cb !== "function") cb = silent, silent = false + if (typeof cb !== 'function') { + cb = silent + silent = false + } if (!silent) console.log(npm.dir) process.nextTick(cb.bind(this, null, npm.dir)) } diff --git a/lib/run-script.js b/lib/run-script.js index 2ca30d0e8..cd57b4570 100644 --- a/lib/run-script.js +++ b/lib/run-script.js @@ -1,14 +1,14 @@ module.exports = runScript -var lifecycle = require("./utils/lifecycle.js") - , npm = require("./npm.js") - , path = require("path") - , readJson = require("read-package-json") - , log = require("npmlog") - , chain = require("slide").chain +var lifecycle = require('./utils/lifecycle.js') +var npm = require('./npm.js') +var path = require('path') +var readJson = require('read-package-json') +var log = require('npmlog') +var chain = require('slide').chain -runScript.usage = "npm run-script <command> [-- <args>...]" - + "\n\nalias: npm run" +runScript.usage = 'npm run-script <command> [-- <args>...]' + + '\n\nalias: npm run' runScript.completion = function (opts, cb) { @@ -20,20 +20,19 @@ runScript.completion = function (opts, cb) { if (argv.length === 3) { // either specified a script locally, in which case, done, // or a package, in which case, complete against its scripts - var json = path.join(npm.localPrefix, "package.json") + var json = path.join(npm.localPrefix, 'package.json') return readJson(json, function (er, d) { - if (er && er.code !== "ENOENT" && er.code !== "ENOTDIR") return cb(er) + if (er && er.code !== 'ENOENT' && er.code !== 'ENOTDIR') return cb(er) if (er) d = {} var scripts = Object.keys(d.scripts || {}) - console.error("local scripts", scripts) + console.error('local scripts', scripts) if (scripts.indexOf(argv[2]) !== -1) return cb() // ok, try to find out which package it was, then - var pref = npm.config.get("global") ? npm.config.get("prefix") + var pref = npm.config.get('global') ? npm.config.get('prefix') : npm.localPrefix - var pkgDir = path.resolve( pref, "node_modules" - , argv[2], "package.json" ) + var pkgDir = path.resolve(pref, 'node_modules', argv[2], 'package.json') readJson(pkgDir, function (er, d) { - if (er && er.code !== "ENOENT" && er.code !== "ENOTDIR") return cb(er) + if (er && er.code !== 'ENOENT' && er.code !== 'ENOTDIR') return cb(er) if (er) d = {} var scripts = Object.keys(d.scripts || {}) return cb(null, scripts) @@ -41,8 +40,8 @@ runScript.completion = function (opts, cb) { }) } - readJson(path.join(npm.localPrefix, "package.json"), function (er, d) { - if (er && er.code !== "ENOENT" && er.code !== "ENOTDIR") return cb(er) + readJson(path.join(npm.localPrefix, 'package.json'), function (er, d) { + if (er && er.code !== 'ENOENT' && er.code !== 'ENOTDIR') return cb(er) d = d || {} cb(null, Object.keys(d.scripts || {})) }) @@ -52,23 +51,29 @@ function runScript (args, cb) { if (!args.length) return list(cb) var pkgdir = npm.localPrefix - , cmd = args.shift() + var cmd = args.shift() - readJson(path.resolve(pkgdir, "package.json"), function (er, d) { + readJson(path.resolve(pkgdir, 'package.json'), function (er, d) { if (er) return cb(er) run(d, pkgdir, cmd, args, cb) }) } -function list(cb) { - var json = path.join(npm.localPrefix, "package.json") - var cmdList = [ "publish", "install", "uninstall" - , "test", "stop", "start", "restart" - ].reduce(function (l, p) { - return l.concat(["pre" + p, p, "post" + p]) - }, []) - return readJson(json, function(er, d) { - if (er && er.code !== "ENOENT" && er.code !== "ENOTDIR") return cb(er) +function list (cb) { + var json = path.join(npm.localPrefix, 'package.json') + var cmdList = [ + 'publish', + 'install', + 'uninstall', + 'test', + 'stop', + 'start', + 'restart' + ].reduce(function (l, p) { + return l.concat(['pre' + p, p, 'post' + p]) + }, []) + return readJson(json, function (er, d) { + if (er && er.code !== 'ENOENT' && er.code !== 'ENOTDIR') return cb(er) if (er) d = {} var allScripts = Object.keys(d.scripts || {}) var scripts = [] @@ -78,37 +83,36 @@ function list(cb) { else runScripts.push(script) }) - if (log.level === "silent") { + if (log.level === 'silent') { return cb(null, allScripts) } - if (npm.config.get("json")) { + if (npm.config.get('json')) { console.log(JSON.stringify(d.scripts || {}, null, 2)) return cb(null, allScripts) } - if (npm.config.get("parseable")) { - allScripts.forEach(function(script) { - console.log(script + ":" + d.scripts[script]) + if (npm.config.get('parseable')) { + allScripts.forEach(function (script) { + console.log(script + ':' + d.scripts[script]) }) return cb(null, allScripts) } - var s = "\n " - var prefix = " " + var s = '\n ' + var prefix = ' ' if (scripts.length) { - console.log("Lifecycle scripts included in %s:", d.name) + console.log('Lifecycle scripts included in %s:', d.name) } - scripts.forEach(function(script) { + scripts.forEach(function (script) { console.log(prefix + script + s + d.scripts[script]) }) if (!scripts.length && runScripts.length) { - console.log("Scripts available in %s via `npm run-script`:", d.name) + console.log('Scripts available in %s via `npm run-script`:', d.name) + } else if (runScripts.length) { + console.log('\navailable via `npm run-script`:') } - else if (runScripts.length) { - console.log("\navailable via `npm run-script`:") - } - runScripts.forEach(function(script) { + runScripts.forEach(function (script) { console.log(prefix + script + s + d.scripts[script]) }) return cb(null, allScripts) @@ -119,38 +123,38 @@ function run (pkg, wd, cmd, args, cb) { if (!pkg.scripts) pkg.scripts = {} var cmds - if (cmd === "restart" && !pkg.scripts.restart) { + if (cmd === 'restart' && !pkg.scripts.restart) { cmds = [ - "prestop", "stop", "poststop", - "restart", - "prestart", "start", "poststart" + 'prestop', 'stop', 'poststop', + 'restart', + 'prestart', 'start', 'poststart' ] } else { if (!pkg.scripts[cmd]) { - if (cmd === "test") { - pkg.scripts.test = "echo \"Error: no test specified\"" - } else if (cmd === "env") { - if (process.platform === "win32") { - log.verbose("run-script using default platform env: SET (Windows)") - pkg.scripts[cmd] = "SET" + if (cmd === 'test') { + pkg.scripts.test = 'echo \'Error: no test specified\'' + } else if (cmd === 'env') { + if (process.platform === 'win32') { + log.verbose('run-script using default platform env: SET (Windows)') + pkg.scripts[cmd] = 'SET' } else { - log.verbose("run-script using default platform env: env (Unix)") - pkg.scripts[cmd] = "env" + log.verbose('run-script using default platform env: env (Unix)') + pkg.scripts[cmd] = 'env' } - } else if (npm.config.get("if-present")) { - return cb(null); + } else if (npm.config.get('if-present')) { + return cb(null) } else { - return cb(new Error("missing script: " + cmd)) + return cb(new Error('missing script: ' + cmd)) } } cmds = [cmd] } if (!cmd.match(/^(pre|post)/)) { - cmds = ["pre"+cmd].concat(cmds).concat("post"+cmd) + cmds = ['pre' + cmd].concat(cmds).concat('post' + cmd) } - log.verbose("run-script", cmds) + log.verbose('run-script', cmds) chain(cmds.map(function (c) { // pass cli arguments after -- to script. if (pkg.scripts[c] && c === cmd) { @@ -165,8 +169,8 @@ function run (pkg, wd, cmd, args, cb) { // join arguments after '--' and pass them to script, // handle special characters such as ', ", ' '. function joinArgs (args) { - var joinedArgs = "" - args.forEach(function(arg) { + var joinedArgs = '' + args.forEach(function (arg) { joinedArgs += ' "' + arg.replace(/"/g, '\\"') + '"' }) return joinedArgs diff --git a/lib/search.js b/lib/search.js index 6dc1c027e..a029d62eb 100644 --- a/lib/search.js +++ b/lib/search.js @@ -1,18 +1,18 @@ module.exports = exports = search -var npm = require("./npm.js") - , columnify = require("columnify") - , updateIndex = require("./cache/update-index.js") +var npm = require('./npm.js') +var columnify = require('columnify') +var updateIndex = require('./cache/update-index.js') -search.usage = "npm search [--long] [search terms ...]" - + "\n\naliases: s, se" +search.usage = 'npm search [--long] [search terms ...]' + + '\n\naliases: s, se' search.completion = function (opts, cb) { var compl = {} - , partial = opts.partialWord - , ipartial = partial.toLowerCase() - , plen = partial.length + var partial = opts.partialWord + var ipartial = partial.toLowerCase() + var plen = partial.length // get the batch of data that matches so far. // this is an example of using npm.commands.search programmatically @@ -20,7 +20,7 @@ search.completion = function (opts, cb) { search(opts.conf.argv.remain.slice(2), true, function (er, data) { if (er) return cb(er) Object.keys(data).forEach(function (name) { - data[name].words.split(" ").forEach(function (w) { + data[name].words.split(' ').forEach(function (w) { if (w.toLowerCase().indexOf(ipartial) === 0) { compl[partial + w.substr(plen)] = true } @@ -31,19 +31,25 @@ search.completion = function (opts, cb) { } function search (args, silent, staleness, cb) { - if (typeof cb !== "function") cb = staleness, staleness = 600 - if (typeof cb !== "function") cb = silent, silent = false + if (typeof cb !== 'function') { + cb = staleness + staleness = 600 + } + if (typeof cb !== 'function') { + cb = silent + silent = false + } - var searchopts = npm.config.get("searchopts") - var searchexclude = npm.config.get("searchexclude") + var searchopts = npm.config.get('searchopts') + var searchexclude = npm.config.get('searchexclude') - if (typeof searchopts !== "string") searchopts = "" + if (typeof searchopts !== 'string') searchopts = '' searchopts = searchopts.split(/\s+/) var opts = searchopts.concat(args).map(function (s) { return s.toLowerCase() }).filter(function (s) { return s }) - if (typeof searchexclude === "string") { + if (typeof searchexclude === 'string') { searchexclude = searchexclude.split(/\s+/) } else { searchexclude = [] @@ -74,7 +80,7 @@ function filter (data, args, notArgs) { return Object.keys(data).map(function (d) { return data[d] }).filter(function (d) { - return typeof d === "object" + return typeof d === 'object' }).map(stripData).map(getWords).filter(function (data) { return filterWords(data, args, notArgs) }).reduce(function (l, r) { @@ -84,51 +90,52 @@ function filter (data, args, notArgs) { } function stripData (data) { - return { name: data.name - , description: npm.config.get("description") ? data.description : "" - , maintainers: (data.maintainers || []).map(function (m) { - return "=" + m.name - }) - , url: !Object.keys(data.versions || {}).length ? data.url : null - , keywords: data.keywords || [] - , version: Object.keys(data.versions || {})[0] || [] - , time: data.time - && data.time.modified - && (new Date(data.time.modified).toISOString() - .split("T").join(" ") - .replace(/:[0-9]{2}\.[0-9]{3}Z$/, "")) - .slice(0, -5) // remove time - || "prehistoric" - } + return { + name: data.name, + description: npm.config.get('description') ? data.description : '', + maintainers: (data.maintainers || []).map(function (m) { + return '=' + m.name + }), + url: !Object.keys(data.versions || {}).length ? data.url : null, + keywords: data.keywords || [], + version: Object.keys(data.versions || {})[0] || [], + time: data.time && + data.time.modified && + (new Date(data.time.modified).toISOString() // remove time + .split('T').join(' ') + .replace(/:[0-9]{2}\.[0-9]{3}Z$/, '')) + .slice(0, -5) || + 'prehistoric' + } } function getWords (data) { data.words = [ data.name ] .concat(data.description) .concat(data.maintainers) - .concat(data.url && ("<" + data.url + ">")) + .concat(data.url && ('<' + data.url + '>')) .concat(data.keywords) .map(function (f) { return f && f.trim && f.trim() }) .filter(function (f) { return f }) - .join(" ") + .join(' ') .toLowerCase() return data } function filterWords (data, args, notArgs) { var words = data.words - for (var i = 0, l = args.length; i < l; i ++) { + for (var i = 0, l = args.length; i < l; i++) { if (!match(words, args[i])) return false } - for (i = 0, l = notArgs.length; i < l; i ++) { + for (i = 0, l = notArgs.length; i < l; i++) { if (match(words, notArgs[i])) return false } return true } function match (words, arg) { - if (arg.charAt(0) === "/") { - arg = arg.replace(/\/$/, "") + if (arg.charAt(0) === '/') { + arg = arg.replace(/\/$/, '') arg = new RegExp(arg.substr(1, arg.length - 1)) return words.match(arg) } @@ -136,68 +143,71 @@ function match (words, arg) { } function prettify (data, args) { - var searchsort = (npm.config.get("searchsort") || "NAME").toLowerCase() - , sortField = searchsort.replace(/^\-+/, "") - , searchRev = searchsort.charAt(0) === "-" - , truncate = !npm.config.get("long") + var searchsort = (npm.config.get('searchsort') || 'NAME').toLowerCase() + var sortField = searchsort.replace(/^\-+/, '') + var searchRev = searchsort.charAt(0) === '-' + var truncate = !npm.config.get('long') if (Object.keys(data).length === 0) { - return "No match found for "+(args.map(JSON.stringify).join(" ")) + return 'No match found for ' + (args.map(JSON.stringify).join(' ')) } var lines = Object.keys(data).map(function (d) { // strip keyname return data[d] - }).map(function(dat) { + }).map(function (dat) { dat.author = dat.maintainers delete dat.maintainers dat.date = dat.time delete dat.time return dat - }).map(function(dat) { + }).map(function (dat) { // split keywords on whitespace or , - if (typeof dat.keywords === "string") { + if (typeof dat.keywords === 'string') { dat.keywords = dat.keywords.split(/[,\s]+/) } if (Array.isArray(dat.keywords)) { - dat.keywords = dat.keywords.join(" ") + dat.keywords = dat.keywords.join(' ') } // split author on whitespace or , - if (typeof dat.author === "string") { + if (typeof dat.author === 'string') { dat.author = dat.author.split(/[,\s]+/) } if (Array.isArray(dat.author)) { - dat.author = dat.author.join(" ") + dat.author = dat.author.join(' ') } return dat }) - lines.sort(function(a, b) { + lines.sort(function (a, b) { var aa = a[sortField].toLowerCase() - , bb = b[sortField].toLowerCase() + var bb = b[sortField].toLowerCase() return aa === bb ? 0 : aa < bb ? -1 : 1 }) if (searchRev) lines.reverse() - var columns = npm.config.get("description") - ? ["name", "description", "author", "date", "version", "keywords"] - : ["name", "author", "date", "version", "keywords"] - - var output = columnify(lines, { - include: columns - , truncate: truncate - , config: { - name: { maxWidth: 40, truncate: false, truncateMarker: "" } - , description: { maxWidth: 60 } - , author: { maxWidth: 20 } - , date: { maxWidth: 11 } - , version: { maxWidth: 11 } - , keywords: { maxWidth: Infinity } - } - }) + var columns = npm.config.get('description') + ? ['name', 'description', 'author', 'date', 'version', 'keywords'] + : ['name', 'author', 'date', 'version', 'keywords'] + + var output = columnify( + lines, + { + include: columns, + truncate: truncate, + config: { + name: { maxWidth: 40, truncate: false, truncateMarker: '' }, + description: { maxWidth: 60 }, + author: { maxWidth: 20 }, + date: { maxWidth: 11 }, + version: { maxWidth: 11 }, + keywords: { maxWidth: Infinity } + } + } + ) output = trimToMaxWidth(output) output = highlightSearchTerms(output, args) @@ -205,63 +215,63 @@ function prettify (data, args) { } var colors = [31, 33, 32, 36, 34, 35 ] - , cl = colors.length +var cl = colors.length function addColorMarker (str, arg, i) { var m = i % cl + 1 - , markStart = String.fromCharCode(m) - , markEnd = String.fromCharCode(0) - - if (arg.charAt(0) === "/") { - //arg = arg.replace(/\/$/, "") - return str.replace( new RegExp(arg.substr(1, arg.length - 2), "gi") - , function (bit) { return markStart + bit + markEnd } ) - + var markStart = String.fromCharCode(m) + var markEnd = String.fromCharCode(0) + + if (arg.charAt(0) === '/') { + return str.replace( + new RegExp(arg.substr(1, arg.length - 2), 'gi'), + function (bit) { return markStart + bit + markEnd } + ) } // just a normal string, do the split/map thing var pieces = str.toLowerCase().split(arg.toLowerCase()) - , p = 0 + var p = 0 return pieces.map(function (piece) { piece = str.substr(p, piece.length) - var mark = markStart - + str.substr(p+piece.length, arg.length) - + markEnd + var mark = markStart + + str.substr(p + piece.length, arg.length) + + markEnd p += piece.length + arg.length return piece + mark - }).join("") + }).join('') } function colorize (line) { - for (var i = 0; i < cl; i ++) { + for (var i = 0; i < cl; i++) { var m = i + 1 - var color = npm.color ? "\033["+colors[i]+"m" : "" + var color = npm.color ? '\u001B[' + colors[i] + 'm' : '' line = line.split(String.fromCharCode(m)).join(color) } - var uncolor = npm.color ? "\033[0m" : "" - return line.split("\u0000").join(uncolor) + var uncolor = npm.color ? '\u001B[0m' : '' + return line.split('\u0000').join(uncolor) } -function getMaxWidth() { +function getMaxWidth () { var cols try { - var tty = require("tty") - , stdout = process.stdout + var tty = require('tty') + var stdout = process.stdout cols = !tty.isatty(stdout.fd) ? Infinity : process.stdout.getWindowSize()[0] cols = (cols === 0) ? Infinity : cols } catch (ex) { cols = Infinity } return cols } -function trimToMaxWidth(str) { +function trimToMaxWidth (str) { var maxWidth = getMaxWidth() - return str.split("\n").map(function(line) { + return str.split('\n').map(function (line) { return line.slice(0, maxWidth) - }).join("\n") + }).join('\n') } -function highlightSearchTerms(str, terms) { +function highlightSearchTerms (str, terms) { terms.forEach(function (arg, i) { str = addColorMarker(str, arg, i) }) diff --git a/lib/set.js b/lib/set.js index c83602ec1..b5e7376fb 100644 --- a/lib/set.js +++ b/lib/set.js @@ -1,13 +1,13 @@ module.exports = set -set.usage = "npm set <key> <value> (See `npm config`)" +set.usage = 'npm set <key> <value> (See `npm config`)' -var npm = require("./npm.js") +var npm = require('./npm.js') set.completion = npm.commands.config.completion function set (args, cb) { if (!args.length) return cb(set.usage) - npm.commands.config(["set"].concat(args), cb) + npm.commands.config(['set'].concat(args), cb) } diff --git a/lib/star.js b/lib/star.js index b6fc49326..29c4037d0 100644 --- a/lib/star.js +++ b/lib/star.js @@ -1,13 +1,12 @@ - module.exports = star -var npm = require("./npm.js") - , log = require("npmlog") - , asyncMap = require("slide").asyncMap - , mapToRegistry = require("./utils/map-to-registry.js") +var npm = require('./npm.js') +var log = require('npmlog') +var asyncMap = require('slide').asyncMap +var mapToRegistry = require('./utils/map-to-registry.js') -star.usage = "npm star [<pkg>...]\n" - + "npm unstar [<pkg>...]" +star.usage = 'npm star [<pkg>...]\n' + + 'npm unstar [<pkg>...]' star.completion = function (opts, cb) { // FIXME: there used to be registry completion here, but it stopped making @@ -17,22 +16,22 @@ star.completion = function (opts, cb) { function star (args, cb) { if (!args.length) return cb(star.usage) - var s = npm.config.get("unicode") ? "\u2605 " : "(*)" - , u = npm.config.get("unicode") ? "\u2606 " : "( )" - , using = !(npm.command.match(/^un/)) + var s = npm.config.get('unicode') ? '\u2605 ' : '(*)' + var u = npm.config.get('unicode') ? '\u2606 ' : '( )' + var using = !(npm.command.match(/^un/)) if (!using) s = u asyncMap(args, function (pkg, cb) { mapToRegistry(pkg, npm.config, function (er, uri, auth) { if (er) return cb(er) var params = { - starred : using, - auth : auth + starred: using, + auth: auth } npm.registry.star(uri, params, function (er, data, raw, req) { if (!er) { - console.log(s + " "+pkg) - log.verbose("star", data) + console.log(s + ' ' + pkg) + log.verbose('star', data) } cb(er, data, raw, req) }) diff --git a/lib/stars.js b/lib/stars.js index e8cb23fb4..4ad8f02e5 100644 --- a/lib/stars.js +++ b/lib/stars.js @@ -1,10 +1,10 @@ module.exports = stars -gstars.usage = "npm stars [<user>]" +stars.usage = 'npm stars [<user>]' -var npm = require("./npm.js") - , log = require("npmlog") - , mapToRegistry = require("./utils/map-to-registry.js") +var npm = require('./npm.js') +var log = require('npmlog') +var mapToRegistry = require('./utils/map-to-registry.js') function stars (args, cb) { npm.commands.whoami([], true, function (er, username) { @@ -20,12 +20,12 @@ function stars (args, cb) { if (er.code !== 'ENEEDAUTH') return cb(er) } - mapToRegistry("", npm.config, function (er, uri, auth) { + mapToRegistry('', npm.config, function (er, uri, auth) { if (er) return cb(er) var params = { - username : name, - auth : auth + username: name, + auth: auth } npm.registry.stars(uri, params, showstars) }) @@ -35,9 +35,9 @@ function stars (args, cb) { if (er) return cb(er) if (data.rows.length === 0) { - log.warn("stars", "user has not starred any packages.") + log.warn('stars', 'user has not starred any packages.') } else { - data.rows.forEach(function(a) { + data.rows.forEach(function (a) { console.log(a.value) }) } diff --git a/lib/start.js b/lib/start.js index 98823825b..85d61e78d 100644 --- a/lib/start.js +++ b/lib/start.js @@ -1 +1 @@ -module.exports = require("./utils/lifecycle.js").cmd("start") +module.exports = require('./utils/lifecycle.js').cmd('start') diff --git a/lib/stop.js b/lib/stop.js index 8ea5ba6aa..e4d02ff28 100644 --- a/lib/stop.js +++ b/lib/stop.js @@ -1 +1 @@ -module.exports = require("./utils/lifecycle.js").cmd("stop") +module.exports = require('./utils/lifecycle.js').cmd('stop') diff --git a/lib/substack.js b/lib/substack.js index 1929f1873..c39a5dcc4 100644 --- a/lib/substack.js +++ b/lib/substack.js @@ -1,15 +1,16 @@ module.exports = substack -var npm = require("./npm.js") +var npm = require('./npm.js') -var isms = - [ "\033[32mbeep \033[35mboop\033[m" - , "Replace your configs with services" - , "SEPARATE ALL THE CONCERNS!" - , "MODULE ALL THE THINGS!" - , "\\o/" - , "but first, burritos" - , "full time mad scientist here" - , "c/,,\\" ] +var isms = [ + '\u001b[32mbeep \u001b[35mboop\u001b[m', + 'Replace your configs with services', + 'SEPARATE ALL THE CONCERNS!', + 'MODULE ALL THE THINGS!', + '\\o/', + 'but first, burritos', + 'full time mad scientist here', + 'c/,,\\' +] function substack (args, cb) { var i = Math.floor(Math.random() * isms.length) diff --git a/lib/tag.js b/lib/tag.js index 24d54676a..01db4d8ea 100644 --- a/lib/tag.js +++ b/lib/tag.js @@ -1,41 +1,41 @@ // turns out tagging isn't very complicated // all the smarts are in the couch. module.exports = tag -tag.usage = "[DEPRECATED] npm tag <name>@<version> [<tag>]" - + "\nSee `dist-tag`" +tag.usage = '[DEPRECATED] npm tag <name>@<version> [<tag>]' + + '\nSee `dist-tag`' -tag.completion = require("./unpublish.js").completion +tag.completion = require('./unpublish.js').completion -var npm = require("./npm.js") - , mapToRegistry = require("./utils/map-to-registry.js") - , npa = require("npm-package-arg") - , semver = require("semver") - , log = require("npmlog") +var npm = require('./npm.js') +var mapToRegistry = require('./utils/map-to-registry.js') +var npa = require('npm-package-arg') +var semver = require('semver') +var log = require('npmlog') function tag (args, cb) { - var thing = npa(args.shift() || "") - , project = thing.name - , version = thing.rawSpec - , t = args.shift() || npm.config.get("tag") + var thing = npa(args.shift() || '') + var project = thing.name + var version = thing.rawSpec + var t = args.shift() || npm.config.get('tag') t = t.trim() - if (!project || !version || !t) return cb("Usage:\n"+tag.usage) + if (!project || !version || !t) return cb('Usage:\n' + tag.usage) if (semver.validRange(t)) { - var er = new Error("Tag name must not be a valid SemVer range: " + t) + var er = new Error('Tag name must not be a valid SemVer range: ' + t) return cb(er) } - log.warn("tag", "This command is deprecated. Use `npm dist-tag` instead.") + log.warn('tag', 'This command is deprecated. Use `npm dist-tag` instead.') mapToRegistry(project, npm.config, function (er, uri, auth) { if (er) return cb(er) var params = { - version : version, - tag : t, - auth : auth + version: version, + tag: t, + auth: auth } npm.registry.tag(uri, params, cb) }) diff --git a/lib/test.js b/lib/test.js index dd4994cf2..cbc758217 100644 --- a/lib/test.js +++ b/lib/test.js @@ -1,12 +1,12 @@ module.exports = test -var testCmd = require("./utils/lifecycle.js").cmd("test") +var testCmd = require('./utils/lifecycle.js').cmd('test') function test (args, cb) { testCmd(args, function (er) { if (!er) return cb() - if (er.code === "ELIFECYCLE") { - return cb("Test failed. See above for more details.") + if (er.code === 'ELIFECYCLE') { + return cb('Test failed. See above for more details.') } return cb(er) }) diff --git a/lib/unbuild.js b/lib/unbuild.js index 998d6e39f..670cfc125 100644 --- a/lib/unbuild.js +++ b/lib/unbuild.js @@ -1,62 +1,70 @@ module.exports = unbuild module.exports.rmStuff = rmStuff -unbuild.usage = "npm unbuild <folder>\n(this is plumbing)" +unbuild.usage = 'npm unbuild <folder>\n(this is plumbing)' -var readJson = require("read-package-json") - , gentlyRm = require("./utils/gently-rm.js") - , npm = require("./npm.js") - , path = require("path") - , isInside = require("path-is-inside") - , lifecycle = require("./utils/lifecycle.js") - , asyncMap = require("slide").asyncMap - , chain = require("slide").chain - , log = require("npmlog") - , build = require("./build.js") +var readJson = require('read-package-json') +var gentlyRm = require('./utils/gently-rm.js') +var npm = require('./npm.js') +var path = require('path') +var isInside = require('path-is-inside') +var lifecycle = require('./utils/lifecycle.js') +var asyncMap = require('slide').asyncMap +var chain = require('slide').chain +var log = require('npmlog') +var build = require('./build.js') // args is a list of folders. // remove any bins/etc, and then delete the folder. function unbuild (args, silent, cb) { - if (typeof silent === "function") cb = silent, silent = false + if (typeof silent === 'function') { + cb = silent + silent = false + } asyncMap(args, unbuild_(silent), cb) } -function unbuild_ (silent) { return function (folder, cb_) { - function cb (er) { - cb_(er, path.relative(npm.root, folder)) - } - folder = path.resolve(folder) - var base = isInside(folder, npm.prefix) ? npm.prefix : folder - delete build._didBuild[folder] - log.verbose("unbuild", folder.substr(npm.prefix.length + 1)) - readJson(path.resolve(folder, "package.json"), function (er, pkg) { - // if no json, then just trash it, but no scripts or whatever. - if (er) return gentlyRm(folder, false, base, cb) - chain - ( [ [lifecycle, pkg, "preuninstall", folder, false, true] - , [lifecycle, pkg, "uninstall", folder, false, true] - , !silent && function(cb) { +function unbuild_ (silent) { + return function (folder, cb_) { + function cb (er) { + cb_(er, path.relative(npm.root, folder)) + } + folder = path.resolve(folder) + var base = isInside(folder, npm.prefix) ? npm.prefix : folder + delete build._didBuild[folder] + log.verbose('unbuild', folder.substr(npm.prefix.length + 1)) + readJson(path.resolve(folder, 'package.json'), function (er, pkg) { + // if no json, then just trash it, but no scripts or whatever. + if (er) return gentlyRm(folder, false, base, cb) + chain( + [ + [lifecycle, pkg, 'preuninstall', folder, false, true], + [lifecycle, pkg, 'uninstall', folder, false, true], + !silent && function (cb) { log.clearProgress() - console.log("unbuild " + pkg._id) + console.log('unbuild ' + pkg._id) log.showProgress() cb() - } - , [rmStuff, pkg, folder] - , [lifecycle, pkg, "postuninstall", folder, false, true] - , [gentlyRm, folder, false, base] ] - , cb ) - }) -}} + }, + [rmStuff, pkg, folder], + [lifecycle, pkg, 'postuninstall', folder, false, true], + [gentlyRm, folder, false, base] + ], + cb + ) + }) + } +} function rmStuff (pkg, folder, cb) { // if it's global, and folder is in {prefix}/node_modules, // then bins are in {prefix}/bin // otherwise, then bins are in folder/../.bin var parent = path.dirname(folder) - , gnm = npm.dir - , top = gnm === parent + var gnm = npm.dir + var top = gnm === parent - log.verbose("unbuild rmStuff", pkg._id, "from", gnm) - if (!top) log.verbose("unbuild rmStuff", "in", parent) + log.verbose('unbuild rmStuff', pkg._id, 'from', gnm) + if (!top) log.verbose('unbuild rmStuff', 'in', parent) asyncMap([rmBins, rmMans], function (fn, cb) { fn(pkg, folder, parent, top, cb) }, cb) @@ -64,11 +72,11 @@ function rmStuff (pkg, folder, cb) { function rmBins (pkg, folder, parent, top, cb) { if (!pkg.bin) return cb() - var binRoot = top ? npm.bin : path.resolve(parent, ".bin") + var binRoot = top ? npm.bin : path.resolve(parent, '.bin') asyncMap(Object.keys(pkg.bin), function (b, cb) { - if (process.platform === "win32") { - chain([ [gentlyRm, path.resolve(binRoot, b) + ".cmd", true] - , [gentlyRm, path.resolve(binRoot, b), true] ], cb) + if (process.platform === 'win32') { + chain([ [gentlyRm, path.resolve(binRoot, b) + '.cmd', true], + [gentlyRm, path.resolve(binRoot, b), true] ], cb) } else { gentlyRm(path.resolve(binRoot, b), true, cb) } @@ -76,14 +84,14 @@ function rmBins (pkg, folder, parent, top, cb) { } function rmMans (pkg, folder, parent, top, cb) { - if (!pkg.man - || !top - || process.platform === "win32" - || !npm.config.get("global")) { + if (!pkg.man || + !top || + process.platform === 'win32' || + !npm.config.get('global')) { return cb() } - var manRoot = path.resolve(npm.config.get("prefix"), "share", "man") - log.verbose("rmMans", "man files are", pkg.man, "in", manRoot) + var manRoot = path.resolve(npm.config.get('prefix'), 'share', 'man') + log.verbose('rmMans', 'man files are', pkg.man, 'in', manRoot) asyncMap(pkg.man, function (man, cb) { if (Array.isArray(man)) { man.forEach(rmMan) @@ -92,25 +100,25 @@ function rmMans (pkg, folder, parent, top, cb) { } function rmMan (man) { - log.silly("rmMan", "preparing to remove", man) + log.silly('rmMan', 'preparing to remove', man) var parseMan = man.match(/(.*\.([0-9]+)(\.gz)?)$/) if (!parseMan) { log.error( - "rmMan", man, "is not a valid name for a man file.", - "Man files must end with a number, " + - "and optionally a .gz suffix if they are compressed." + 'rmMan', man, 'is not a valid name for a man file.', + 'Man files must end with a number, ' + + 'and optionally a .gz suffix if they are compressed.' ) return cb() } var stem = parseMan[1] var sxn = parseMan[2] - var gz = parseMan[3] || "" + var gz = parseMan[3] || '' var bn = path.basename(stem) var manDest = path.join( manRoot, - "man"+sxn, - (bn.indexOf(pkg.name) === 0 ? bn : pkg.name+"-"+bn)+"."+sxn+gz + 'man' + sxn, + (bn.indexOf(pkg.name) === 0 ? bn : pkg.name + '-' + bn) + '.' + sxn + gz ) gentlyRm(manDest, true, cb) } diff --git a/lib/uninstall.js b/lib/uninstall.js index 33de8da64..b7b9e3bb5 100644 --- a/lib/uninstall.js +++ b/lib/uninstall.js @@ -29,7 +29,7 @@ function uninstall (args, cb) { : npm.prefix var dryrun = !!npm.config.get('dry-run') - if (args.length === 1 && args[0] === ".") args = [] + if (args.length === 1 && args[0] === '.') args = [] args = args.filter(function (a) { return path.resolve(a) !== where }) @@ -38,8 +38,8 @@ function uninstall (args, cb) { new Uninstaller(where, dryrun, args).run(cb) } else { // remove this package from the global space, if it's installed there - readJson(path.resolve(npm.localPrefix, "package.json"), function (er, pkg) { - if (er && er.code !== "ENOENT" && er.code !== "ENOTDIR") return cb(er) + readJson(path.resolve(npm.localPrefix, 'package.json'), function (er, pkg) { + if (er && er.code !== 'ENOENT' && er.code !== 'ENOTDIR') return cb(er) if (er) return cb(uninstall.usage) new Uninstaller(where, dryrun, [pkg.name]).run(cb) }) diff --git a/lib/unpublish.js b/lib/unpublish.js index c692730a9..63f87b820 100644 --- a/lib/unpublish.js +++ b/lib/unpublish.js @@ -1,15 +1,15 @@ module.exports = unpublish -var log = require("npmlog") -var npm = require("./npm.js") -var readJson = require("read-package-json") -var path = require("path") -var mapToRegistry = require("./utils/map-to-registry.js") -var npa = require("npm-package-arg") -var getPublishConfig = require("./utils/get-publish-config.js") +var log = require('npmlog') +var npm = require('./npm.js') +var readJson = require('read-package-json') +var path = require('path') +var mapToRegistry = require('./utils/map-to-registry.js') +var npa = require('npm-package-arg') +var getPublishConfig = require('./utils/get-publish-config.js') -unpublish.usage = "npm unpublish [<@scope>/]<pkg>[@<version>]" +unpublish.usage = 'npm unpublish [<@scope>/]<pkg>[@<version>]' unpublish.completion = function (opts, cb) { if (opts.conf.argv.remain.length >= 3) return cb() @@ -18,11 +18,11 @@ unpublish.completion = function (opts, cb) { var un = encodeURIComponent(username) if (!un) return cb() - var byUser = "-/by-user/" + un + var byUser = '-/by-user/' + un mapToRegistry(byUser, npm.config, function (er, uri, auth) { if (er) return cb(er) - npm.registry.get(uri, { auth : auth }, function (er, pkgs) { + npm.registry.get(uri, { auth: auth }, function (er, pkgs) { // do a bit of filtering at this point, so that we don't need // to fetch versions for more than one thing, but also don't // accidentally a whole project. @@ -36,12 +36,12 @@ unpublish.completion = function (opts, cb) { mapToRegistry(pkgs[0], npm.config, function (er, uri, auth) { if (er) return cb(er) - npm.registry.get(uri, { auth : auth }, function (er, d) { + npm.registry.get(uri, { auth: auth }, function (er, d) { if (er) return cb(er) var vers = Object.keys(d.versions) if (!vers.length) return cb(null, pkgs) return cb(null, vers.map(function (v) { - return pkgs[0] + "@" + v + return pkgs[0] + '@' + v })) }) }) @@ -54,24 +54,26 @@ function unpublish (args, cb) { if (args.length > 1) return cb(unpublish.usage) var thing = args.length ? npa(args[0]) : {} - , project = thing.name - , version = thing.rawSpec - - log.silly("unpublish", "args[0]", args[0]) - log.silly("unpublish", "thing", thing) - if (!version && !npm.config.get("force")) { - return cb("Refusing to delete entire project.\n" - + "Run with --force to do this.\n" - + unpublish.usage) + var project = thing.name + var version = thing.rawSpec + + log.silly('unpublish', 'args[0]', args[0]) + log.silly('unpublish', 'thing', thing) + if (!version && !npm.config.get('force')) { + return cb( + 'Refusing to delete entire project.\n' + + 'Run with --force to do this.\n' + + unpublish.usage + ) } if (!project || path.resolve(project) === npm.localPrefix) { // if there's a package.json in the current folder, then // read the package name and version out of that. - var cwdJson = path.join(npm.localPrefix, "package.json") + var cwdJson = path.join(npm.localPrefix, 'package.json') return readJson(cwdJson, function (er, data) { - if (er && er.code !== "ENOENT" && er.code !== "ENOTDIR") return cb(er) - if (er) return cb("Usage:\n" + unpublish.usage) + if (er && er.code !== 'ENOENT' && er.code !== 'ENOTDIR') return cb(er) + if (er) return cb('Usage:\n' + unpublish.usage) log.verbose('unpublish', data) gotProject(data.name, data.version, data.publishConfig, cb) }) @@ -87,7 +89,7 @@ function gotProject (project, version, publishConfig, cb_) { function cb (er) { if (er) return cb_(er) - console.log("- " + project + (version ? "@" + version : "")) + console.log('- ' + project + (version ? '@' + version : '')) cb_() } @@ -96,9 +98,9 @@ function gotProject (project, version, publishConfig, cb_) { var registry = mappedConfig.client // remove from the cache first - npm.commands.cache(["clean", project, version], function (er) { + npm.commands.cache(['clean', project, version], function (er) { if (er) { - log.error("unpublish", "Failed to clean cache") + log.error('unpublish', 'Failed to clean cache') return cb(er) } diff --git a/lib/utils/completion/file-completion.js b/lib/utils/completion/file-completion.js index 6ce2f8346..78777a025 100644 --- a/lib/utils/completion/file-completion.js +++ b/lib/utils/completion/file-completion.js @@ -1,21 +1,24 @@ module.exports = fileCompletion -var mkdir = require("mkdirp") - , path = require("path") - , glob = require("glob") +var mkdir = require('mkdirp') +var path = require('path') +var glob = require('glob') function fileCompletion (root, req, depth, cb) { - if (typeof cb !== "function") cb = depth, depth = Infinity + if (typeof cb !== 'function') { + cb = depth + depth = Infinity + } mkdir(root, function (er) { if (er) return cb(er) // can be either exactly the req, or a descendent - var pattern = root + "/{" + req + "," + req + "/**/*}" - , opts = { mark: true, dot: true, maxDepth: depth } + var pattern = root + '/{' + req + ',' + req + '/**/*}' + var opts = { mark: true, dot: true, maxDepth: depth } glob(pattern, opts, function (er, files) { if (er) return cb(er) return cb(null, (files || []).map(function (f) { - var tail = f.substr(root.length + 1).replace(/^\//, "") + var tail = f.substr(root.length + 1).replace(/^\//, '') return path.join(req, tail) })) }) diff --git a/lib/utils/completion/installed-deep.js b/lib/utils/completion/installed-deep.js index 5fb67d263..146a4d790 100644 --- a/lib/utils/completion/installed-deep.js +++ b/lib/utils/completion/installed-deep.js @@ -1,21 +1,25 @@ module.exports = installedDeep -var npm = require("../../npm.js") - , readInstalled = require("read-installed") +var npm = require('../../npm.js') +var readInstalled = require('read-installed') function installedDeep (opts, cb) { var local - , global - , depth = npm.config.get("depth") - , opt = { depth: depth, dev: true } + var global + var depth = npm.config.get('depth') + var opt = { depth: depth, dev: true } - if (npm.config.get("global")) local = [], next() - else readInstalled(npm.prefix, opt, function (er, data) { - local = getNames(data || {}) + if (npm.config.get('global')) { + local = [] next() - }) + } else { + readInstalled(npm.prefix, opt, function (er, data) { + local = getNames(data || {}) + next() + }) + } - readInstalled(npm.config.get("prefix"), opt, function (er, data) { + readInstalled(npm.config.get('prefix'), opt, function (er, data) { global = getNames(data || {}) next() }) @@ -37,9 +41,9 @@ function installedDeep (opts, cb) { function next () { if (!local || !global) return - if (!npm.config.get("global")) { + if (!npm.config.get('global')) { global = global.map(function (g) { - return [g, "-g"] + return [g, '-g'] }) } var names = local.concat(global) diff --git a/lib/utils/completion/installed-shallow.js b/lib/utils/completion/installed-shallow.js index 8d64649d5..bf692fede 100644 --- a/lib/utils/completion/installed-shallow.js +++ b/lib/utils/completion/installed-shallow.js @@ -1,31 +1,39 @@ module.exports = installedShallow -var npm = require("../../npm.js") - , fs = require("graceful-fs") - , path = require("path") - , readJson = require("read-package-json") - , asyncMap = require("slide").asyncMap +var npm = require('../../npm.js') +var fs = require('graceful-fs') +var path = require('path') +var readJson = require('read-package-json') +var asyncMap = require('slide').asyncMap function installedShallow (opts, filter, cb) { - if (typeof cb !== "function") cb = filter, filter = null + if (typeof cb !== 'function') { + cb = filter + filter = null + } var conf = opts.conf - , args = conf.argv.remain + var args = conf.argv.remain if (args.length > 3) return cb() var local - , global - , localDir = npm.dir - , globalDir = npm.globalDir - if (npm.config.get("global")) local = [], next() - else fs.readdir(localDir, function (er, pkgs) { - local = (pkgs || []).filter(function (p) { - return p.charAt(0) !== "." - }) + var global + var localDir = npm.dir + var globalDir = npm.globalDir + if (npm.config.get('global')) { + local = [] next() - }) + } else { + fs.readdir(localDir, function (er, pkgs) { + local = (pkgs || []).filter(function (p) { + return p.charAt(0) !== '.' + }) + next() + }) + } + fs.readdir(globalDir, function (er, pkgs) { global = (pkgs || []).filter(function (p) { - return p.charAt(0) !== "." + return p.charAt(0) !== '.' }) next() }) @@ -37,7 +45,7 @@ function installedShallow (opts, filter, cb) { function filterInstalled (local, global, filter, cb) { var fl - , fg + var fg if (!filter) { fl = local @@ -46,7 +54,7 @@ function filterInstalled (local, global, filter, cb) { } asyncMap(local, function (p, cb) { - readJson(path.join(npm.dir, p, "package.json"), function (er, d) { + readJson(path.join(npm.dir, p, 'package.json'), function (er, d) { if (!d || !filter(d)) return cb(null, []) return cb(null, d.name) }) @@ -57,7 +65,7 @@ function filterInstalled (local, global, filter, cb) { var globalDir = npm.globalDir asyncMap(global, function (p, cb) { - readJson(path.join(globalDir, p, "package.json"), function (er, d) { + readJson(path.join(globalDir, p, 'package.json'), function (er, d) { if (!d || !filter(d)) return cb(null, []) return cb(null, d.name) }) @@ -68,12 +76,12 @@ function filterInstalled (local, global, filter, cb) { function next () { if (!fg || !fl) return - if (!npm.config.get("global")) { + if (!npm.config.get('global')) { fg = fg.map(function (g) { - return [g, "-g"] + return [g, '-g'] }) } - console.error("filtered", fl, fg) + console.error('filtered', fl, fg) return cb(null, fl.concat(fg)) } } diff --git a/lib/utils/depr-check.js b/lib/utils/depr-check.js index 7166348b0..89cf40273 100644 --- a/lib/utils/depr-check.js +++ b/lib/utils/depr-check.js @@ -1,13 +1,13 @@ -var log = require("npmlog") +var log = require('npmlog') var deprecated = {} - , deprWarned = {} +var deprWarned = {} module.exports = function deprCheck (data) { if (deprecated[data._id]) data.deprecated = deprecated[data._id] if (data.deprecated) deprecated[data._id] = data.deprecated else return if (!deprWarned[data._id]) { deprWarned[data._id] = true - log.warn("deprecated", "%s: %s", data._id, data.deprecated) + log.warn('deprecated', '%s: %s', data._id, data.deprecated) } } diff --git a/lib/utils/error-handler.js b/lib/utils/error-handler.js index 09dca8a94..10bf7b5a6 100644 --- a/lib/utils/error-handler.js +++ b/lib/utils/error-handler.js @@ -2,45 +2,47 @@ module.exports = errorHandler var cbCalled = false - , log = require("npmlog") - , npm = require("../npm.js") - , rm = require("rimraf") - , itWorked = false - , path = require("path") - , wroteLogFile = false - , exitCode = 0 - , rollbacks = npm.rollbacks - , chain = require("slide").chain - , writeStream = require("fs-write-stream-atomic") - , nameValidator = require("validate-npm-package-name") - - -process.on("exit", function (code) { +var log = require('npmlog') +var npm = require('../npm.js') +var rm = require('rimraf') +var itWorked = false +var path = require('path') +var wroteLogFile = false +var exitCode = 0 +var rollbacks = npm.rollbacks +var chain = require('slide').chain +var writeStream = require('fs-write-stream-atomic') +var nameValidator = require('validate-npm-package-name') + +process.on('exit', function (code) { log.disableProgress() if (!npm.config || !npm.config.loaded) return if (code) itWorked = false - if (itWorked) log.info("ok") + if (itWorked) log.info('ok') else { if (!cbCalled) { - log.error("", "cb() never called!") + log.error('', 'cb() never called!') } if (wroteLogFile) { // just a line break - if (log.levels[log.level] <= log.levels.error) console.error("") - - log.error("", - ["Please include the following file with any support request:" - ," " + path.resolve("npm-debug.log") - ].join("\n")) + if (log.levels[log.level] <= log.levels.error) console.error('') + + log.error( + '', + [ + 'Please include the following file with any support request:', + ' ' + path.resolve('npm-debug.log') + ].join('\n') + ) wroteLogFile = false } if (code) { - log.error("code", code) + log.error('code', code) } } - var doExit = npm.config.get("_exit") + var doExit = npm.config.get('_exit') if (doExit) { // actually exit. if (exitCode === 0 && !itWorked) { @@ -55,9 +57,9 @@ process.on("exit", function (code) { function exit (code, noLog) { exitCode = exitCode || process.exitCode || code - var doExit = npm.config ? npm.config.get("_exit") : true - log.verbose("exit", [code, doExit]) - if (log.level === "silent") noLog = true + var doExit = npm.config ? npm.config.get('_exit') : true + log.verbose('exit', [code, doExit]) + if (log.level === 'silent') noLog = true if (rollbacks.length) { chain(rollbacks.map(function (f) { @@ -66,22 +68,22 @@ function exit (code, noLog) { } }), function (er) { if (er) { - log.error("error rolling back", er) + log.error('error rolling back', er) if (!code) errorHandler(er) - else if (noLog) rm("npm-debug.log", reallyExit.bind(null, er)) + else if (noLog) rm('npm-debug.log', reallyExit.bind(null, er)) else writeLogFile(reallyExit.bind(this, er)) } else { if (!noLog && code) writeLogFile(reallyExit) - else rm("npm-debug.log", reallyExit) + else rm('npm-debug.log', reallyExit) } }) rollbacks.length = 0 } else if (code && !noLog) writeLogFile(reallyExit) - else rm("npm-debug.log", reallyExit) + else rm('npm-debug.log', reallyExit) function reallyExit (er) { - if (er && !code) code = typeof er.errno === "number" ? er.errno : 1 + if (er && !code) code = typeof er.errno === 'number' ? er.errno : 1 // truncate once it's been written. log.record.length = 0 @@ -91,299 +93,384 @@ function exit (code, noLog) { // just emit a fake exit event. // if we're really exiting, then let it exit on its own, so that // in-process stuff can finish or clean up first. - if (!doExit) process.emit("exit", code) + if (!doExit) process.emit('exit', code) } } - function errorHandler (er) { log.disableProgress() - // console.error("errorHandler", er) + // console.error('errorHandler', er) if (!npm.config || !npm.config.loaded) { // logging won't work unless we pretend that it's ready - er = er || new Error("Exit prior to config file resolving.") + er = er || new Error('Exit prior to config file resolving.') console.error(er.stack || er.message) } if (cbCalled) { - er = er || new Error("Callback called more than once.") + er = er || new Error('Callback called more than once.') } cbCalled = true if (!er) return exit(0) - if (typeof er === "string") { - log.error("", er) + if (typeof er === 'string') { + log.error('', er) return exit(1, true) } else if (!(er instanceof Error)) { - log.error("weird error", er) + log.error('weird error', er) return exit(1, true) } var m = er.code || er.message.match(/^(?:Error: )?(E[A-Z]+)/) - if (m && !er.code) er.code = m - - ; [ "type" - , "fstream_path" - , "fstream_unc_path" - , "fstream_type" - , "fstream_class" - , "fstream_finish_call" - , "fstream_linkpath" - , "stack" - , "fstream_stack" - , "statusCode" - , "pkgid" - ].forEach(function (k) { - var v = er[k] - if (!v) return - if (k === "fstream_stack") v = v.join("\n") - log.verbose(k, v) - }) + if (m && !er.code) { + er.code = m + } - log.verbose("cwd", process.cwd()) - - var os = require("os") - // log.error("System", os.type() + " " + os.release()) - // log.error("command", process.argv.map(JSON.stringify).join(" ")) - // log.error("node -v", process.version) - // log.error("npm -v", npm.version) - log.error("", os.type() + " " + os.release()) - log.error("argv", process.argv.map(JSON.stringify).join(" ")) - log.error("node", process.version) - log.error("npm ", "v" + npm.version) - - ; [ "file" - , "path" - , "code" - , "errno" - , "syscall" - ].forEach(function (k) { - var v = er[k] - if (v) log.error(k, v) - }) + ;[ + 'type', + 'fstream_path', + 'fstream_unc_path', + 'fstream_type', + 'fstream_class', + 'fstream_finish_call', + 'fstream_linkpath', + 'stack', + 'fstream_stack', + 'statusCode', + 'pkgid' + ].forEach(function (k) { + var v = er[k] + if (!v) return + if (k === 'fstream_stack') v = v.join('\n') + log.verbose(k, v) + }) + + log.verbose('cwd', process.cwd()) + + var os = require('os') + // log.error('System', os.type() + ' ' + os.release()) + // log.error('command', process.argv.map(JSON.stringify).join(' ')) + // log.error('node -v', process.version) + // log.error('npm -v', npm.version) + log.error('', os.type() + ' ' + os.release()) + log.error('argv', process.argv.map(JSON.stringify).join(' ')) + log.error('node', process.version) + log.error('npm ', 'v' + npm.version) + + ;[ + 'file', + 'path', + 'code', + 'errno', + 'syscall' + ].forEach(function (k) { + var v = er[k] + if (v) log.error(k, v) + }) // just a line break - if (log.levels[log.level] <= log.levels.error) console.error("") + if (log.levels[log.level] <= log.levels.error) console.error('') switch (er.code) { - case "ECONNREFUSED": - log.error("", er) - log.error("", ["\nIf you are behind a proxy, please make sure that the" - ,"'proxy' config is set properly. See: 'npm help config'" - ].join("\n")) + case 'ECONNREFUSED': + log.error('', er) + log.error( + '', + [ + '\nIf you are behind a proxy, please make sure that the', + "'proxy' config is set properly. See: 'npm help config'" + ].join('\n') + ) break - case "EACCES": - case "EPERM": - log.error("", er) - log.error("", ["\nPlease try running this command again as root/Administrator." - ].join("\n")) + case 'EACCES': + case 'EPERM': + log.error('', er) + log.error('', ['\nPlease try running this command again as root/Administrator.' + ].join('\n')) break - case "ELIFECYCLE": - log.error("", er.message) - log.error("", ["","Failed at the "+er.pkgid+" "+er.stage+" script '"+er.script+"'." - ,"This is most likely a problem with the "+er.pkgname+" package," - ,"not with npm itself." - ,"Tell the author that this fails on your system:" - ," "+er.script - ,"You can get their info via:" - ," npm owner ls "+er.pkgname - ,"There is likely additional logging output above." - ].join("\n")) + case 'ELIFECYCLE': + log.error('', er.message) + log.error( + '', + [ + '', + 'Failed at the ' + er.pkgid + ' ' + er.stage + " script '" + er.script + "'.", + 'This is most likely a problem with the ' + er.pkgname + ' package,', + 'not with npm itself.', + 'Tell the author that this fails on your system:', + ' ' + er.script, + 'You can get their info via:', + ' npm owner ls ' + er.pkgname, + 'There is likely additional logging output above.' + ].join('\n') + ) break - case "ENOGIT": - log.error("", er.message) - log.error("", ["","Failed using git." - ,"This is most likely not a problem with npm itself." - ,"Please check if you have git installed and in your PATH." - ].join("\n")) + case 'ENOGIT': + log.error('', er.message) + log.error( + '', + [ + '', + 'Failed using git.', + 'This is most likely not a problem with npm itself.', + 'Please check if you have git installed and in your PATH.' + ].join('\n') + ) break - case "EJSONPARSE": - log.error("", er.message) - log.error("", "File: "+er.file) - log.error("", ["Failed to parse package.json data." - ,"package.json must be actual JSON, not just JavaScript." - ,"","This is not a bug in npm." - ,"Tell the package author to fix their package.json file." - ].join("\n"), "JSON.parse") + case 'EJSONPARSE': + log.error('', er.message) + log.error('', 'File: ' + er.file) + log.error( + '', + [ + 'Failed to parse package.json data.', + 'package.json must be actual JSON, not just JavaScript.', + '', + 'This is not a bug in npm.', + 'Tell the package author to fix their package.json file.' + ].join('\n'), + 'JSON.parse' + ) break // TODO(isaacs) // Add a special case here for E401 and E403 explaining auth issues? - case "E404": + case 'E404': var msg = [er.message] - if (er.pkgid && er.pkgid !== "-") { - msg.push("", "'" + er.pkgid + "' is not in the npm registry.") + if (er.pkgid && er.pkgid !== '-') { + msg.push('', "'" + er.pkgid + "' is not in the npm registry.") var valResult = nameValidator(er.pkgid) if (valResult.validForNewPackages) { - msg.push("You should bug the author to publish it (or use the name yourself!)") + msg.push('You should bug the author to publish it (or use the name yourself!)') } else { - msg.push("Your package name is not valid, because", "") + msg.push('Your package name is not valid, because', '') var errorsArray = (valResult.errors || []).concat(valResult.warnings || []) - errorsArray.forEach(function(item, idx) { - msg.push(" " + (idx + 1) + ". " + item) + errorsArray.forEach(function (item, idx) { + msg.push(' ' + (idx + 1) + '. ' + item) }) } if (er.parent) { - msg.push("It was specified as a dependency of '"+er.parent+"'") + msg.push("It was specified as a dependency of '" + er.parent + "'") } - msg.push("\nNote that you can also install from a" - ,"tarball, folder, http url, or git url.") + msg.push( + '\nNote that you can also install from a', + 'tarball, folder, http url, or git url.' + ) } // There's no need to have 404 in the message as well. - msg[0] = msg[0].replace(/^404\s+/, "") - log.error("404", msg.join("\n")) + msg[0] = msg[0].replace(/^404\s+/, '') + log.error('404', msg.join('\n')) break - case "EPUBLISHCONFLICT": - log.error("publish fail", ["Cannot publish over existing version." - ,"Update the 'version' field in package.json and try again." - ,"" - ,"To automatically increment version numbers, see:" - ," npm help version" - ].join("\n")) + case 'EPUBLISHCONFLICT': + log.error( + 'publish fail', + [ + 'Cannot publish over existing version.', + "Update the 'version' field in package.json and try again.", + '', + 'To automatically increment version numbers, see:', + ' npm help version' + ].join('\n') + ) break - case "EISGIT": - log.error("git", [er.message - ," "+er.path - ,"Refusing to remove it. Update manually," - ,"or move it out of the way first." - ].join("\n")) + case 'EISGIT': + log.error( + 'git', + [ + er.message, + ' ' + er.path, + 'Refusing to remove it. Update manually,', + 'or move it out of the way first.' + ].join('\n') + ) break - case "ECYCLE": - log.error("cycle", [er.message - ,"While installing: "+er.pkgid - ,"Found a pathological dependency case that npm cannot solve." - ,"Please report this to the package author." - ].join("\n")) + case 'ECYCLE': + log.error( + 'cycle', + [ + er.message, + 'While installing: ' + er.pkgid, + 'Found a pathological dependency case that npm cannot solve.', + 'Please report this to the package author.' + ].join('\n') + ) break - case "EBADPLATFORM": - log.error("notsup", [er.message - ,"Not compatible with your operating system or architecture: "+er.pkgid - ,"Valid OS: "+er.os.join(",") - ,"Valid Arch: "+er.cpu.join(",") - ,"Actual OS: "+process.platform - ,"Actual Arch: "+process.arch - ].join("\n")) + case 'EBADPLATFORM': + log.error( + 'notsup', + [ + er.message, + 'Not compatible with your operating system or architecture: ' + er.pkgid, + 'Valid OS: ' + er.os.join(','), + 'Valid Arch: ' + er.cpu.join(','), + 'Actual OS: ' + process.platform, + 'Actual Arch: ' + process.arch + ].join('\n') + ) break - case "EEXIST": - log.error([er.message - ,"File exists: "+er.path - ,"Move it away, and try again."].join("\n")) + case 'EEXIST': + log.error( + [ + er.message, + 'File exists: ' + er.path, + 'Move it away, and try again.' + ].join('\n') + ) break - case "ENEEDAUTH": - log.error("need auth", [er.message - ,"You need to authorize this machine using `npm adduser`" - ].join("\n")) + case 'ENEEDAUTH': + log.error( + 'need auth', + [ + er.message, + 'You need to authorize this machine using `npm adduser`' + ].join('\n') + ) break - case "EPEERINVALID": + case 'EPEERINVALID': var peerErrors = Object.keys(er.peersDepending).map(function (peer) { - return "Peer " + peer + " wants " + er.packageName + "@" - + er.peersDepending[peer] + return 'Peer ' + peer + ' wants ' + + er.packageName + '@' + er.peersDepending[peer] }) - log.error("peerinvalid", [er.message].concat(peerErrors).join("\n")) + log.error('peerinvalid', [er.message].concat(peerErrors).join('\n')) break - case "ECONNRESET": - case "ENOTFOUND": - case "ETIMEDOUT": - case "EAI_FAIL": - log.error("network", [er.message - ,"This is most likely not a problem with npm itself" - ,"and is related to network connectivity." - ,"In most cases you are behind a proxy or have bad network settings." - ,"\nIf you are behind a proxy, please make sure that the" - ,"'proxy' config is set properly. See: 'npm help config'" - ].join("\n")) + case 'ECONNRESET': + case 'ENOTFOUND': + case 'ETIMEDOUT': + case 'EAI_FAIL': + log.error( + 'network', + [ + er.message, + 'This is most likely not a problem with npm itself', + 'and is related to network connectivity.', + 'In most cases you are behind a proxy or have bad network settings.', + '\nIf you are behind a proxy, please make sure that the', + "'proxy' config is set properly. See: 'npm help config'" + ].join('\n') + ) break - case "ENOPACKAGEJSON": - log.error("package.json", [er.message - ,"This is most likely not a problem with npm itself." - ,"npm can't find a package.json file in your current directory." - ].join("\n")) + case 'ENOPACKAGEJSON': + log.error( + 'package.json', + [ + er.message, + 'This is most likely not a problem with npm itself.', + "npm can't find a package.json file in your current directory." + ].join('\n') + ) break - case "ETARGET": - var msg = [er.message - ,"This is most likely not a problem with npm itself." - ,"In most cases you or one of your dependencies are requesting" - ,"a package version that doesn't exist." - ] - if (er.parent) { - msg.push("\nIt was specified as a dependency of '"+er.parent+"'\n") - } - log.error("notarget", msg.join("\n")) + case 'ETARGET': + msg = [ + er.message, + 'This is most likely not a problem with npm itself.', + 'In most cases you or one of your dependencies are requesting', + "a package version that doesn't exist." + ] + if (er.parent) { + msg.push("\nIt was specified as a dependency of '" + er.parent + "'\n") + } + log.error('notarget', msg.join('\n')) break - case "ENOTSUP": + case 'ENOTSUP': if (er.required) { - log.error("notsup", [er.message - ,"Not compatible with your version of node/npm: "+er.pkgid - ,"Required: "+JSON.stringify(er.required) - ,"Actual: " - +JSON.stringify({npm:npm.version - ,node:npm.config.get("node-version")}) - ].join("\n")) + log.error( + 'notsup', + [ + er.message, + 'Not compatible with your version of node/npm: ' + er.pkgid, + 'Required: ' + JSON.stringify(er.required), + 'Actual: ' + JSON.stringify({ + npm: npm.version, + node: npm.config.get('node-version') + }) + ].join('\n') + ) break } // else passthrough - - case "ENOSPC": - log.error("nospc", [er.message - ,"This is most likely not a problem with npm itself" - ,"and is related to insufficient space on your system." - ].join("\n")) + /*eslint no-fallthrough:0*/ + + case 'ENOSPC': + log.error( + 'nospc', + [ + er.message, + 'This is most likely not a problem with npm itself', + 'and is related to insufficient space on your system.' + ].join('\n') + ) break - case "EROFS": - log.error("rofs", [er.message - ,"This is most likely not a problem with npm itself" - ,"and is related to the file system being read-only." - ,"\nOften virtualized file systems, or other file systems" - ,"that don't support symlinks, give this error." - ].join("\n")) + case 'EROFS': + log.error( + 'rofs', + [ + er.message, + 'This is most likely not a problem with npm itself', + 'and is related to the file system being read-only.', + '\nOften virtualized file systems, or other file systems', + "that don't support symlinks, give this error." + ].join('\n') + ) break - case "ENOENT": - log.error("enoent", [er.message - ,"This is most likely not a problem with npm itself" - ,"and is related to npm not being able to find a file." - ,er.file?"\nCheck if the file '"+er.file+"' is present.":"" - ].join("\n")) + case 'ENOENT': + log.error( + 'enoent', + [ + er.message, + 'This is most likely not a problem with npm itself', + 'and is related to npm not being able to find a file.', + er.file ? "\nCheck if the file '" + er.file + "' is present." : '' + ].join('\n') + ) break - case "EMISSINGARG": - case "EUNKNOWNTYPE": - case "EINVALIDTYPE": - case "ETOOMANYARGS": - log.error("typeerror", [er.stack - ,"This is an error with npm itself. Please report this error at:" - ," <http://github.com/npm/npm/issues>" - ].join("\n")) + case 'EMISSINGARG': + case 'EUNKNOWNTYPE': + case 'EINVALIDTYPE': + case 'ETOOMANYARGS': + log.error( + 'typeerror', + [ + er.stack, + 'This is an error with npm itself. Please report this error at:', + ' <http://github.com/npm/npm/issues>' + ].join('\n') + ) break default: - log.error("", er.message || er) - log.error("", ["", "If you need help, you may report this error at:" - ," <https://github.com/npm/npm/issues>" - ].join("\n")) + log.error('', er.message || er) + log.error( + '', + [ + '', + 'If you need help, you may report this error at:', + ' <https://github.com/npm/npm/issues>' + ].join('\n') + ) break } - exit(typeof er.errno === "number" ? er.errno : 1) + exit(typeof er.errno === 'number' ? er.errno : 1) } var writingLogFile = false @@ -392,22 +479,22 @@ function writeLogFile (cb) { writingLogFile = true wroteLogFile = true - var fstr = writeStream("npm-debug.log") - , os = require("os") - , out = "" + var fstr = writeStream('npm-debug.log') + var os = require('os') + var out = '' log.record.forEach(function (m) { var pref = [m.id, m.level] if (m.prefix) pref.push(m.prefix) - pref = pref.join(" ") + pref = pref.join(' ') m.message.trim().split(/\r?\n/).map(function (line) { - return (pref + " " + line).trim() + return (pref + ' ' + line).trim() }).forEach(function (line) { out += line + os.EOL }) }) fstr.end(out) - fstr.on("close", cb) + fstr.on('close', cb) } diff --git a/lib/utils/git.js b/lib/utils/git.js index 9c80ea553..2d9da1086 100644 --- a/lib/utils/git.js +++ b/lib/utils/git.js @@ -1,20 +1,19 @@ - // handle some git configuration for windows exports.spawn = spawnGit exports.chainableExec = chainableExec exports.whichAndExec = whichAndExec -var exec = require("child_process").execFile - , spawn = require("./spawn") - , npm = require("../npm.js") - , which = require("which") - , git = npm.config.get("git") - , assert = require("assert") - , log = require("npmlog") +var exec = require('child_process').execFile +var spawn = require('./spawn') +var npm = require('../npm.js') +var which = require('which') +var git = npm.config.get('git') +var assert = require('assert') +var log = require('npmlog') function prefixGitArgs () { - return process.platform === "win32" ? ["-c", "core.longpaths=true"] : [] + return process.platform === 'win32' ? ['-c', 'core.longpaths=true'] : [] } function execGit (args, options, cb) { @@ -24,7 +23,7 @@ function execGit (args, options, cb) { } function spawnGit (args, options) { - log.info("git", args) + log.info('git', args) return spawn(git, prefixGitArgs().concat(args || []), options) } @@ -38,11 +37,11 @@ function whichGit (cb) { } function whichAndExec (args, options, cb) { - assert.equal(typeof cb, "function", "no callback provided") + assert.equal(typeof cb, 'function', 'no callback provided') // check for git whichGit(function (err) { if (err) { - err.code = "ENOGIT" + err.code = 'ENOGIT' return cb(err) } diff --git a/lib/utils/lifecycle.js b/lib/utils/lifecycle.js index 8f9233488..7d5699fb5 100644 --- a/lib/utils/lifecycle.js +++ b/lib/utils/lifecycle.js @@ -2,20 +2,20 @@ exports = module.exports = lifecycle exports.cmd = cmd exports.makeEnv = makeEnv -var log = require("npmlog") -var spawn = require("./spawn") -var npm = require("../npm.js") -var path = require("path") -var fs = require("graceful-fs") -var chain = require("slide").chain -var Stream = require("stream").Stream -var PATH = "PATH" -var uidNumber = require("uid-number") -var umask = require("./umask") - -// windows calls it's path "Path" usually, but this is not guaranteed. -if (process.platform === "win32") { - PATH = "Path" +var log = require('npmlog') +var spawn = require('./spawn') +var npm = require('../npm.js') +var path = require('path') +var fs = require('graceful-fs') +var chain = require('slide').chain +var Stream = require('stream').Stream +var PATH = 'PATH' +var uidNumber = require('uid-number') +var umask = require('./umask') + +// windows calls it's path 'Path' usually, but this is not guaranteed. +if (process.platform === 'win32') { + PATH = 'Path' Object.keys(process.env).forEach(function (e) { if (e.match(/^PATH$/i)) { PATH = e @@ -24,12 +24,21 @@ if (process.platform === "win32") { } function lifecycle (pkg, stage, wd, unsafe, failOk, cb) { - if (typeof cb !== "function") cb = failOk, failOk = false - if (typeof cb !== "function") cb = unsafe, unsafe = false - if (typeof cb !== "function") cb = wd, wd = null + if (typeof cb !== 'function') { + cb = failOk + failOk = false + } + if (typeof cb !== 'function') { + cb = unsafe + unsafe = false + } + if (typeof cb !== 'function') { + cb = wd + wd = null + } while (pkg && pkg._data) pkg = pkg._data - if (!pkg) return cb(new Error("Invalid package data")) + if (!pkg) return cb(new Error('Invalid package data')) log.info(stage, pkg._id) if (!pkg.scripts || npm.config.get('ignore-scripts')) pkg.scripts = {} @@ -37,12 +46,15 @@ function lifecycle (pkg, stage, wd, unsafe, failOk, cb) { validWd(wd || path.resolve(npm.dir, pkg.name), function (er, wd) { if (er) return cb(er) - unsafe = unsafe || npm.config.get("unsafe-perm") + unsafe = unsafe || npm.config.get('unsafe-perm') - if ((wd.indexOf(npm.dir) !== 0 || path.basename(wd) !== pkg.name) - && !unsafe && pkg.scripts[stage]) { - log.warn( "cannot run in wd", "%s %s (wd=%s)" - , pkg._id, pkg.scripts[stage], wd) + if ((wd.indexOf(npm.dir) !== 0 || path.basename(wd) !== pkg.name) && + !unsafe && + pkg.scripts[stage]) { + log.warn( + 'cannot run in wd', + '%s %s (wd=%s)', pkg._id, pkg.scripts[stage], wd + ) return cb() } @@ -52,38 +64,31 @@ function lifecycle (pkg, stage, wd, unsafe, failOk, cb) { env.npm_node_execpath = env.NODE = env.NODE || process.execPath env.npm_execpath = require.main.filename - // "nobody" typically doesn't have permission to write to /tmp + // 'nobody' typically doesn't have permission to write to /tmp // even if it's never used, sh freaks out. - if (!npm.config.get("unsafe-perm")) env.TMPDIR = wd + if (!npm.config.get('unsafe-perm')) env.TMPDIR = wd lifecycle_(pkg, stage, wd, env, unsafe, failOk, cb) }) } -function checkForLink (pkg, cb) { - var f = path.join(npm.dir, pkg.name) - fs.lstat(f, function (er, s) { - cb(null, !(er || !s.isSymbolicLink())) - }) -} - function lifecycle_ (pkg, stage, wd, env, unsafe, failOk, cb) { var pathArr = [] - , p = wd.split("node_modules") - , acc = path.resolve(p.shift()) + var p = wd.split('node_modules') + var acc = path.resolve(p.shift()) p.forEach(function (pp) { - pathArr.unshift(path.join(acc, "node_modules", ".bin")) - acc = path.join(acc, "node_modules", pp) + pathArr.unshift(path.join(acc, 'node_modules', '.bin')) + acc = path.join(acc, 'node_modules', pp) }) - pathArr.unshift(path.join(acc, "node_modules", ".bin")) + pathArr.unshift(path.join(acc, 'node_modules', '.bin')) // we also unshift the bundled node-gyp-bin folder so that // the bundled one will be used for installing things. - pathArr.unshift(path.join(__dirname, "..", "..", "bin", "node-gyp-bin")) + pathArr.unshift(path.join(__dirname, '..', '..', 'bin', 'node-gyp-bin')) if (env[PATH]) pathArr.push(env[PATH]) - env[PATH] = pathArr.join(process.platform === "win32" ? ";" : ":") + env[PATH] = pathArr.join(process.platform === 'win32' ? ';' : ':') var packageLifecycle = pkg.scripts && pkg.scripts.hasOwnProperty(stage) @@ -94,21 +99,24 @@ function lifecycle_ (pkg, stage, wd, env, unsafe, failOk, cb) { function done (er) { if (er) { - if (npm.config.get("force")) { - log.info("forced, continuing", er) + if (npm.config.get('force')) { + log.info('forced, continuing', er) er = null } else if (failOk) { - log.warn("continuing anyway", er.message) + log.warn('continuing anyway', er.message) er = null } } cb(er) } - chain - ( [ packageLifecycle && [runPackageLifecycle, pkg, env, wd, unsafe] - , [runHookLifecycle, pkg, env, wd, unsafe] ] - , done ) + chain( + [ + packageLifecycle && [runPackageLifecycle, pkg, env, wd, unsafe], + [runHookLifecycle, pkg, env, wd, unsafe] + ], + done + ) } function validWd (d, cb) { @@ -116,7 +124,7 @@ function validWd (d, cb) { if (er || !st.isDirectory()) { var p = path.dirname(d) if (p === d) { - return cb(new Error("Could not find suitable wd")) + return cb(new Error('Could not find suitable wd')) } return validWd(p, cb) } @@ -127,17 +135,16 @@ function validWd (d, cb) { function runPackageLifecycle (pkg, env, wd, unsafe, cb) { // run package lifecycle scripts in the package root, or the nearest parent. var stage = env.npm_lifecycle_event - , cmd = env.npm_lifecycle_script + var cmd = env.npm_lifecycle_script - var note = "\n> " + pkg._id + " " + stage + " " + wd - + "\n> " + cmd + "\n" + var note = '\n> ' + pkg._id + ' ' + stage + ' ' + wd + + '\n> ' + cmd + '\n' runCmd(note, cmd, pkg, env, stage, wd, unsafe, cb) } - var running = false var queue = [] -function dequeue() { +function dequeue () { running = false if (queue.length) { var r = queue.shift() @@ -153,17 +160,17 @@ function runCmd (note, cmd, pkg, env, stage, wd, unsafe, cb) { running = true log.pause() - var user = unsafe ? null : npm.config.get("user") - , group = unsafe ? null : npm.config.get("group") + var user = unsafe ? null : npm.config.get('user') + var group = unsafe ? null : npm.config.get('group') if (log.level !== 'silent') { log.clearProgress() console.log(note) log.showProgress() } - log.verbose("unsafe-perm in lifecycle", unsafe) + log.verbose('unsafe-perm in lifecycle', unsafe) - if (process.platform === "win32") { + if (process.platform === 'win32') { unsafe = true } @@ -184,34 +191,35 @@ function runCmd_ (cmd, pkg, env, wd, stage, unsafe, uid, gid, cb_) { process.nextTick(dequeue) } - var conf = { cwd: wd - , env: env - , stdio: [ 0, 1, 2 ] - } + var conf = { + cwd: wd, + env: env, + stdio: [ 0, 1, 2 ] + } if (!unsafe) { conf.uid = uid ^ 0 conf.gid = gid ^ 0 } - var sh = "sh" - var shFlag = "-c" + var sh = 'sh' + var shFlag = '-c' - if (process.platform === "win32") { - sh = process.env.comspec || "cmd" - shFlag = "/c" + if (process.platform === 'win32') { + sh = process.env.comspec || 'cmd' + shFlag = '/c' conf.windowsVerbatimArguments = true } log.disableProgress() var proc = spawn(sh, [shFlag, cmd], conf) - proc.on("error", procError) - proc.on("close", function (code, signal) { + proc.on('error', procError) + proc.on('close', function (code, signal) { if (signal) { - process.kill(process.pid, signal); + process.kill(process.pid, signal) } else if (code) { - var er = new Error("Exit status " + code) + var er = new Error('Exit status ' + code) } procError(er) }) @@ -219,12 +227,11 @@ function runCmd_ (cmd, pkg, env, wd, stage, unsafe, uid, gid, cb_) { function procError (er) { log.enableProgress() if (er && !npm.ROLLBACK) { - log.info(pkg._id, "Failed to exec "+stage+" script") - er.message = pkg._id + " " - + stage + ": `" + cmd +"`\n" - + er.message - if (er.code !== "EPERM") { - er.code = "ELIFECYCLE" + log.info(pkg._id, 'Failed to exec ' + stage + ' script') + er.message = pkg._id + ' ' + stage + ': `' + cmd + '`\n' + + er.message + if (er.code !== 'EPERM') { + er.code = 'ELIFECYCLE' } er.pkgid = pkg._id er.stage = stage @@ -232,33 +239,30 @@ function runCmd_ (cmd, pkg, env, wd, stage, unsafe, uid, gid, cb_) { er.pkgname = pkg.name return cb(er) } else if (er) { - log.error(pkg._id+"."+stage, er) - log.error(pkg._id+"."+stage, "continuing anyway") + log.error(pkg._id + '.' + stage, er) + log.error(pkg._id + '.' + stage, 'continuing anyway') return cb() } cb(er) } } - function runHookLifecycle (pkg, env, wd, unsafe, cb) { // check for a hook script, run if present. var stage = env.npm_lifecycle_event - , hook = path.join(npm.dir, ".hooks", stage) - , user = unsafe ? null : npm.config.get("user") - , group = unsafe ? null : npm.config.get("group") - , cmd = hook + var hook = path.join(npm.dir, '.hooks', stage) + var cmd = hook fs.stat(hook, function (er) { if (er) return cb() - var note = "\n> " + pkg._id + " " + stage + " " + wd - + "\n> " + cmd + var note = '\n> ' + pkg._id + ' ' + stage + ' ' + wd + + '\n> ' + cmd runCmd(note, hook, pkg, env, stage, wd, unsafe, cb) }) } function makeEnv (data, prefix, env) { - prefix = prefix || "npm_package_" + prefix = prefix || 'npm_package_' if (!env) { env = {} for (var i in process.env) if (!i.match(/^npm_/)) { @@ -266,83 +270,89 @@ function makeEnv (data, prefix, env) { } // npat asks for tap output - if (npm.config.get("npat")) env.TAP = 1 + if (npm.config.get('npat')) env.TAP = 1 // express and others respect the NODE_ENV value. - if (npm.config.get("production")) env.NODE_ENV = "production" + if (npm.config.get('production')) env.NODE_ENV = 'production' - } else if (!data.hasOwnProperty("_lifecycleEnv")) { - Object.defineProperty(data, "_lifecycleEnv", - { value : env - , enumerable : false - }) + } else if (!data.hasOwnProperty('_lifecycleEnv')) { + Object.defineProperty(data, '_lifecycleEnv', + { + value: env, + enumerable: false + } + ) } - for (var i in data) if (i.charAt(0) !== "_") { - var envKey = (prefix+i).replace(/[^a-zA-Z0-9_]/g, '_') - if (i === "readme") { + for (i in data) if (i.charAt(0) !== '_') { + var envKey = (prefix + i).replace(/[^a-zA-Z0-9_]/g, '_') + if (i === 'readme') { continue } - if (data[i] && typeof(data[i]) === "object") { + if (data[i] && typeof data[i] === 'object') { try { // quick and dirty detection for cyclical structures JSON.stringify(data[i]) - makeEnv(data[i], envKey+"_", env) + makeEnv(data[i], envKey + '_', env) } catch (ex) { // usually these are package objects. // just get the path and basic details. var d = data[i] - makeEnv( { name: d.name, version: d.version, path:d.path } - , envKey+"_", env) + makeEnv( + { name: d.name, version: d.version, path: d.path }, + envKey + '_', + env + ) } } else { env[envKey] = String(data[i]) - env[envKey] = -1 !== env[envKey].indexOf("\n") - ? JSON.stringify(env[envKey]) - : env[envKey] + env[envKey] = env[envKey].indexOf('\n') !== -1 ? + JSON.stringify(env[envKey]) : + env[envKey] } } - if (prefix !== "npm_package_") return env + if (prefix !== 'npm_package_') return env - prefix = "npm_config_" + prefix = 'npm_config_' var pkgConfig = {} - , keys = npm.config.keys - , pkgVerConfig = {} - , namePref = data.name + ":" - , verPref = data.name + "@" + data.version + ":" + var keys = npm.config.keys + var pkgVerConfig = {} + var namePref = data.name + ':' + var verPref = data.name + '@' + data.version + ':' keys.forEach(function (i) { - if (i.charAt(0) === "_" && i.indexOf("_"+namePref) !== 0) { + if (i.charAt(0) === '_' && i.indexOf('_' + namePref) !== 0) { return } var value = npm.config.get(i) if (value instanceof Stream || Array.isArray(value)) return if (i.match(/umask/)) value = umask.toString(value) - if (!value) value = "" - else if (typeof value === "number") value = "" + value - else if (typeof value !== "string") value = JSON.stringify(value) + if (!value) value = '' + else if (typeof value === 'number') value = '' + value + else if (typeof value !== 'string') value = JSON.stringify(value) - value = -1 !== value.indexOf("\n") + value = value.indexOf('\n') !== -1 ? JSON.stringify(value) : value - i = i.replace(/^_+/, "") + i = i.replace(/^_+/, '') + var k if (i.indexOf(namePref) === 0) { - var k = i.substr(namePref.length).replace(/[^a-zA-Z0-9_]/g, "_") - pkgConfig[ k ] = value + k = i.substr(namePref.length).replace(/[^a-zA-Z0-9_]/g, '_') + pkgConfig[k] = value } else if (i.indexOf(verPref) === 0) { - var k = i.substr(verPref.length).replace(/[^a-zA-Z0-9_]/g, "_") - pkgVerConfig[ k ] = value + k = i.substr(verPref.length).replace(/[^a-zA-Z0-9_]/g, '_') + pkgVerConfig[k] = value } - var envKey = (prefix+i).replace(/[^a-zA-Z0-9_]/g, "_") + var envKey = (prefix + i).replace(/[^a-zA-Z0-9_]/g, '_') env[envKey] = value }) - prefix = "npm_package_config_" + prefix = 'npm_package_config_' ;[pkgConfig, pkgVerConfig].forEach(function (conf) { for (var i in conf) { - var envKey = (prefix+i) + var envKey = (prefix + i) env[envKey] = conf[i] } }) @@ -352,10 +362,10 @@ function makeEnv (data, prefix, env) { function cmd (stage) { function CMD (args, cb) { - npm.commands["run-script"]([stage].concat(args), cb) + npm.commands['run-script']([stage].concat(args), cb) } - CMD.usage = "npm "+stage+" [-- <args>]" - var installedShallow = require("./completion/installed-shallow.js") + CMD.usage = 'npm ' + stage + ' [-- <args>]' + var installedShallow = require('./completion/installed-shallow.js') CMD.completion = function (opts, cb) { installedShallow(opts, function (d) { return d.scripts && d.scripts[stage] diff --git a/lib/utils/link.js b/lib/utils/link.js index 1376f292f..1091f4683 100644 --- a/lib/utils/link.js +++ b/lib/utils/link.js @@ -1,13 +1,12 @@ - module.exports = link link.ifExists = linkIfExists -var fs = require("graceful-fs") - , chain = require("slide").chain - , mkdir = require("mkdirp") - , rm = require("./gently-rm.js") - , path = require("path") - , npm = require("../npm.js") +var fs = require('graceful-fs') +var chain = require('slide').chain +var mkdir = require('mkdirp') +var rm = require('./gently-rm.js') +var path = require('path') +var npm = require('../npm.js') function linkIfExists (from, to, gently, cb) { fs.stat(from, function (er) { @@ -27,13 +26,19 @@ function linkIfExists (from, to, gently, cb) { } function link (from, to, gently, abs, cb) { - if (typeof cb !== "function") cb = abs, abs = false - if (typeof cb !== "function") cb = gently, gently = null - if (npm.config.get("force")) gently = false + if (typeof cb !== 'function') { + cb = abs + abs = false + } + if (typeof cb !== 'function') { + cb = gently + gently = null + } + if (npm.config.get('force')) gently = false to = path.resolve(to) var target = from = path.resolve(from) - if (!abs && process.platform !== "win32") { + if (!abs && process.platform !== 'win32') { // junctions on windows must be absolute target = path.relative(path.dirname(to), from) // if there is no folder in common, then it will be much @@ -41,10 +46,13 @@ function link (from, to, gently, abs, cb) { if (target.length >= from.length) target = from } - chain - ( [ [fs, "stat", from] - , [rm, to, gently] - , [mkdir, path.dirname(to)] - , [fs, "symlink", target, to, "junction"] ] - , cb) + chain( + [ + [fs, 'stat', from], + [rm, to, gently], + [mkdir, path.dirname(to)], + [fs, 'symlink', target, to, 'junction'] + ], + cb + ) } diff --git a/lib/utils/locker.js b/lib/utils/locker.js index 4a8f37271..9cd8b2c4f 100644 --- a/lib/utils/locker.js +++ b/lib/utils/locker.js @@ -1,38 +1,39 @@ -var crypto = require("crypto") -var resolve = require("path").resolve +var crypto = require('crypto') +var resolve = require('path').resolve -var lockfile = require("lockfile") -var log = require("npmlog") -var mkdirp = require("mkdirp") +var lockfile = require('lockfile') +var log = require('npmlog') -var npm = require("../npm.js") +var npm = require('../npm.js') var correctMkdir = require('../utils/correct-mkdir.js') var installLocks = {} function lockFileName (base, name) { - var c = name.replace(/[^a-zA-Z0-9]+/g, "-").replace(/^-+|-+$/g, "") - , p = resolve(base, name) - , h = crypto.createHash("sha1").update(p).digest("hex") - , l = resolve(npm.cache, "_locks") + var c = name.replace(/[^a-zA-Z0-9]+/g, '-').replace(/^-+|-+$/g, '') + var p = resolve(base, name) + var h = crypto.createHash('sha1').update(p).digest('hex') + var l = resolve(npm.cache, '_locks') - return resolve(l, c.substr(0, 24)+"-"+h.substr(0, 16)+".lock") + return resolve(l, c.substr(0, 24) + '-' + h.substr(0, 16) + '.lock') } function lock (base, name, cb) { - var lockDir = resolve(npm.cache, "_locks") + var lockDir = resolve(npm.cache, '_locks') correctMkdir(lockDir, function (er) { if (er) return cb(er) - var opts = { stale: npm.config.get("cache-lock-stale") - , retries: npm.config.get("cache-lock-retries") - , wait: npm.config.get("cache-lock-wait") } + var opts = { + stale: npm.config.get('cache-lock-stale'), + retries: npm.config.get('cache-lock-retries'), + wait: npm.config.get('cache-lock-wait') + } var lf = lockFileName(base, name) lockfile.lock(lf, opts, function (er) { - if (er) log.warn("locking", lf, "failed", er) + if (er) log.warn('locking', lf, 'failed', er) if (!er) { - log.verbose("lock", "using", lf, "for", resolve(base, name)) + log.verbose('lock', 'using', lf, 'for', resolve(base, name)) installLocks[lf] = true } @@ -43,33 +44,30 @@ function lock (base, name, cb) { function unlock (base, name, cb) { var lf = lockFileName(base, name) - , locked = installLocks[lf] + var locked = installLocks[lf] if (locked === false) { return process.nextTick(cb) - } - else if (locked === true) { + } else if (locked === true) { lockfile.unlock(lf, function (er) { if (er) { - log.warn("unlocking", lf, "failed", er) - } - else { + log.warn('unlocking', lf, 'failed', er) + } else { installLocks[lf] = false - log.verbose("unlock", "done using", lf, "for", resolve(base, name)) + log.verbose('unlock', 'done using', lf, 'for', resolve(base, name)) } cb(er) }) - } - else { + } else { var notLocked = new Error( - "Attempt to unlock " + resolve(base, name) + ", which hasn't been locked" + 'Attempt to unlock ' + resolve(base, name) + ", which hasn't been locked" ) - notLocked.code = "ENOTLOCKED" + notLocked.code = 'ENOTLOCKED' throw notLocked } } module.exports = { - lock : lock, - unlock : unlock + lock: lock, + unlock: unlock } diff --git a/lib/utils/map-to-registry.js b/lib/utils/map-to-registry.js index bd68a26d4..34046d191 100644 --- a/lib/utils/map-to-registry.js +++ b/lib/utils/map-to-registry.js @@ -1,56 +1,56 @@ -var url = require("url") +var url = require('url') -var log = require("npmlog") - , npa = require("npm-package-arg") +var log = require('npmlog') +var npa = require('npm-package-arg') module.exports = mapToRegistry -function mapToRegistry(name, config, cb) { - log.silly("mapToRegistry", "name", name) +function mapToRegistry (name, config, cb) { + log.silly('mapToRegistry', 'name', name) var registry // the name itself takes precedence var data = npa(name) if (data.scope) { // the name is definitely scoped, so escape now - name = name.replace("/", "%2f") + name = name.replace('/', '%2f') - log.silly("mapToRegistry", "scope (from package name)", data.scope) + log.silly('mapToRegistry', 'scope (from package name)', data.scope) - registry = config.get(data.scope + ":registry") + registry = config.get(data.scope + ':registry') if (!registry) { - log.verbose("mapToRegistry", "no registry URL found in name for scope", data.scope) + log.verbose('mapToRegistry', 'no registry URL found in name for scope', data.scope) } } // ...then --scope=@scope or --scope=scope - var scope = config.get("scope") + var scope = config.get('scope') if (!registry && scope) { // I'm an enabler, sorry - if (scope.charAt(0) !== "@") scope = "@" + scope + if (scope.charAt(0) !== '@') scope = '@' + scope - log.silly("mapToRegistry", "scope (from config)", scope) + log.silly('mapToRegistry', 'scope (from config)', scope) - registry = config.get(scope + ":registry") + registry = config.get(scope + ':registry') if (!registry) { - log.verbose("mapToRegistry", "no registry URL found in config for scope", scope) + log.verbose('mapToRegistry', 'no registry URL found in config for scope', scope) } } // ...and finally use the default registry if (!registry) { - log.silly("mapToRegistry", "using default registry") - registry = config.get("registry") + log.silly('mapToRegistry', 'using default registry') + registry = config.get('registry') } - log.silly("mapToRegistry", "registry", registry) + log.silly('mapToRegistry', 'registry', registry) var auth = config.getCredentialsByURI(registry) // normalize registry URL so resolution doesn't drop a piece of registry URL - var normalized = registry.slice(-1) !== "/" ? registry+"/" : registry + var normalized = registry.slice(-1) !== '/' ? registry + '/' : registry var uri = url.resolve(normalized, name) - log.silly("mapToRegistry", "uri", uri) + log.silly('mapToRegistry', 'uri', uri) cb(null, uri, auth, normalized) } diff --git a/lib/utils/pulse-till-done.js b/lib/utils/pulse-till-done.js index 85fb288d1..fc6450e00 100644 --- a/lib/utils/pulse-till-done.js +++ b/lib/utils/pulse-till-done.js @@ -1,4 +1,4 @@ -"use strict" +'use strict' var validate = require('aproba') var log = require('npmlog') @@ -7,13 +7,13 @@ var pulse module.exports = function (prefix, cb) { validate('SF', [prefix, cb]) - if (!pulsers ++) { + if (!pulsers++) { pulse = setInterval(function () { - log.gauge.pulse("network") + log.gauge.pulse('network') }, 250) } return function () { - if (!-- pulsers) { + if (!--pulsers) { clearInterval(pulse) } cb.apply(null, arguments) diff --git a/lib/utils/read-local-package.js b/lib/utils/read-local-package.js index ca6d61321..27ca7b4e3 100644 --- a/lib/utils/read-local-package.js +++ b/lib/utils/read-local-package.js @@ -1,12 +1,12 @@ exports = module.exports = readLocalPkg -var npm = require("../npm.js") - , readJson = require("read-package-json") +var npm = require('../npm.js') +var readJson = require('read-package-json') function readLocalPkg (cb) { - if (npm.config.get("global")) return cb() - var path = require("path") - readJson(path.resolve(npm.prefix, "package.json"), function (er, d) { + if (npm.config.get('global')) return cb() + var path = require('path') + readJson(path.resolve(npm.prefix, 'package.json'), function (er, d) { return cb(er, d && d.name) }) } diff --git a/lib/utils/spawn.js b/lib/utils/spawn.js index 74684521f..e389d83e0 100644 --- a/lib/utils/spawn.js +++ b/lib/utils/spawn.js @@ -1,16 +1,16 @@ module.exports = spawn -var _spawn = require("child_process").spawn -var EventEmitter = require("events").EventEmitter +var _spawn = require('child_process').spawn +var EventEmitter = require('events').EventEmitter function spawn (cmd, args, options) { var raw = _spawn(cmd, args, options) var cooked = new EventEmitter() - raw.on("error", function (er) { + raw.on('error', function (er) { er.file = cmd - cooked.emit("error", er) - }).on("close", function (code, signal) { + cooked.emit('error', er) + }).on('close', function (code, signal) { // Create ENOENT error because Node.js v0.8 will not emit // an `error` event if the command could not be found. if (code === 127) { @@ -21,7 +21,7 @@ function spawn (cmd, args, options) { er.file = cmd cooked.emit('error', er) } else { - cooked.emit("close", code, signal) + cooked.emit('close', code, signal) } }) diff --git a/lib/utils/umask.js b/lib/utils/umask.js index 6ccb4a119..2dde1befa 100644 --- a/lib/utils/umask.js +++ b/lib/utils/umask.js @@ -1,5 +1,5 @@ -var umask = require("umask") -var npmlog = require("npmlog") +var umask = require('umask') +var npmlog = require('npmlog') var _fromString = umask.fromString module.exports = umask @@ -8,7 +8,7 @@ module.exports = umask umask.fromString = function (val) { _fromString(val, function (err, result) { if (err) { - npmlog.warn("invalid umask", err.message) + npmlog.warn('invalid umask', err.message) } val = result }) diff --git a/lib/utils/warn-deprecated.js b/lib/utils/warn-deprecated.js index ec821b9bd..fe5c5ec82 100644 --- a/lib/utils/warn-deprecated.js +++ b/lib/utils/warn-deprecated.js @@ -1,6 +1,6 @@ module.exports = warnDeprecated -var log = require("npmlog") +var log = require('npmlog') var deprecations = {} @@ -11,8 +11,7 @@ function warnDeprecated (type) { deprecations[type] = {} messages.forEach(function (m) { log.warn(type, m) }) } - } - else { + } else { if (!deprecations[type]) deprecations[type] = {} if (!deprecations[type][instance]) { diff --git a/lib/version.js b/lib/version.js index 08b276c37..c93e3b850 100644 --- a/lib/version.js +++ b/lib/version.js @@ -2,36 +2,38 @@ module.exports = version -var semver = require("semver") - , path = require("path") - , fs = require("graceful-fs") - , writeFileAtomic = require("write-file-atomic") - , chain = require("slide").chain - , log = require("npmlog") - , npm = require("./npm.js") - , git = require("./utils/git.js") - , assert = require("assert") - , lifecycle = require("./utils/lifecycle.js") - -version.usage = "npm version [<newversion> | major | minor | patch | premajor | preminor | prepatch | prerelease]" - + "\n(run in package dir)\n" - + "'npm -v' or 'npm --version' to print npm version " - + "("+npm.version+")\n" - + "'npm view <pkg> version' to view a package's " - + "published version\n" - + "'npm ls' to inspect current package/dependency versions" +var semver = require('semver') +var path = require('path') +var fs = require('graceful-fs') +var writeFileAtomic = require('write-file-atomic') +var chain = require('slide').chain +var log = require('npmlog') +var npm = require('./npm.js') +var git = require('./utils/git.js') +var assert = require('assert') +var lifecycle = require('./utils/lifecycle.js') + +version.usage = 'npm version [<newversion> | major | minor | patch | premajor | preminor | prepatch | prerelease]' + + '\n(run in package dir)\n' + + "'npm -v' or 'npm --version' to print npm version " + + '(' + npm.version + ')\n' + + "'npm view <pkg> version' to view a package's " + + 'published version\n' + + "'npm ls' to inspect current package/dependency versions" function version (args, silent, cb_) { - if (typeof cb_ !== "function") cb_ = silent, silent = false + if (typeof cb_ !== 'function') { + cb_ = silent + silent = false + } if (args.length > 1) return cb_(version.usage) - var packagePath = path.join(npm.localPrefix, "package.json") + var packagePath = path.join(npm.localPrefix, 'package.json') fs.readFile(packagePath, function (er, data) { if (data) data = data.toString() try { data = JSON.parse(data) - } - catch (e) { + } catch (e) { er = e data = null } @@ -39,38 +41,38 @@ function version (args, silent, cb_) { if (!args.length) return dump(data, cb_) if (er) { - log.error("version", "No valid package.json found") + log.error('version', 'No valid package.json found') return cb_(er) } var newVersion = semver.valid(args[0]) if (!newVersion) newVersion = semver.inc(data.version, args[0]) if (!newVersion) return cb_(version.usage) - if (data.version === newVersion) return cb_(new Error("Version not changed")) + if (data.version === newVersion) return cb_(new Error('Version not changed')) data.version = newVersion var lifecycleData = Object.create(data) - lifecycleData._id = data.name + "@" + newVersion + lifecycleData._id = data.name + '@' + newVersion var where = npm.prefix chain([ - [lifecycle, lifecycleData, "preversion", where] - , [version_, data, silent] - , [lifecycle, lifecycleData, "version", where] - , [lifecycle, lifecycleData, "postversion", where] ] - , cb_) + [lifecycle, lifecycleData, 'preversion', where], + [version_, data, silent], + [lifecycle, lifecycleData, 'version', where], + [lifecycle, lifecycleData, 'postversion', where] ], + cb_) }) } function version_ (data, silent, cb_) { function cb (er) { - if (!er && !silent) console.log("v" + data.version) + if (!er && !silent) console.log('v' + data.version) cb_(er) } checkGit(function (er, hasGit) { if (er) return cb(new Error(er)) - write(data, "package.json", function (er) { + write(data, 'package.json', function (er) { if (er) return cb(new Error(er)) updateShrinkwrap(data.version, function (er, hasShrinkwrap) { @@ -82,22 +84,21 @@ function version_ (data, silent, cb_) { } function updateShrinkwrap (newVersion, cb) { - fs.readFile(path.join(npm.localPrefix, "npm-shrinkwrap.json"), function (er, data) { - if (er && er.code === "ENOENT") return cb(null, false) + fs.readFile(path.join(npm.localPrefix, 'npm-shrinkwrap.json'), function (er, data) { + if (er && er.code === 'ENOENT') return cb(null, false) try { data = data.toString() data = JSON.parse(data) - } - catch (er) { - log.error("version", "Bad npm-shrinkwrap.json data") + } catch (er) { + log.error('version', 'Bad npm-shrinkwrap.json data') return cb(er) } data.version = newVersion - write(data, "npm-shrinkwrap.json", function (er) { + write(data, 'npm-shrinkwrap.json', function (er) { if (er) { - log.error("version", "Bad npm-shrinkwrap.json data") + log.error('version', 'Bad npm-shrinkwrap.json data') return cb(er) } cb(null, true) @@ -114,43 +115,45 @@ function dump (data, cb) { v[k] = process.versions[k] }) - if (npm.config.get("json")) v = JSON.stringify(v, null, 2) + if (npm.config.get('json')) v = JSON.stringify(v, null, 2) console.log(v) cb() } function checkGit (cb) { - fs.stat(path.join(npm.localPrefix, ".git"), function (er, s) { - var doGit = !er && s.isDirectory() && npm.config.get("git-tag-version") + fs.stat(path.join(npm.localPrefix, '.git'), function (er, s) { + var doGit = !er && s.isDirectory() && npm.config.get('git-tag-version') if (!doGit) { - if (er) log.verbose("version", "error checking for .git", er) - log.verbose("version", "not tagging in git") + if (er) log.verbose('version', 'error checking for .git', er) + log.verbose('version', 'not tagging in git') return cb(null, false) } // check for git git.whichAndExec( - [ "status", "--porcelain" ], - { env : process.env }, + [ 'status', '--porcelain' ], + { env: process.env }, function (er, stdout) { - if (er && er.code === "ENOGIT") { + if (er && er.code === 'ENOGIT') { log.warn( - "version", - "This is a Git checkout, but the git command was not found.", - "npm could not create a Git tag for this release!" + 'version', + 'This is a Git checkout, but the git command was not found.', + 'npm could not create a Git tag for this release!' ) return cb(null, false) } - var lines = stdout.trim().split("\n").filter(function (line) { + var lines = stdout.trim().split('\n').filter(function (line) { return line.trim() && !line.match(/^\?\? /) }).map(function (line) { return line.trim() }) - if (lines.length) return cb(new Error( - "Git working directory not clean.\n"+lines.join("\n") - )) + if (lines.length) { + return cb(new Error( + 'Git working directory not clean.\n' + lines.join('\n') + )) + } cb(null, true) } @@ -159,29 +162,29 @@ function checkGit (cb) { } function commit (version, hasShrinkwrap, cb) { - var options = { env : process.env } - var message = npm.config.get("message").replace(/%s/g, version) - var sign = npm.config.get("sign-git-tag") - var flag = sign ? "-sm" : "-am" + var options = { env: process.env } + var message = npm.config.get('message').replace(/%s/g, version) + var sign = npm.config.get('sign-git-tag') + var flag = sign ? '-sm' : '-am' chain( [ - git.chainableExec([ "add", "package.json" ], options), - hasShrinkwrap && git.chainableExec([ "add", "npm-shrinkwrap.json" ] , options), - git.chainableExec([ "commit", "-m", message ], options), - git.chainableExec([ "tag", npm.config.get("tag-version-prefix") + version, flag, message ], options) + git.chainableExec([ 'add', 'package.json' ], options), + hasShrinkwrap && git.chainableExec([ 'add', 'npm-shrinkwrap.json' ], options), + git.chainableExec([ 'commit', '-m', message ], options), + git.chainableExec([ 'tag', npm.config.get('tag-version-prefix') + version, flag, message ], options) ], cb ) } function write (data, file, cb) { - assert(data && typeof data === "object", "must pass data to version write") - assert(typeof file === "string", "must pass filename to write to version write") + assert(data && typeof data === 'object', 'must pass data to version write') + assert(typeof file === 'string', 'must pass filename to write to version write') - log.verbose("version.write", "data", data, "to", file) + log.verbose('version.write', 'data', data, 'to', file) writeFileAtomic( path.join(npm.localPrefix, file), - new Buffer(JSON.stringify(data, null, 2) + "\n"), + new Buffer(JSON.stringify(data, null, 2) + '\n'), cb ) } diff --git a/lib/view.js b/lib/view.js index b23850430..9ca18d354 100644 --- a/lib/view.js +++ b/lib/view.js @@ -1,17 +1,17 @@ // npm view [pkg [pkg ...]] module.exports = view -view.usage = "npm view [<@scope>/]<pkg>[@<version>] [<field>[.subfield]...]" - + "\n\naliases: info, show, v" - -var npm = require("./npm.js") - , readJson = require("read-package-json") - , log = require("npmlog") - , util = require("util") - , semver = require("semver") - , mapToRegistry = require("./utils/map-to-registry.js") - , npa = require("npm-package-arg") - , path = require("path") +view.usage = 'npm view [<@scope>/]<pkg>[@<version>] [<field>[.subfield]...]' + + '\n\naliases: info, show, v' + +var npm = require('./npm.js') +var readJson = require('read-package-json') +var log = require('npmlog') +var util = require('util') +var semver = require('semver') +var mapToRegistry = require('./utils/map-to-registry.js') +var npa = require('npm-package-arg') +var path = require('path') view.completion = function (opts, cb) { if (opts.conf.argv.remain.length <= 2) { @@ -20,14 +20,14 @@ view.completion = function (opts, cb) { return cb() } // have the package, get the fields. - var tag = npm.config.get("tag") + var tag = npm.config.get('tag') mapToRegistry(opts.conf.argv.remain[2], npm.config, function (er, uri, auth) { if (er) return cb(er) - npm.registry.get(uri, { auth : auth }, function (er, d) { + npm.registry.get(uri, { auth: auth }, function (er, d) { if (er) return cb(er) - var dv = d.versions[d["dist-tags"][tag]] - , fields = [] + var dv = d.versions[d['dist-tags'][tag]] + var fields = [] d.versions = Object.keys(d.versions).sort(semver.compareLoose) fields = getFields(d).concat(getFields(dv)) cb(null, fields) @@ -39,48 +39,51 @@ view.completion = function (opts, cb) { if (!d) return f pref = pref || [] Object.keys(d).forEach(function (k) { - if (k.charAt(0) === "_" || k.indexOf(".") !== -1) return - var p = pref.concat(k).join(".") + if (k.charAt(0) === '_' || k.indexOf('.') !== -1) return + var p = pref.concat(k).join('.') f.push(p) if (Array.isArray(d[k])) { d[k].forEach(function (val, i) { - var pi = p + "[" + i + "]" - if (val && typeof val === "object") getFields(val, f, [p]) + var pi = p + '[' + i + ']' + if (val && typeof val === 'object') getFields(val, f, [p]) else f.push(pi) }) return } - if (typeof d[k] === "object") getFields(d[k], f, [p]) + if (typeof d[k] === 'object') getFields(d[k], f, [p]) }) return f } } function view (args, silent, cb) { - if (typeof cb !== "function") cb = silent, silent = false + if (typeof cb !== 'function') { + cb = silent + silent = false + } - if (!args.length) args = ["."] + if (!args.length) args = ['.'] var pkg = args.shift() - , nv = npa(pkg) - , name = nv.name - , local = (name === "." || !name) + var nv = npa(pkg) + var name = nv.name + var local = (name === '.' || !name) - if (npm.config.get("global") && local) { - return cb(new Error("Cannot use view command in global mode.")) + if (npm.config.get('global') && local) { + return cb(new Error('Cannot use view command in global mode.')) } if (local) { var dir = npm.prefix - readJson(path.resolve(dir, "package.json"), function (er, d) { + readJson(path.resolve(dir, 'package.json'), function (er, d) { d = d || {} - if (er && er.code !== "ENOENT" && er.code !== "ENOTDIR") return cb(er) - if (!d.name) return cb(new Error("Invalid package.json")) + if (er && er.code !== 'ENOENT' && er.code !== 'ENOTDIR') return cb(er) + if (!d.name) return cb(new Error('Invalid package.json')) var p = d.name nv = npa(p) - if (pkg && ~pkg.indexOf("@")) { - nv.rawSpec = pkg.split("@")[pkg.indexOf("@")] + if (pkg && ~pkg.indexOf('@')) { + nv.rawSpec = pkg.split('@')[pkg.indexOf('@')] } fetchAndRead(nv, args, silent, cb) @@ -93,53 +96,54 @@ function view (args, silent, cb) { function fetchAndRead (nv, args, silent, cb) { // get the data about this package var name = nv.name - , version = nv.rawSpec || npm.config.get("tag") + var version = nv.rawSpec || npm.config.get('tag') mapToRegistry(name, npm.config, function (er, uri, auth) { if (er) return cb(er) - npm.registry.get(uri, { auth : auth }, function (er, data) { + npm.registry.get(uri, { auth: auth }, function (er, data) { if (er) return cb(er) - if (data["dist-tags"] && data["dist-tags"].hasOwnProperty(version)) { - version = data["dist-tags"][version] + if (data['dist-tags'] && data['dist-tags'].hasOwnProperty(version)) { + version = data['dist-tags'][version] } if (data.time && data.time.unpublished) { var u = data.time.unpublished - er = new Error("Unpublished by " + u.name + " on " + u.time) + er = new Error('Unpublished by ' + u.name + ' on ' + u.time) er.statusCode = 404 - er.code = "E404" + er.code = 'E404' er.pkgid = data._id return cb(er, data) } - var results = [] - , error = null - , versions = data.versions || {} + var error = null + var versions = data.versions || {} data.versions = Object.keys(versions).sort(semver.compareLoose) - if (!args.length) args = [""] + if (!args.length) args = [''] // remove readme unless we asked for it - if (-1 === args.indexOf("readme")) { + if (args.indexOf('readme') === -1) { delete data.readme } Object.keys(versions).forEach(function (v) { - if (semver.satisfies(v, version, true)) args.forEach(function (args) { - // remove readme unless we asked for it - if (-1 === args.indexOf("readme")) { - delete versions[v].readme - } - results.push(showFields(data, versions[v], args)) - }) + if (semver.satisfies(v, version, true)) { + args.forEach(function (args) { + // remove readme unless we asked for it + if (args.indexOf('readme') !== -1) { + delete versions[v].readme + } + results.push(showFields(data, versions[v], args)) + }) + } }) results = results.reduce(reducer, {}) var retval = results - if (args.length === 1 && args[0] === "") { + if (args.length === 1 && args[0] === '') { retval = cleanBlanks(retval) - log.silly("cleanup", retval) + log.silly('cleanup', retval) } if (error || silent) cb(error, retval) @@ -151,18 +155,21 @@ function fetchAndRead (nv, args, silent, cb) { function cleanBlanks (obj) { var clean = {} Object.keys(obj).forEach(function (version) { - clean[version] = obj[version][""] + clean[version] = obj[version][''] }) return clean } function reducer (l, r) { - if (r) Object.keys(r).forEach(function (v) { - l[v] = l[v] || {} - Object.keys(r[v]).forEach(function (t) { - l[v][t] = r[v][t] + if (r) { + Object.keys(r).forEach(function (v) { + l[v] = l[v] || {} + Object.keys(r[v]).forEach(function (t) { + l[v][t] = r[v][t] + }) }) - }) + } + return l } @@ -174,12 +181,12 @@ function showFields (data, version, fields) { o[k] = s[k] }) }) - return search(o, fields.split("."), version.version, fields) + return search(o, fields.split('.'), version.version, fields) } function search (data, fields, version, title) { var field - , tail = fields + var tail = fields while (!field && fields.length) field = tail.shift() fields = [field].concat(tail) var o @@ -196,7 +203,7 @@ function search (data, fields, version, title) { if (data.field && data.field.hasOwnProperty(index)) { return search(data[field][index], tail, version, title) } else { - field = field + "[" + index + "]" + field = field + '[' + index + ']' } } if (Array.isArray(data)) { @@ -206,8 +213,8 @@ function search (data, fields, version, title) { var results = [] data.forEach(function (data, i) { var tl = title.length - , newt = title.substr(0, tl-(fields.join(".").length) - 1) - + "["+i+"]" + [""].concat(fields).join(".") + var newt = title.substr(0, tl - fields.join('.').length - 1) + + '[' + i + ']' + [''].concat(fields).join('.') results.push(search(data, fields.slice(), version, newt)) }) results = results.reduce(reducer, {}) @@ -216,11 +223,11 @@ function search (data, fields, version, title) { if (!data.hasOwnProperty(field)) return undefined data = data[field] if (tail.length) { - if (typeof data === "object") { + if (typeof data === 'object') { // there are more fields to deal with. return search(data, tail, version, title) } else { - return new Error("Not an object: "+data) + return new Error('Not an object: ' + data) } } o = {} @@ -231,33 +238,33 @@ function search (data, fields, version, title) { function printData (data, name, cb) { var versions = Object.keys(data) - , msg = "" - , includeVersions = versions.length > 1 - , includeFields + var msg = '' + var includeVersions = versions.length > 1 + var includeFields versions.forEach(function (v) { var fields = Object.keys(data[v]) includeFields = includeFields || (fields.length > 1) fields.forEach(function (f) { var d = cleanup(data[v][f]) - if (includeVersions || includeFields || typeof d !== "string") { + if (includeVersions || includeFields || typeof d !== 'string') { d = cleanup(data[v][f]) - d = npm.config.get("json") + d = npm.config.get('json') ? JSON.stringify(d, null, 2) : util.inspect(d, false, 5, npm.color) - } else if (typeof d === "string" && npm.config.get("json")) { + } else if (typeof d === 'string' && npm.config.get('json')) { d = JSON.stringify(d) } - if (f && includeFields) f += " = " - if (d.indexOf("\n") !== -1) d = " \n" + d - msg += (includeVersions ? name + "@" + v + " " : "") - + (includeFields ? f : "") + d + "\n" + if (f && includeFields) f += ' = ' + if (d.indexOf('\n') !== -1) d = ' \n' + d + msg += (includeVersions ? name + '@' + v + ' ' : '') + + (includeFields ? f : '') + d + '\n' }) }) // preserve output symmetry by adding a whitespace-only line at the end if // there's one at the beginning - if (/^\s*\n/.test(msg)) msg += "\n" + if (/^\s*\n/.test(msg)) msg += '\n' // print directly to stdout to not unnecessarily add blank lines process.stdout.write(msg) @@ -268,32 +275,32 @@ function cleanup (data) { if (Array.isArray(data)) { return data.map(cleanup) } - if (!data || typeof data !== "object") return data + if (!data || typeof data !== 'object') return data - if (typeof data.versions === "object" - && data.versions - && !Array.isArray(data.versions)) { + if (typeof data.versions === 'object' && + data.versions && + !Array.isArray(data.versions)) { data.versions = Object.keys(data.versions || {}) } var keys = Object.keys(data) keys.forEach(function (d) { - if (d.charAt(0) === "_") delete data[d] - else if (typeof data[d] === "object") data[d] = cleanup(data[d]) + if (d.charAt(0) === '_') delete data[d] + else if (typeof data[d] === 'object') data[d] = cleanup(data[d]) }) keys = Object.keys(data) - if (keys.length <= 3 - && data.name - && (keys.length === 1 - || keys.length === 3 && data.email && data.url - || keys.length === 2 && (data.email || data.url))) { + if (keys.length <= 3 && + data.name && + (keys.length === 1 || + keys.length === 3 && data.email && data.url || + keys.length === 2 && (data.email || data.url))) { data = unparsePerson(data) } return data } function unparsePerson (d) { - if (typeof d === "string") return d - return d.name - + (d.email ? " <"+d.email+">" : "") - + (d.url ? " ("+d.url+")" : "") + if (typeof d === 'string') return d + return d.name + + (d.email ? ' <' + d.email + '>' : '') + + (d.url ? ' (' + d.url + ')' : '') } diff --git a/lib/visnup.js b/lib/visnup.js index 8d710c20b..b0352fd6d 100644 --- a/lib/visnup.js +++ b/lib/visnup.js @@ -1,38 +1,38 @@ module.exports = visnup -var npm = require("./npm.js") +var npm = require('./npm.js') var handsomeFace = [ - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 232, 237, 236, 236, 232, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] - ,[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 235, 236, 235, 233, 237, 235, 233, 232, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] - ,[0, 0, 0, 0, 0, 0, 0, 0, 0, 232, 235, 233, 232, 235, 235, 234, 233, 236, 232, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] - ,[0, 0, 0, 0, 0, 0, 0, 0, 237, 235, 232, 232, 234, 233, 233, 232, 232, 233, 232, 232, 235, 232, 233, 234, 234, 0, 0, 0, 0, 0, 0, 0, 0, 0] - ,[0, 0, 0, 0, 0, 0, 0, 232, 232, 232, 239, 238, 235, 233, 232, 232, 232, 232, 232, 232, 232, 233, 235, 232, 233, 233, 232, 0, 0, 0, 0, 0, 0, 0] - ,[0, 0, 0, 0, 234, 234, 232, 233, 234, 233, 234, 235, 233, 235, 60, 238, 238, 234, 234, 233, 234, 233, 238, 251, 246, 233, 233, 232, 0, 0, 0, 0, 0, 0] - ,[0, 0, 233, 233, 233, 232, 232, 239, 249, 251, 252, 231, 231, 188, 250, 254, 59, 60, 255, 231, 231, 231, 252, 235, 239, 235, 232, 233, 0, 0, 0, 0, 0, 0] - ,[0, 0, 232, 233, 232, 232, 232, 248, 231, 231, 231, 231, 231, 231, 231, 254, 238, 254, 231, 231, 231, 231, 231, 252, 233, 235, 237, 233, 234, 0, 0, 0, 0, 0] - ,[0, 0, 233, 232, 232, 232, 248, 231, 231, 231, 231, 231, 231, 231, 231, 231, 231, 231, 231, 231, 231, 231, 231, 231, 251, 233, 233, 233, 236, 233, 0, 0, 0, 0] - ,[232, 233, 233, 232, 232, 246, 231, 231, 231, 231, 231, 231, 231, 231, 231, 231, 231, 231, 231, 231, 231, 231, 231, 231, 231, 231, 249, 233, 234, 234, 0, 0, 0, 0] - ,[232, 232, 232, 232, 233, 249, 231, 255, 255, 255, 255, 254, 109, 60, 239, 237, 238, 237, 235, 235, 235, 235, 236, 235, 235, 235, 234, 232, 232, 232, 232, 232, 233, 0] - ,[0, 232, 232, 233, 233, 233, 233, 233, 233, 233, 233, 233, 235, 236, 238, 238, 235, 188, 254, 254, 145, 236, 252, 254, 254, 254, 254, 249, 236, 235, 232, 232, 233, 0] - ,[0, 0, 233, 237, 249, 239, 233, 252, 231, 231, 231, 231, 231, 231, 254, 235, 235, 254, 231, 231, 251, 235, 237, 231, 231, 231, 231, 7, 237, 235, 232, 233, 233, 0] - ,[0, 0, 0, 0, 233, 248, 239, 233, 231, 231, 231, 231, 254, 233, 233, 235, 254, 255, 231, 254, 237, 236, 254, 239, 235, 235, 233, 233, 232, 232, 233, 232, 0, 0] - ,[0, 0, 0, 232, 233, 246, 255, 255, 236, 236, 236, 236, 236, 255, 231, 231, 231, 231, 231, 231, 252, 234, 248, 231, 231, 231, 231, 248, 232, 232, 232, 0, 0, 0] - ,[0, 0, 0, 0, 235, 237, 7, 231, 231, 231, 231, 231, 231, 231, 231, 231, 231, 231, 231, 231, 255, 238, 235, 7, 231, 231, 231, 246, 232, 0, 0, 0, 0, 0] - ,[0, 0, 0, 0, 0, 235, 103, 188, 231, 231, 231, 231, 231, 231, 231, 231, 231, 231, 231, 231, 231, 252, 232, 238, 231, 231, 255, 244, 232, 0, 0, 0, 0, 0] - ,[0, 0, 0, 0, 0, 235, 236, 103, 146, 253, 255, 231, 231, 231, 231, 231, 253, 251, 250, 250, 250, 246, 232, 235, 152, 255, 146, 66, 233, 0, 0, 0, 0, 0] - ,[0, 0, 0, 0, 0, 0, 233, 103, 146, 146, 146, 146, 254, 231, 231, 231, 109, 103, 146, 255, 188, 239, 240, 103, 255, 253, 103, 238, 234, 0, 0, 0, 0, 0] - ,[0, 0, 0, 0, 0, 0, 232, 235, 109, 146, 146, 146, 146, 146, 252, 152, 146, 146, 146, 146, 146, 146, 146, 146, 146, 146, 103, 235, 233, 0, 0, 0, 0, 0] - ,[0, 0, 0, 0, 0, 0, 0, 235, 235, 103, 146, 146, 146, 146, 146, 146, 188, 188, 188, 188, 188, 188, 152, 146, 146, 146, 66, 235, 0, 0, 0, 0, 0, 0] - ,[0, 0, 0, 0, 0, 0, 0, 0, 233, 235, 66, 146, 146, 146, 146, 152, 255, 146, 240, 239, 241, 109, 146, 146, 146, 103, 233, 0, 0, 0, 0, 0, 0, 0] - ,[0, 0, 0, 0, 0, 0, 0, 0, 0, 234, 237, 109, 146, 146, 146, 146, 146, 254, 231, 231, 188, 146, 146, 146, 103, 233, 0, 0, 0, 0, 0, 0, 0, 0] - ,[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 233, 237, 60, 103, 146, 146, 146, 146, 146, 103, 66, 60, 235, 232, 0, 0, 0, 0, 0, 0, 0, 0, 0] - ,[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 232, 233, 233, 236, 235, 237, 235, 237, 237, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]] - + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 232, 237, 236, 236, 232, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 235, 236, 235, 233, 237, 235, 233, 232, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 232, 235, 233, 232, 235, 235, 234, 233, 236, 232, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 237, 235, 232, 232, 234, 233, 233, 232, 232, 233, 232, 232, 235, 232, 233, 234, 234, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 232, 232, 232, 239, 238, 235, 233, 232, 232, 232, 232, 232, 232, 232, 233, 235, 232, 233, 233, 232, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 234, 234, 232, 233, 234, 233, 234, 235, 233, 235, 60, 238, 238, 234, 234, 233, 234, 233, 238, 251, 246, 233, 233, 232, 0, 0, 0, 0, 0, 0], + [0, 0, 233, 233, 233, 232, 232, 239, 249, 251, 252, 231, 231, 188, 250, 254, 59, 60, 255, 231, 231, 231, 252, 235, 239, 235, 232, 233, 0, 0, 0, 0, 0, 0], + [0, 0, 232, 233, 232, 232, 232, 248, 231, 231, 231, 231, 231, 231, 231, 254, 238, 254, 231, 231, 231, 231, 231, 252, 233, 235, 237, 233, 234, 0, 0, 0, 0, 0], + [0, 0, 233, 232, 232, 232, 248, 231, 231, 231, 231, 231, 231, 231, 231, 231, 231, 231, 231, 231, 231, 231, 231, 231, 251, 233, 233, 233, 236, 233, 0, 0, 0, 0], + [232, 233, 233, 232, 232, 246, 231, 231, 231, 231, 231, 231, 231, 231, 231, 231, 231, 231, 231, 231, 231, 231, 231, 231, 231, 231, 249, 233, 234, 234, 0, 0, 0, 0], + [232, 232, 232, 232, 233, 249, 231, 255, 255, 255, 255, 254, 109, 60, 239, 237, 238, 237, 235, 235, 235, 235, 236, 235, 235, 235, 234, 232, 232, 232, 232, 232, 233, 0], + [0, 232, 232, 233, 233, 233, 233, 233, 233, 233, 233, 233, 235, 236, 238, 238, 235, 188, 254, 254, 145, 236, 252, 254, 254, 254, 254, 249, 236, 235, 232, 232, 233, 0], + [0, 0, 233, 237, 249, 239, 233, 252, 231, 231, 231, 231, 231, 231, 254, 235, 235, 254, 231, 231, 251, 235, 237, 231, 231, 231, 231, 7, 237, 235, 232, 233, 233, 0], + [0, 0, 0, 0, 233, 248, 239, 233, 231, 231, 231, 231, 254, 233, 233, 235, 254, 255, 231, 254, 237, 236, 254, 239, 235, 235, 233, 233, 232, 232, 233, 232, 0, 0], + [0, 0, 0, 232, 233, 246, 255, 255, 236, 236, 236, 236, 236, 255, 231, 231, 231, 231, 231, 231, 252, 234, 248, 231, 231, 231, 231, 248, 232, 232, 232, 0, 0, 0], + [0, 0, 0, 0, 235, 237, 7, 231, 231, 231, 231, 231, 231, 231, 231, 231, 231, 231, 231, 231, 255, 238, 235, 7, 231, 231, 231, 246, 232, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 235, 103, 188, 231, 231, 231, 231, 231, 231, 231, 231, 231, 231, 231, 231, 231, 252, 232, 238, 231, 231, 255, 244, 232, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 235, 236, 103, 146, 253, 255, 231, 231, 231, 231, 231, 253, 251, 250, 250, 250, 246, 232, 235, 152, 255, 146, 66, 233, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 233, 103, 146, 146, 146, 146, 254, 231, 231, 231, 109, 103, 146, 255, 188, 239, 240, 103, 255, 253, 103, 238, 234, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 232, 235, 109, 146, 146, 146, 146, 146, 252, 152, 146, 146, 146, 146, 146, 146, 146, 146, 146, 146, 103, 235, 233, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 235, 235, 103, 146, 146, 146, 146, 146, 146, 188, 188, 188, 188, 188, 188, 152, 146, 146, 146, 66, 235, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 233, 235, 66, 146, 146, 146, 146, 152, 255, 146, 240, 239, 241, 109, 146, 146, 146, 103, 233, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 234, 237, 109, 146, 146, 146, 146, 146, 254, 231, 231, 188, 146, 146, 146, 103, 233, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 233, 237, 60, 103, 146, 146, 146, 146, 146, 103, 66, 60, 235, 232, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 232, 233, 233, 236, 235, 237, 235, 237, 237, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] +] function visnup (args, cb) { handsomeFace.forEach(function (line) { console.log(line.map(function (ch) { - return "\033[" + (ch ? "48;5;" + ch : ch) + "m" + return '\u001b[' + (ch ? '48;5;' + ch : ch) + 'm' }).join(' ')) }) diff --git a/lib/whoami.js b/lib/whoami.js index a3f83cf45..77d52eef9 100644 --- a/lib/whoami.js +++ b/lib/whoami.js @@ -1,31 +1,30 @@ -var npm = require("./npm.js") +var npm = require('./npm.js') module.exports = whoami -whoami.usage = "npm whoami [--registry <registry>]\n(just prints username according to given registry)" +whoami.usage = 'npm whoami [--registry <registry>]\n(just prints username according to given registry)' function whoami (args, silent, cb) { // FIXME: need tighter checking on this, but is a breaking change - if (typeof cb !== "function") { + if (typeof cb !== 'function') { cb = silent silent = false } - var registry = npm.config.get("registry") - if (!registry) return cb(new Error("no default registry set")) + var registry = npm.config.get('registry') + if (!registry) return cb(new Error('no default registry set')) var auth = npm.config.getCredentialsByURI(registry) if (auth) { if (auth.username) { if (!silent) console.log(auth.username) return process.nextTick(cb.bind(this, null, auth.username)) - } - else if (auth.token) { - return npm.registry.whoami(registry, { auth : auth }, function (er, username) { + } else if (auth.token) { + return npm.registry.whoami(registry, { auth: auth }, function (er, username) { if (er) return cb(er) if (!username) { var needNewSession = new Error( - "Your auth token is no longer valid. Please log in again." + 'Your auth token is no longer valid. Please log in again.' ) needNewSession.code = 'ENEEDAUTH' return cb(needNewSession) diff --git a/lib/xmas.js b/lib/xmas.js index fa8d1db55..25535533e 100644 --- a/lib/xmas.js +++ b/lib/xmas.js @@ -1,55 +1,59 @@ // happy xmas -var log = require("npmlog") +var log = require('npmlog') module.exports = function (args, cb) { -var s = process.platform === "win32" ? " *" : " \u2605" - , f = "\uFF0F" - , b = "\uFF3C" - , x = process.platform === "win32" ? " " : "" - , o = [ "\u0069" , "\u0020", "\u0020", "\u0020", "\u0020", "\u0020" - , "\u0020", "\u0020", "\u0020", "\u0020", "\u0020", "\u0020" - , "\u0020", "\u2E1B","\u2042","\u2E2E","&","@","\uFF61" ] - , oc = [21,33,34,35,36,37] - , l = "\u005e" + var s = process.platform === 'win32' ? ' *' : ' \u2605' + var f = '\uFF0F' + var b = '\uFF3C' + var x = process.platform === 'win32' ? ' ' : '' + var o = [ + '\u0069', '\u0020', '\u0020', '\u0020', '\u0020', '\u0020', + '\u0020', '\u0020', '\u0020', '\u0020', '\u0020', '\u0020', + '\u0020', '\u2E1B', '\u2042', '\u2E2E', '&', '@', '\uFF61' + ] + var oc = [21, 33, 34, 35, 36, 37] + var l = '\u005e' -function w (s) { process.stderr.write(s) } + function w (s) { process.stderr.write(s) } -w("\n") -;(function T (H) { - for (var i = 0; i < H; i ++) w(" ") - w(x+"\033[33m"+s+"\n") - var M = H * 2 - 1 - for (var L = 1; L <= H; L ++) { - var O = L * 2 - 2 - var S = (M - O) / 2 - for (i = 0; i < S; i ++) w(" ") - w(x+"\033[32m"+f) - for (i = 0; i < O; i ++) w( - "\033["+oc[Math.floor(Math.random()*oc.length)]+"m"+ - o[Math.floor(Math.random() * o.length)] - ) - w(x+"\033[32m"+b+"\n") - } - w(" ") - for (i = 1; i < H; i ++) w("\033[32m"+l) - w("| "+x+" |") - for (i = 1; i < H; i ++) w("\033[32m"+l) - if (H > 10) { - w("\n ") - for (i = 1; i < H; i ++) w(" ") - w("| "+x+" |") - for (i = 1; i < H; i ++) w(" ") - } -})(20) -w("\n\n") -log.heading = '' -log.addLevel('npm', 100000, log.headingStyle) -log.npm("loves you", "Happy Xmas, Noders!") -cb() + w('\n') + ;(function T (H) { + for (var i = 0; i < H; i++) w(' ') + w(x + '\u001b[33m' + s + '\n') + var M = H * 2 - 1 + for (var L = 1; L <= H; L++) { + var O = L * 2 - 2 + var S = (M - O) / 2 + for (i = 0; i < S; i++) w(' ') + w(x + '\u001b[32m' + f) + for (i = 0; i < O; i++) { + w( + '\u001b[' + oc[Math.floor(Math.random() * oc.length)] + 'm' + + o[Math.floor(Math.random() * o.length)] + ) + } + w(x + '\u001b[32m' + b + '\n') + } + w(' ') + for (i = 1; i < H; i++) w('\u001b[32m' + l) + w('| ' + x + ' |') + for (i = 1; i < H; i++) w('\u001b[32m' + l) + if (H > 10) { + w('\n ') + for (i = 1; i < H; i++) w(' ') + w('| ' + x + ' |') + for (i = 1; i < H; i++) w(' ') + } + })(20) + w('\n\n') + log.heading = '' + log.addLevel('npm', 100000, log.headingStyle) + log.npm('loves you', 'Happy Xmas, Noders!') + cb() } -var dg=false -Object.defineProperty(module.exports, "usage", {get:function () { +var dg = false +Object.defineProperty(module.exports, 'usage', {get: function () { if (dg) module.exports([], function () {}) dg = true - return " " + return ' ' }}) diff --git a/scripts/index-build.js b/scripts/index-build.js index 21297cc93..8fbbf8595 100755 --- a/scripts/index-build.js +++ b/scripts/index-build.js @@ -1,63 +1,58 @@ #!/usr/bin/env node -var fs = require("fs") - , path = require("path") - , root = path.resolve(__dirname, "..") - , glob = require("glob") - , conversion = { "cli": 1, "api": 3, "files": 5, "misc": 7 } - -glob(root + "/{README.md,doc/*/*.md}", function (er, files) { - if (er) - throw er +var fs = require('fs') +var path = require('path') +var root = path.resolve(__dirname, '..') +var glob = require('glob') +var conversion = { 'cli': 1, 'api': 3, 'files': 5, 'misc': 7 } + +glob(root + '/{README.md,doc/*/*.md}', function (er, files) { + if (er) throw er + output(files.map(function (f) { var b = path.basename(f) - if (b === "README.md") - return [0, b] - if (b === "index.md") - return null + if (b === 'README.md') return [0, b] + if (b === 'index.md') return null var s = conversion[path.basename(path.dirname(f))] return [s, f] }).filter(function (f) { return f }).sort(function (a, b) { - return (a[0] === b[0]) - ? ( path.basename(a[1]) === "npm.md" ? -1 - : path.basename(b[1]) === "npm.md" ? 1 - : a[1] > b[1] ? 1 : -1 ) - : a[0] - b[0] + return (a[0] === b[0]) ? + (path.basename(a[1]) === 'npm.md' ? -1 : + path.basename(b[1]) === 'npm.md' ? 1 : + a[1] > b[1] ? 1 : -1) : + a[0] - b[0] })) }) -return - function output (files) { console.log( - "npm-index(7) -- Index of all npm documentation\n" + - "==============================================\n") + 'npm-index(7) -- Index of all npm documentation\n' + + '==============================================\n') writeLines(files, 0) - writeLines(files, 1, "Command Line Documentation", "Using npm on the command line") - writeLines(files, 3, "API Documentation", "Using npm in your Node programs") - writeLines(files, 5, "Files", "File system structures npm uses") - writeLines(files, 7, "Misc", "Various other bits and bobs") + writeLines(files, 1, 'Command Line Documentation', 'Using npm on the command line') + writeLines(files, 3, 'API Documentation', 'Using npm in your Node programs') + writeLines(files, 5, 'Files', 'File system structures npm uses') + writeLines(files, 7, 'Misc', 'Various other bits and bobs') } function writeLines (files, sxn, heading, desc) { if (heading) { - console.log("## %s\n\n%s\n", heading, desc) + console.log('## %s\n\n%s\n', heading, desc) } files.filter(function (f) { return f[0] === sxn }).forEach(writeLine) } - function writeLine (sd) { var sxn = sd[0] || 1 - , doc = sd[1] - , d = path.basename(doc, ".md") + var doc = sd[1] + var d = path.basename(doc, '.md') - var content = fs.readFileSync(doc, "utf8").split("\n")[0].split("-- ")[1] + var content = fs.readFileSync(doc, 'utf8').split('\n')[0].split('-- ')[1] - console.log("### %s(%d)\n", d, sxn) - console.log(content + "\n") + console.log('### %s(%d)\n', d, sxn) + console.log(content + '\n') } diff --git a/scripts/publish-tag.js b/scripts/publish-tag.js index 046ec9888..d0c04556e 100644 --- a/scripts/publish-tag.js +++ b/scripts/publish-tag.js @@ -1,3 +1,3 @@ -var semver = require("semver") -var version = semver.parse(require("../package.json").version) +var semver = require('semver') +var version = semver.parse(require('../package.json').version) console.log('v%s.%s-next', version.major, version.minor) diff --git a/test/common.js b/test/common.js deleted file mode 100644 index 2755056b1..000000000 --- a/test/common.js +++ /dev/null @@ -1,7 +0,0 @@ - -// whatever, it's just tests. -;["util","assert"].forEach(function (thing) { - thing = require("thing") - for (var i in thing) global[i] = thing[i] -} - diff --git a/test/disabled/package-config/test.js b/test/disabled/package-config/test.js index 7337b237b..386891d31 100755 --- a/test/disabled/package-config/test.js +++ b/test/disabled/package-config/test.js @@ -1,17 +1,20 @@ #!/usr/bin/env node var env = process.env - , orig = require(process.env.npm_package_name+"/package.json").config - , assert = require("assert") +var orig = require(process.env.npm_package_name + '/package.json').config +var assert = require('assert') -console.log("Before running this test, do:\n" - +" npm config set package-config:foo boo\n" - +"or else it's about to fail.") -assert.equal(env.npm_package_config_foo, "boo", "foo != boo") -assert.equal(orig.foo, "bar", "original foo != bar") -assert.equal(env["npm_config_package-config:foo"], "boo", - "package-config:foo != boo") -console.log({ foo: env.npm_package_config_foo - , orig_foo: orig.foo - , "package-config:foo": env["npm_config_package-config:foo"] - }) +console.log( + 'Before running this test, do:\n' + + ' npm config set package-config:foo boo\n' + + "or else it's about to fail." +) +assert.equal(env.npm_package_config_foo, 'boo', 'foo != boo') +assert.equal(orig.foo, 'bar', 'original foo != bar') +assert.equal(env['npm_config_package-config:foo'], 'boo', + 'package-config:foo != boo') +console.log({ + foo: env.npm_package_config_foo, + orig_foo: orig.foo, + 'package-config:foo': env['npm_config_package-config:foo'] +}) diff --git a/test/packages/npm-test-blerg/test.js b/test/packages/npm-test-blerg/test.js index f548458ac..cc8d2da54 100644 --- a/test/packages/npm-test-blerg/test.js +++ b/test/packages/npm-test-blerg/test.js @@ -1,5 +1,4 @@ - -var assert = require("assert") -assert.equal(undefined, process.env.npm_config__password, "password exposed!") -assert.equal(undefined, process.env.npm_config__auth, "auth exposed!") -assert.equal(undefined, process.env.npm_config__authCrypt, "authCrypt exposed!") +var assert = require('assert') +assert.equal(undefined, process.env.npm_config__password, 'password exposed!') +assert.equal(undefined, process.env.npm_config__auth, 'auth exposed!') +assert.equal(undefined, process.env.npm_config__authCrypt, 'authCrypt exposed!') diff --git a/test/packages/npm-test-blerg3/test.js b/test/packages/npm-test-blerg3/test.js index f548458ac..cc8d2da54 100644 --- a/test/packages/npm-test-blerg3/test.js +++ b/test/packages/npm-test-blerg3/test.js @@ -1,5 +1,4 @@ - -var assert = require("assert") -assert.equal(undefined, process.env.npm_config__password, "password exposed!") -assert.equal(undefined, process.env.npm_config__auth, "auth exposed!") -assert.equal(undefined, process.env.npm_config__authCrypt, "authCrypt exposed!") +var assert = require('assert') +assert.equal(undefined, process.env.npm_config__password, 'password exposed!') +assert.equal(undefined, process.env.npm_config__auth, 'auth exposed!') +assert.equal(undefined, process.env.npm_config__authCrypt, 'authCrypt exposed!') diff --git a/test/packages/npm-test-bundled-git/test.js b/test/packages/npm-test-bundled-git/test.js index 4fcc54caf..793cc55a8 100644 --- a/test/packages/npm-test-bundled-git/test.js +++ b/test/packages/npm-test-bundled-git/test.js @@ -1,4 +1,4 @@ -var a = require("./node_modules/glob/node_modules/minimatch/package.json") -var e = require("./minimatch-expected.json") -var assert = require("assert") +var a = require('./node_modules/glob/node_modules/minimatch/package.json') +var e = require('./minimatch-expected.json') +var assert = require('assert') assert.deepEqual(a, e, "didn't get expected minimatch/package.json") diff --git a/test/packages/npm-test-ignore-nested-nm/test.js b/test/packages/npm-test-ignore-nested-nm/test.js index 308c66b50..18a0f0b56 100644 --- a/test/packages/npm-test-ignore-nested-nm/test.js +++ b/test/packages/npm-test-ignore-nested-nm/test.js @@ -1,2 +1,2 @@ -fs = require('fs') +var fs = require('fs') fs.statSync(__dirname + '/lib/node_modules/foo') diff --git a/test/packages/npm-test-missing-bindir/test.js b/test/packages/npm-test-missing-bindir/test.js index f548458ac..cc8d2da54 100644 --- a/test/packages/npm-test-missing-bindir/test.js +++ b/test/packages/npm-test-missing-bindir/test.js @@ -1,5 +1,4 @@ - -var assert = require("assert") -assert.equal(undefined, process.env.npm_config__password, "password exposed!") -assert.equal(undefined, process.env.npm_config__auth, "auth exposed!") -assert.equal(undefined, process.env.npm_config__authCrypt, "authCrypt exposed!") +var assert = require('assert') +assert.equal(undefined, process.env.npm_config__password, 'password exposed!') +assert.equal(undefined, process.env.npm_config__auth, 'auth exposed!') +assert.equal(undefined, process.env.npm_config__authCrypt, 'authCrypt exposed!') diff --git a/test/packages/npm-test-optional-deps/test.js b/test/packages/npm-test-optional-deps/test.js index 2232906d6..b9dc2c79b 100644 --- a/test/packages/npm-test-optional-deps/test.js +++ b/test/packages/npm-test-optional-deps/test.js @@ -1,9 +1,9 @@ -var fs = require("fs") -var assert = require("assert") -var path = require("path") +var fs = require('fs') +var assert = require('assert') +var path = require('path') // sax should be the only dep that ends up installed -var dir = path.resolve(__dirname, "node_modules") -assert.deepEqual(fs.readdirSync(dir), ["sax"]) -assert.equal(require("sax/package.json").version, "0.3.5") +var dir = path.resolve(__dirname, 'node_modules') +assert.deepEqual(fs.readdirSync(dir), ['sax']) +assert.equal(require('sax/package.json').version, '0.3.5') diff --git a/test/packages/npm-test-shrinkwrap/test.js b/test/packages/npm-test-shrinkwrap/test.js index fba90ec65..34638c2ce 100644 --- a/test/packages/npm-test-shrinkwrap/test.js +++ b/test/packages/npm-test-shrinkwrap/test.js @@ -1,5 +1,4 @@ -var path = require("path") -var assert = require("assert") +var assert = require('assert') process.env.npm_config_prefix = process.cwd() delete process.env.npm_config_global @@ -7,13 +6,13 @@ delete process.env.npm_config_depth var npm = process.env.npm_execpath -require("child_process").execFile(process.execPath, [npm, "ls", "--json"], { - stdio: "pipe", env: process.env, cwd: process.cwd() }, +require('child_process').execFile(process.execPath, [npm, 'ls', '--json'], { + stdio: 'pipe', env: process.env, cwd: process.cwd() }, function (err, stdout, stderr) { if (err) throw err var actual = JSON.parse(stdout) - var expected = require("./npm-shrinkwrap.json") + var expected = require('./npm-shrinkwrap.json') rmFrom(actual) actual = actual.dependencies rmFrom(expected) @@ -26,10 +25,12 @@ require("child_process").execFile(process.execPath, [npm, "ls", "--json"], { function rmFrom (obj) { for (var i in obj) { - if (i === "from") + if (i === 'from') { delete obj[i] - else if (i === "dependencies") - for (var j in obj[i]) + } else if (i === 'dependencies') { + for (var j in obj[i]) { rmFrom(obj[i][j]) + } + } } } diff --git a/test/run.js b/test/run.js index 5b33e68ab..c9eb97569 100644 --- a/test/run.js +++ b/test/run.js @@ -1,35 +1,35 @@ // Everything in this file uses child processes, because we're // testing a command line utility. -var chain = require("slide").chain -var child_process = require("child_process") -var path = require("path") - , testdir = __dirname - , fs = require("graceful-fs") - , npmpkg = path.dirname(testdir) - , npmcli = path.resolve(npmpkg, "bin", "npm-cli.js") - -var temp = process.env.TMPDIR - || process.env.TMP - || process.env.TEMP - || ( process.platform === "win32" - ? "c:\\windows\\temp" - : "/tmp" ) - -temp = path.resolve(temp, "npm-test-" + process.pid) - -var root = path.resolve(temp, "root") - , cache = path.resolve(temp, "npm_cache") +var chain = require('slide').chain +var child_process = require('child_process') +var path = require('path') +var testdir = __dirname +var fs = require('graceful-fs') +var npmpkg = path.dirname(testdir) +var npmcli = path.resolve(npmpkg, 'bin', 'npm-cli.js') + +var temp = process.env.TMPDIR || + process.env.TMP || + process.env.TEMP || + (process.platform === 'win32' ? + 'c:\\windows\\temp' : + '/tmp') + +temp = path.resolve(temp, 'npm-test-' + process.pid) + +var root = path.resolve(temp, 'root') +var cache = path.resolve(temp, 'npm_cache') var failures = 0 - , mkdir = require("mkdirp") - , rimraf = require("rimraf") +var mkdir = require('mkdirp') +var rimraf = require('rimraf') -var pathEnvSplit = process.platform === "win32" ? ";" : ":" - , pathEnv = process.env.PATH.split(pathEnvSplit) - , npmPath = process.platform === "win32" ? root : path.join(root, "bin") +var pathEnvSplit = process.platform === 'win32' ? ';' : ':' +var pathEnv = process.env.PATH.split(pathEnvSplit) +var npmPath = process.platform === 'win32' ? root : path.join(root, 'bin') -pathEnv.unshift(npmPath, path.join(root, "node_modules", ".bin")) +pathEnv.unshift(npmPath, path.join(root, 'node_modules', '.bin')) // lastly, make sure that we get the same node that is being used to do // run this script. That's very important, especially when running this @@ -42,66 +42,65 @@ Object.keys(process.env).forEach(function (i) { env[i] = process.env[i] }) env.npm_config_prefix = root -env.npm_config_color = "always" -env.npm_config_global = "true" +env.npm_config_color = 'always' +env.npm_config_global = 'true' // have to set this to false, or it'll try to test itself forever -env.npm_config_npat = "false" +env.npm_config_npat = 'false' env.PATH = pathEnv.join(pathEnvSplit) -env.NODE_PATH = path.join(root, "node_modules") +env.NODE_PATH = path.join(root, 'node_modules') env.npm_config_cache = cache - - function cleanup (cb) { if (failures !== 0) return rimraf(root, function (er) { if (er) cb(er) - mkdir(root, 0755, cb) + mkdir(root, parseInt('0755', 8), cb) }) } function prefix (content, pref) { - return pref + (content.trim().split(/\r?\n/).join("\n" + pref)) + return pref + (content.trim().split(/\r?\n/).join('\n' + pref)) } var execCount = 0 function exec (cmd, cwd, shouldFail, cb) { - if (typeof shouldFail === "function") { - cb = shouldFail, shouldFail = false + if (typeof shouldFail === 'function') { + cb = shouldFail + shouldFail = false } - console.error("\n+"+cmd + (shouldFail ? " (expect failure)" : "")) + console.error('\n+' + cmd + (shouldFail ? ' (expect failure)' : '')) // special: replace 'node' with the current execPath, // and 'npm' with the thing we installed. var cmdShow = cmd - var npmReplace = path.resolve(npmPath, "npm") + var npmReplace = path.resolve(npmPath, 'npm') var nodeReplace = process.execPath - if (process.platform === "win32") { + if (process.platform === 'win32') { npmReplace = '"' + npmReplace + '"' nodeReplace = '"' + nodeReplace + '"' } - cmd = cmd.replace(/^npm /, npmReplace + " ") - cmd = cmd.replace(/^node /, nodeReplace + " ") + cmd = cmd.replace(/^npm /, npmReplace + ' ') + cmd = cmd.replace(/^node /, nodeReplace + ' ') - console.error("$$$$$$ cd %s; PATH=%s %s", cwd, env.PATH, cmd) + console.error('$$$$$$ cd %s; PATH=%s %s', cwd, env.PATH, cmd) child_process.exec(cmd, {cwd: cwd, env: env}, function (er, stdout, stderr) { - console.error("$$$$$$ after command", cmd, cwd) + console.error('$$$$$$ after command', cmd, cwd) if (stdout) { - console.error(prefix(stdout, " 1> ")) + console.error(prefix(stdout, ' 1> ')) } if (stderr) { - console.error(prefix(stderr, " 2> ")) + console.error(prefix(stderr, ' 2> ')) } - execCount ++ + execCount++ if (!shouldFail && !er || shouldFail && er) { - // stdout = (""+stdout).trim() - console.log("ok " + execCount + " " + cmdShow) + // stdout = (''+stdout).trim() + console.log('ok ' + execCount + ' ' + cmdShow) return cb() } else { - console.log("not ok " + execCount + " " + cmdShow) - cb(new Error("failed "+cmdShow)) + console.log('not ok ' + execCount + ' ' + cmdShow) + cb(new Error('failed ' + cmdShow)) } }) } @@ -121,23 +120,21 @@ function flatten (arr) { function setup (cb) { cleanup(function (er) { if (er) return cb(er) - exec("node \""+npmcli+"\" install \""+npmpkg+"\"", root, false, cb) + exec('node \'' + npmcli + '\' install \'' + npmpkg + '\'', root, false, cb) }) } function main (cb) { - console.log("# testing in %s", temp) - console.log("# global prefix = %s", root) - - + console.log('# testing in %s', temp) + console.log('# global prefix = %s', root) failures = 0 process.chdir(testdir) - var base = path.resolve(root, path.join("lib", "node_modules")) + var base = path.resolve(root, path.join('lib', 'node_modules')) // get the list of packages - var packages = fs.readdirSync(path.resolve(testdir, "packages")) + var packages = fs.readdirSync(path.resolve(testdir, 'packages')) packages = packages.filter(function (p) { return p && !p.match(/^\./) }) @@ -146,41 +143,44 @@ function main (cb) { function installAllThenTestAll () { var packagesToRm = packages.slice(0) - if (process.platform !== "win32") { + if (process.platform !== 'win32') { // Windows can't handle npm rm npm due to file-in-use issues. - packagesToRm.push("npm") + packagesToRm.push('npm') } chain( - [ setup - , [ exec, "npm install "+npmpkg, testdir ] - , [ execChain, packages.map(function (p) { - return [ "npm install packages/"+p, testdir ] - }) ] - , [ execChain, packages.map(function (p) { - return [ "npm test -ddd", path.resolve(base, p) ] - }) ] - , [ execChain, packagesToRm.map(function (p) { - return [ "npm rm "+p, root ] - }) ] - , installAndTestEach - ] - , cb - ) + [ + setup, + [exec, 'npm install ' + npmpkg, testdir], + [execChain, packages.map(function (p) { + return [ 'npm install packages/' + p, testdir ] + })], + [execChain, packages.map(function (p) { + return [ 'npm test -ddd', path.resolve(base, p) ] + })], + [execChain, packagesToRm.map(function (p) { + return [ 'npm rm ' + p, root ] + })], + installAndTestEach + ], + cb + ) } function installAndTestEach (cb) { var thingsToChain = [ - setup - , [ execChain, flatten(packages.map(function (p) { - return [ [ "npm install packages/"+p, testdir ] - , [ "npm test", path.resolve(base, p) ] - , [ "npm rm "+p, root ] ] - })) ] + setup, + [execChain, flatten(packages.map(function (p) { + return [ + ['npm install packages/' + p, testdir], + ['npm test', path.resolve(base, p)], + ['npm rm ' + p, root] + ] + }))] ] - if (process.platform !== "win32") { + if (process.platform !== 'win32') { // Windows can't handle npm rm npm due to file-in-use issues. - thingsToChain.push([exec, "npm rm npm", testdir]) + thingsToChain.push([exec, 'npm rm npm', testdir]) } chain(thingsToChain, cb) @@ -188,6 +188,6 @@ function main (cb) { } main(function (er) { - console.log("1.." + execCount) + console.log('1..' + execCount) if (er) throw er }) diff --git a/test/tap/00-check-mock-dep.js b/test/tap/00-check-mock-dep.js index 1c862317c..cdc7af852 100644 --- a/test/tap/00-check-mock-dep.js +++ b/test/tap/00-check-mock-dep.js @@ -1,17 +1,17 @@ -console.log("TAP Version 13") +console.log('TAP Version 13') -process.on("uncaughtException", function (er) { +process.on('uncaughtException', function (er) { if (er) { throw er } - console.log("not ok - Failed checking mock registry dep. Expect much fail!") - console.log("1..1") + console.log('not ok - Failed checking mock registry dep. Expect much fail!') + console.log('1..1') process.exit(1) }) -var assert = require("assert") -var semver = require("semver") -var mock = require("npm-registry-mock/package.json").version -var req = require("../../package.json").devDependencies["npm-registry-mock"] +var assert = require('assert') +var semver = require('semver') +var mock = require('npm-registry-mock/package.json').version +var req = require('../../package.json').devDependencies['npm-registry-mock'] assert(semver.satisfies(mock, req)) -console.log("ok") -console.log("1..1") +console.log('ok') +console.log('1..1') diff --git a/test/tap/00-config-setup.js b/test/tap/00-config-setup.js index 33581eb13..a6687d116 100644 --- a/test/tap/00-config-setup.js +++ b/test/tap/00-config-setup.js @@ -1,32 +1,32 @@ -var path = require("path") -var userconfigSrc = path.resolve(__dirname, "..", "fixtures", "config", "userconfig") -exports.userconfig = userconfigSrc + "-with-gc" -exports.globalconfig = path.resolve(__dirname, "..", "fixtures", "config", "globalconfig") -exports.builtin = path.resolve(__dirname, "..", "fixtures", "config", "builtin") -exports.malformed = path.resolve(__dirname, "..", "fixtures", "config", "malformed") +var path = require('path') +var userconfigSrc = path.resolve(__dirname, '..', 'fixtures', 'config', 'userconfig') +exports.userconfig = userconfigSrc + '-with-gc' +exports.globalconfig = path.resolve(__dirname, '..', 'fixtures', 'config', 'globalconfig') +exports.builtin = path.resolve(__dirname, '..', 'fixtures', 'config', 'builtin') +exports.malformed = path.resolve(__dirname, '..', 'fixtures', 'config', 'malformed') exports.ucData = { globalconfig: exports.globalconfig, - email: "i@izs.me", - "env-thing": "asdf", - "init.author.name": "Isaac Z. Schlueter", - "init.author.email": "i@izs.me", - "init.author.url": "http://blog.izs.me/", - "init.version": "1.2.3", - "proprietary-attribs": false, - "npm:publishtest": true, - "_npmjs.org:couch": "https://admin:password@localhost:5984/registry", - "npm-www:nocache": "1", - nodedir: "/Users/isaacs/dev/js/node-v0.8", - "sign-git-tag": true, - message: "v%s", - "strict-ssl": false, - "tmp": process.env.HOME + "/.tmp", - _auth: "dXNlcm5hbWU6cGFzc3dvcmQ=", + email: 'i@izs.me', + 'env-thing': 'asdf', + 'init.author.name': 'Isaac Z. Schlueter', + 'init.author.email': 'i@izs.me', + 'init.author.url': 'http://blog.izs.me/', + 'init.version': '1.2.3', + 'proprietary-attribs': false, + 'npm:publishtest': true, + '_npmjs.org:couch': 'https://admin:password@localhost:5984/registry', + 'npm-www:nocache': '1', + nodedir: '/Users/isaacs/dev/js/node-v0.8', + 'sign-git-tag': true, + message: 'v%s', + 'strict-ssl': false, + 'tmp': process.env.HOME + '/.tmp', + _auth: 'dXNlcm5hbWU6cGFzc3dvcmQ=', _token: - { AuthSession: "yabba-dabba-doodle", - version: "1", - expires: "1345001053415", - path: "/", + { AuthSession: 'yabba-dabba-doodle', + version: '1', + expires: '1345001053415', + path: '/', httponly: true } } // set the userconfig in the env @@ -38,31 +38,30 @@ Object.keys(process.env).forEach(function (k) { }) process.env.npm_config_userconfig = exports.userconfig process.env.npm_config_other_env_thing = 1000 -process.env.random_env_var = "asdf" -process.env.npm_config__underbar_env_thing = "underful" +process.env.random_env_var = 'asdf' +process.env.npm_config__underbar_env_thing = 'underful' process.env.NPM_CONFIG_UPPERCASE_ENV_THING = 42 exports.envData = { userconfig: exports.userconfig, - "_underbar-env-thing": "underful", - "uppercase-env-thing": "42", - "other-env-thing": "1000" + '_underbar-env-thing': 'underful', + 'uppercase-env-thing': '42', + 'other-env-thing': '1000' } exports.envDataFix = { userconfig: exports.userconfig, - "_underbar-env-thing": "underful", - "uppercase-env-thing": 42, - "other-env-thing": 1000 + '_underbar-env-thing': 'underful', + 'uppercase-env-thing': 42, + 'other-env-thing': 1000 } - if (module === require.main) { // set the globalconfig in the userconfig - var fs = require("fs") + var fs = require('fs') var uc = fs.readFileSync(userconfigSrc) - var gcini = "globalconfig = " + exports.globalconfig + "\n" + var gcini = 'globalconfig = ' + exports.globalconfig + '\n' fs.writeFileSync(exports.userconfig, gcini + uc) - console.log("1..1") - console.log("ok 1 setup done") + console.log('1..1') + console.log('ok 1 setup done') } diff --git a/test/tap/00-verify-bundle-deps.js b/test/tap/00-verify-bundle-deps.js index 92818142a..75ea81c59 100644 --- a/test/tap/00-verify-bundle-deps.js +++ b/test/tap/00-verify-bundle-deps.js @@ -1,17 +1,14 @@ -var fs = require("fs") -var path = require("path") -var test = require("tap").test +var test = require('tap').test -var manifest = require("../../package.json") +var manifest = require('../../package.json') var deps = Object.keys(manifest.dependencies) -var dev = Object.keys(manifest.devDependencies) var bundled = manifest.bundleDependencies -test("all deps are bundled deps or dev deps", function (t) { +test('all deps are bundled deps or dev deps', function (t) { deps.forEach(function (name) { t.assert( bundled.indexOf(name) !== -1, - name + " is in bundledDependencies" + name + ' is in bundledDependencies' ) }) diff --git a/test/tap/00-verify-ls-ok.js b/test/tap/00-verify-ls-ok.js index aa6acdbc5..2d20e500b 100644 --- a/test/tap/00-verify-ls-ok.js +++ b/test/tap/00-verify-ls-ok.js @@ -1,18 +1,18 @@ -var common = require("../common-tap") -var test = require("tap").test -var path = require("path") -var cwd = path.resolve(__dirname, "..", "..") -var fs = require("fs") +var common = require('../common-tap') +var test = require('tap').test +var path = require('path') +var cwd = path.resolve(__dirname, '..', '..') +var fs = require('fs') -test("npm ls in npm", function (t) { - t.ok(fs.existsSync(cwd), "ensure that the path we are calling ls within exists") +test('npm ls in npm', function (t) { + t.ok(fs.existsSync(cwd), 'ensure that the path we are calling ls within exists') var files = fs.readdirSync(cwd) - t.notEqual(files.length, 0, "ensure there are files in the directory we are to ls") + t.notEqual(files.length, 0, 'ensure there are files in the directory we are to ls') - var opt = { cwd: cwd, stdio: [ "ignore", "ignore", 2 ] } - common.npm(["ls"], opt, function (err, code) { - t.ifError(err, "error should not exist") - t.equal(code, 0, "npm ls exited with code") + var opt = { cwd: cwd, stdio: [ 'ignore', 'ignore', 2 ] } + common.npm(['ls'], opt, function (err, code) { + t.ifError(err, 'error should not exist') + t.equal(code, 0, 'npm ls exited with code') t.end() }) }) diff --git a/test/tap/404-parent.js b/test/tap/404-parent.js index e3f49f7ba..a8bd95163 100644 --- a/test/tap/404-parent.js +++ b/test/tap/404-parent.js @@ -1,52 +1,52 @@ -var common = require("../common-tap.js") -var test = require("tap").test -var npm = require("../../") -var osenv = require("osenv") -var path = require("path") -var fs = require("fs") -var rimraf = require("rimraf") -var mkdirp = require("mkdirp") -var pkg = path.resolve(__dirname, "404-parent") -var mr = require("npm-registry-mock") +var common = require('../common-tap.js') +var test = require('tap').test +var npm = require('../../') +var osenv = require('osenv') +var path = require('path') +var fs = require('fs') +var rimraf = require('rimraf') +var mkdirp = require('mkdirp') +var pkg = path.resolve(__dirname, '404-parent') +var mr = require('npm-registry-mock') -test("404-parent: if parent exists, specify parent in error message", function (t) { +test('404-parent: if parent exists, specify parent in error message', function (t) { setup() - rimraf.sync(path.resolve(pkg, "node_modules")) + rimraf.sync(path.resolve(pkg, 'node_modules')) performInstall(function (err) { - t.ok(err instanceof Error, "error was returned") - t.ok(err.parent === "404-parent-test", "error's parent set") + t.ok(err instanceof Error, 'error was returned') + t.ok(err.parent === '404-parent-test', "error's parent set") t.end() }) }) -test("cleanup", function (t) { +test('cleanup', function (t) { process.chdir(osenv.tmpdir()) rimraf.sync(pkg) t.end() }) -function setup() { +function setup () { mkdirp.sync(pkg) - mkdirp.sync(path.resolve(pkg, "cache")) - fs.writeFileSync(path.resolve(pkg, "package.json"), JSON.stringify({ - author: "Evan Lucas", - name: "404-parent-test", - version: "0.0.0", - description: "Test for 404-parent", + mkdirp.sync(path.resolve(pkg, 'cache')) + fs.writeFileSync(path.resolve(pkg, 'package.json'), JSON.stringify({ + author: 'Evan Lucas', + name: '404-parent-test', + version: '0.0.0', + description: 'Test for 404-parent', dependencies: { - "test-npm-404-parent-test": "*" + 'test-npm-404-parent-test': '*' } - }), "utf8") + }), 'utf8') process.chdir(pkg) } function plugin (server) { - server.get("/test-npm-404-parent-test") - .reply(404, {"error": "version not found"}) + server.get('/test-npm-404-parent-test') + .reply(404, {'error': 'version not found'}) } function performInstall (cb) { - mr({port : common.port, plugin : plugin}, function (er, s) { // create mock registry. + mr({port: common.port, plugin: plugin}, function (er, s) { // create mock registry. npm.load({registry: common.registry}, function () { var pwd = process.cwd() process.chdir(pkg) diff --git a/test/tap/access.js b/test/tap/access.js index 5ac1d6138..833a874a1 100644 --- a/test/tap/access.js +++ b/test/tap/access.js @@ -1,43 +1,43 @@ -var fs = require("fs") -var path = require("path") -var mkdirp = require("mkdirp") -var rimraf = require("rimraf") -var mr = require("npm-registry-mock") +var fs = require('fs') +var path = require('path') +var mkdirp = require('mkdirp') +var rimraf = require('rimraf') +var mr = require('npm-registry-mock') -var test = require("tap").test -var common = require("../common-tap.js") +var test = require('tap').test +var common = require('../common-tap.js') -var pkg = path.resolve(__dirname, "access") +var pkg = path.resolve(__dirname, 'access') var server var scoped = { - name : "@scoped/pkg", - version : "1.1.1" + name: '@scoped/pkg', + version: '1.1.1' } var body = { - access : "public" + access: 'public' } function mocks (server) { - server.post("/-/package/@scoped%2fpkg/access", JSON.stringify(body)) - .reply(200, { "access" : "public" }) - server.post("/-/package/@scoped%2fanother/access", JSON.stringify(body)) - .reply(200, { "access" : "public" }) + server.post('/-/package/@scoped%2fpkg/access', JSON.stringify(body)) + .reply(200, { 'access': 'public' }) + server.post('/-/package/@scoped%2fanother/access', JSON.stringify(body)) + .reply(200, { 'access': 'public' }) } -test("setup", function (t) { +test('setup', function (t) { mkdirp(pkg, function (er) { - t.ifError(er, pkg + " made successfully") + t.ifError(er, pkg + ' made successfully') - mr({port : common.port, plugin : mocks}, function (err, s) { + mr({port: common.port, plugin: mocks}, function (er, s) { server = s fs.writeFile( - path.join(pkg, "package.json"), + path.join(pkg, 'package.json'), JSON.stringify(scoped), function (er) { - t.ifError(er, "wrote package.json") + t.ifError(er, 'wrote package.json') t.end() } ) @@ -45,52 +45,52 @@ test("setup", function (t) { }) }) -test("npm access on current package", function (t) { +test('npm access on current package', function (t) { common.npm( [ - "access", - "public", - "--registry", common.registry, - "--loglevel", "silent" + 'access', + 'public', + '--registry', common.registry, + '--loglevel', 'silent' ], - { cwd : pkg }, + { cwd: pkg }, function (er, code, stdout, stderr) { - t.ifError(er, "npm access") - t.notOk(code, "exited OK") - t.notOk(stderr, "no error output") + t.ifError(er, 'npm access') + t.notOk(code, 'exited OK') + t.notOk(stderr, 'no error output') t.end() } ) }) -test("npm access on named package", function (t) { +test('npm access on named package', function (t) { common.npm( [ - "access", - "public", "@scoped/another", - "--registry", common.registry, - "--loglevel", "silent" + 'access', + 'public', '@scoped/another', + '--registry', common.registry, + '--loglevel', 'silent' ], - { cwd : pkg }, + { cwd: pkg }, function (er, code, stdout, stderr) { - t.ifError(er, "npm access") - t.notOk(code, "exited OK") - t.notOk(stderr, "no error output") + t.ifError(er, 'npm access') + t.notOk(code, 'exited OK') + t.notOk(stderr, 'no error output') t.end() } ) }) -test("npm change access on unscoped package", function (t) { +test('npm change access on unscoped package', function (t) { common.npm( [ - "access", - "restricted", "yargs", - "--registry", common.registry + 'access', + 'restricted', 'yargs', + '--registry', common.registry ], - { cwd : pkg }, + { cwd: pkg }, function (er, code, stdout, stderr) { t.ok(code, 'exited with Error') t.ok(stderr.match(/you can't change the access level of unscoped packages/)) @@ -102,11 +102,11 @@ test("npm change access on unscoped package", function (t) { test('npm access add', function (t) { common.npm( [ - "access", - "add", "@scoped/another", - "--registry", common.registry + 'access', + 'add', '@scoped/another', + '--registry', common.registry ], - { cwd : pkg }, + { cwd: pkg }, function (er, code, stdout, stderr) { t.ok(code, 'exited with Error') t.ok(stderr.match(/npm access add isn't implemented yet!/)) @@ -118,11 +118,11 @@ test('npm access add', function (t) { test('npm access rm', function (t) { common.npm( [ - "access", - "rm", "@scoped/another", - "--registry", common.registry + 'access', + 'rm', '@scoped/another', + '--registry', common.registry ], - { cwd : pkg }, + { cwd: pkg }, function (er, code, stdout, stderr) { t.ok(code, 'exited with Error') t.ok(stderr.match(/npm access rm isn't implemented yet!/)) @@ -134,11 +134,11 @@ test('npm access rm', function (t) { test('npm access ls', function (t) { common.npm( [ - "access", - "ls", "@scoped/another", - "--registry", common.registry + 'access', + 'ls', '@scoped/another', + '--registry', common.registry ], - { cwd : pkg }, + { cwd: pkg }, function (er, code, stdout, stderr) { t.ok(code, 'exited with Error') t.ok(stderr.match(/npm access ls isn't implemented yet!/)) @@ -150,11 +150,11 @@ test('npm access ls', function (t) { test('npm access edit', function (t) { common.npm( [ - "access", - "edit", "@scoped/another", - "--registry", common.registry + 'access', + 'edit', '@scoped/another', + '--registry', common.registry ], - { cwd : pkg }, + { cwd: pkg }, function (er, code, stdout, stderr) { t.ok(code, 'exited with Error') t.ok(stderr.match(/npm access edit isn't implemented yet!/)) @@ -166,11 +166,11 @@ test('npm access edit', function (t) { test('npm access blerg', function (t) { common.npm( [ - "access", - "blerg", "@scoped/another", - "--registry", common.registry + 'access', + 'blerg', '@scoped/another', + '--registry', common.registry ], - { cwd : pkg }, + { cwd: pkg }, function (er, code, stdout, stderr) { t.ok(code, 'exited with Error') t.ok(stderr.match(/Usage:/)) @@ -179,8 +179,8 @@ test('npm access blerg', function (t) { ) }) -test("cleanup", function (t) { - t.pass("cleaned up") +test('cleanup', function (t) { + t.pass('cleaned up') rimraf.sync(pkg) server.close() t.end() diff --git a/test/tap/add-remote-git-fake-windows.js b/test/tap/add-remote-git-fake-windows.js index c9c9dd446..33b38781a 100644 --- a/test/tap/add-remote-git-fake-windows.js +++ b/test/tap/add-remote-git-fake-windows.js @@ -29,7 +29,6 @@ var pjChild = JSON.stringify({ version: '1.0.3' }, null, 2) + '\n' - test('setup', function (t) { bootstrap() setup(function (er, r) { diff --git a/test/tap/adduser-always-auth.js b/test/tap/adduser-always-auth.js index 6a451b451..3ec819000 100644 --- a/test/tap/adduser-always-auth.js +++ b/test/tap/adduser-always-auth.js @@ -1,142 +1,147 @@ -var fs = require("fs") -var path = require("path") -var rimraf = require("rimraf") -var mr = require("npm-registry-mock") +var fs = require('fs') +var path = require('path') +var rimraf = require('rimraf') +var mr = require('npm-registry-mock') -var test = require("tap").test -var common = require("../common-tap.js") +var test = require('tap').test +var common = require('../common-tap.js') -var opts = {cwd : __dirname} -var outfile = path.resolve(__dirname, "_npmrc") +var opts = {cwd: __dirname} +var outfile = path.resolve(__dirname, '_npmrc') var responses = { - "Username" : "u\n", - "Password" : "p\n", - "Email" : "u@p.me\n" + 'Username': 'u\n', + 'Password': 'p\n', + 'Email': 'u@p.me\n' } -function mocks(server) { +function mocks (server) { server.filteringRequestBody(function (r) { if (r.match(/\"_id\":\"org\.couchdb\.user:u\"/)) { - return "auth" + return 'auth' } }) - server.put("/-/user/org.couchdb.user:u", "auth") - .reply(201, {username : "u", password : "p", email : "u@p.me"}) + server.put('/-/user/org.couchdb.user:u', 'auth') + .reply(201, { username: 'u', password: 'p', email: 'u@p.me' }) } -test("npm login", function (t) { - mr({port : common.port, plugin : mocks}, function (er, s) { +test('npm login', function (t) { + mr({ port: common.port, plugin: mocks }, function (er, s) { var runner = common.npm( [ - "login", - "--registry", common.registry, - "--loglevel", "silent", - "--userconfig", outfile + 'login', + '--registry', common.registry, + '--loglevel', 'silent', + '--userconfig', outfile ], opts, function (err, code) { - t.notOk(code, "exited OK") - t.notOk(err, "no error output") - var config = fs.readFileSync(outfile, "utf8") - t.like(config, /:always-auth=false/, "always-auth is scoped and false (by default)") + t.notOk(code, 'exited OK') + t.notOk(err, 'no error output') + var config = fs.readFileSync(outfile, 'utf8') + t.like(config, /:always-auth=false/, 'always-auth is scoped and false (by default)') s.close() rimraf(outfile, function (err) { - t.ifError(err, "removed config file OK") + t.ifError(err, 'removed config file OK') t.end() }) }) - var o = "", e = "", remaining = Object.keys(responses).length - runner.stdout.on("data", function (chunk) { + var o = '' + var e = '' + var remaining = Object.keys(responses).length + runner.stdout.on('data', function (chunk) { remaining-- o += chunk - var label = chunk.toString("utf8").split(":")[0] + var label = chunk.toString('utf8').split(':')[0] runner.stdin.write(responses[label]) if (remaining === 0) runner.stdin.end() }) - runner.stderr.on("data", function (chunk) { e += chunk }) + runner.stderr.on('data', function (chunk) { e += chunk }) }) }) -test("npm login --always-auth", function (t) { - mr({port : common.port, plugin : mocks}, function (er, s) { +test('npm login --always-auth', function (t) { + mr({ port: common.port, plugin: mocks }, function (er, s) { var runner = common.npm( [ - "login", - "--registry", common.registry, - "--loglevel", "silent", - "--userconfig", outfile, - "--always-auth" + 'login', + '--registry', common.registry, + '--loglevel', 'silent', + '--userconfig', outfile, + '--always-auth' ], opts, function (err, code) { - t.notOk(code, "exited OK") - t.notOk(err, "no error output") - var config = fs.readFileSync(outfile, "utf8") - t.like(config, /:always-auth=true/, "always-auth is scoped and true") + t.notOk(code, 'exited OK') + t.notOk(err, 'no error output') + var config = fs.readFileSync(outfile, 'utf8') + t.like(config, /:always-auth=true/, 'always-auth is scoped and true') s.close() rimraf(outfile, function (err) { - t.ifError(err, "removed config file OK") + t.ifError(err, 'removed config file OK') t.end() }) }) - var o = "", e = "", remaining = Object.keys(responses).length - runner.stdout.on("data", function (chunk) { + var o = '' + var e = '' + var remaining = Object.keys(responses).length + runner.stdout.on('data', function (chunk) { remaining-- o += chunk - var label = chunk.toString("utf8").split(":")[0] + var label = chunk.toString('utf8').split(':')[0] runner.stdin.write(responses[label]) if (remaining === 0) runner.stdin.end() }) - runner.stderr.on("data", function (chunk) { e += chunk }) + runner.stderr.on('data', function (chunk) { e += chunk }) }) }) -test("npm login --no-always-auth", function (t) { - mr({port : common.port, plugin : mocks}, function (er, s) { +test('npm login --no-always-auth', function (t) { + mr({ port: common.port, plugin: mocks }, function (er, s) { var runner = common.npm( [ - "login", - "--registry", common.registry, - "--loglevel", "silent", - "--userconfig", outfile, - "--no-always-auth" + 'login', + '--registry', common.registry, + '--loglevel', 'silent', + '--userconfig', outfile, + '--no-always-auth' ], opts, function (err, code) { - t.notOk(code, "exited OK") - t.notOk(err, "no error output") - var config = fs.readFileSync(outfile, "utf8") - t.like(config, /:always-auth=false/, "always-auth is scoped and false") + t.notOk(code, 'exited OK') + t.notOk(err, 'no error output') + var config = fs.readFileSync(outfile, 'utf8') + t.like(config, /:always-auth=false/, 'always-auth is scoped and false') s.close() rimraf(outfile, function (err) { - t.ifError(err, "removed config file OK") + t.ifError(err, 'removed config file OK') t.end() }) }) - var o = "", e = "", remaining = Object.keys(responses).length - runner.stdout.on("data", function (chunk) { + var o = '' + var e = '' + var remaining = Object.keys(responses).length + runner.stdout.on('data', function (chunk) { remaining-- o += chunk - var label = chunk.toString("utf8").split(":")[0] + var label = chunk.toString('utf8').split(':')[0] runner.stdin.write(responses[label]) if (remaining === 0) runner.stdin.end() }) - runner.stderr.on("data", function (chunk) { e += chunk }) + runner.stderr.on('data', function (chunk) { e += chunk }) }) }) - -test("cleanup", function (t) { +test('cleanup', function (t) { rimraf.sync(outfile) - t.pass("cleaned up") + t.pass('cleaned up') t.end() }) diff --git a/test/tap/adduser-legacy-auth.js b/test/tap/adduser-legacy-auth.js index f9829c618..885a685b9 100644 --- a/test/tap/adduser-legacy-auth.js +++ b/test/tap/adduser-legacy-auth.js @@ -73,7 +73,9 @@ test('npm login', function (t) { }) }) - var o = '', e = '', remaining = Object.keys(responses).length + var o = '' + var e = '' + var remaining = Object.keys(responses).length runner.stdout.on('data', function (chunk) { remaining-- o += chunk diff --git a/test/tap/bin.js b/test/tap/bin.js index ee4e1ff28..55ca894bb 100644 --- a/test/tap/bin.js +++ b/test/tap/bin.js @@ -1,17 +1,17 @@ -var path = require("path") -var test = require("tap").test -var common = require("../common-tap.js") +var path = require('path') +var test = require('tap').test +var common = require('../common-tap.js') var opts = { cwd: __dirname } -var binDir = "../../node_modules/.bin" +var binDir = '../../node_modules/.bin' var fixture = path.resolve(__dirname, binDir) test('npm bin', function (t) { - common.npm(["bin"], opts, function (err, code, stdout, stderr) { - t.ifError(err, "bin ran without issue") - t.notOk(stderr, "should have no stderr") - t.equal(code, 0, "exit ok") + common.npm(['bin'], opts, function (err, code, stdout, stderr) { + t.ifError(err, 'bin ran without issue') + t.notOk(stderr, 'should have no stderr') + t.equal(code, 0, 'exit ok') var res = path.resolve(stdout) - t.equal(res, fixture + "\n") + t.equal(res, fixture + '\n') t.end() }) }) diff --git a/test/tap/bugs.js b/test/tap/bugs.js index 51ba5d3fe..a0a3be1b8 100644 --- a/test/tap/bugs.js +++ b/test/tap/bugs.js @@ -1,151 +1,151 @@ -if (process.platform === "win32") { - console.error("skipping test, because windows and shebangs") - return +if (process.platform === 'win32') { + console.error('skipping test, because windows and shebangs') + process.exit(0) } -var common = require("../common-tap.js") -var mr = require("npm-registry-mock") +var common = require('../common-tap.js') +var mr = require('npm-registry-mock') -var test = require("tap").test -var rimraf = require("rimraf") -var fs = require("fs") -var path = require("path") +var test = require('tap').test +var rimraf = require('rimraf') +var fs = require('fs') +var path = require('path') var join = path.join -var outFile = path.join(__dirname, "/_output") +var outFile = path.join(__dirname, '/_output') var opts = { cwd: __dirname } -test("setup", function (t) { - var s = "#!/usr/bin/env bash\n" + - "echo \"$@\" > " + JSON.stringify(__dirname) + "/_output\n" - fs.writeFileSync(join(__dirname, "/_script.sh"), s, "ascii") - fs.chmodSync(join(__dirname, "/_script.sh"), "0755") - t.pass("made script") +test('setup', function (t) { + var s = '#!/usr/bin/env bash\n' + + 'echo \"$@\" > ' + JSON.stringify(__dirname) + '/_output\n' + fs.writeFileSync(join(__dirname, '/_script.sh'), s, 'ascii') + fs.chmodSync(join(__dirname, '/_script.sh'), '0755') + t.pass('made script') t.end() }) -test("npm bugs underscore", function (t) { - mr({port : common.port}, function (er, s) { +test('npm bugs underscore', function (t) { + mr({ port: common.port }, function (er, s) { common.npm([ - "bugs", "underscore", - "--registry=" + common.registry, - "--loglevel=silent", - "--browser=" + join(__dirname, "/_script.sh") + 'bugs', 'underscore', + '--registry=' + common.registry, + '--loglevel=silent', + '--browser=' + join(__dirname, '/_script.sh') ], opts, function (err, code, stdout, stderr) { - t.ifError(err, "bugs ran without issue") - t.notOk(stderr, "should have no stderr") - t.equal(code, 0, "exit ok") - var res = fs.readFileSync(outFile, "ascii") + t.ifError(err, 'bugs ran without issue') + t.notOk(stderr, 'should have no stderr') + t.equal(code, 0, 'exit ok') + var res = fs.readFileSync(outFile, 'ascii') s.close() - t.equal(res, "https://github.com/jashkenas/underscore/issues\n") + t.equal(res, 'https://github.com/jashkenas/underscore/issues\n') rimraf.sync(outFile) t.end() }) }) }) -test("npm bugs optimist - github (https://)", function (t) { - mr({port : common.port}, function (er, s) { +test('npm bugs optimist - github (https://)', function (t) { + mr({ port: common.port }, function (er, s) { common.npm([ - "bugs", "optimist", - "--registry=" + common.registry, - "--loglevel=silent", - "--browser=" + join(__dirname, "/_script.sh") + 'bugs', 'optimist', + '--registry=' + common.registry, + '--loglevel=silent', + '--browser=' + join(__dirname, '/_script.sh') ], opts, function (err, code, stdout, stderr) { - t.ifError(err, "bugs ran without issue") - t.notOk(stderr, "should have no stderr") - t.equal(code, 0, "exit ok") - var res = fs.readFileSync(outFile, "ascii") + t.ifError(err, 'bugs ran without issue') + t.notOk(stderr, 'should have no stderr') + t.equal(code, 0, 'exit ok') + var res = fs.readFileSync(outFile, 'ascii') s.close() - t.equal(res, "https://github.com/substack/node-optimist/issues\n") + t.equal(res, 'https://github.com/substack/node-optimist/issues\n') rimraf.sync(outFile) t.end() }) }) }) -test("npm bugs npm-test-peer-deps - no repo", function (t) { - mr({port : common.port}, function (er, s) { +test('npm bugs npm-test-peer-deps - no repo', function (t) { + mr({ port: common.port }, function (er, s) { common.npm([ - "bugs", "npm-test-peer-deps", - "--registry=" + common.registry, - "--loglevel=silent", - "--browser=" + join(__dirname, "/_script.sh") + 'bugs', 'npm-test-peer-deps', + '--registry=' + common.registry, + '--loglevel=silent', + '--browser=' + join(__dirname, '/_script.sh') ], opts, function (err, code, stdout, stderr) { - t.ifError(err, "bugs ran without issue") - t.notOk(stderr, "should have no stderr") - t.equal(code, 0, "exit ok") - var res = fs.readFileSync(outFile, "ascii") + t.ifError(err, 'bugs ran without issue') + t.notOk(stderr, 'should have no stderr') + t.equal(code, 0, 'exit ok') + var res = fs.readFileSync(outFile, 'ascii') s.close() - t.equal(res, "https://www.npmjs.org/package/npm-test-peer-deps\n") + t.equal(res, 'https://www.npmjs.org/package/npm-test-peer-deps\n') rimraf.sync(outFile) t.end() }) }) }) -test("npm bugs test-repo-url-http - non-github (http://)", function (t) { - mr({port : common.port}, function (er, s) { +test('npm bugs test-repo-url-http - non-github (http://)', function (t) { + mr({ port: common.port }, function (er, s) { common.npm([ - "bugs", "test-repo-url-http", - "--registry=" + common.registry, - "--loglevel=silent", - "--browser=" + join(__dirname, "/_script.sh") + 'bugs', 'test-repo-url-http', + '--registry=' + common.registry, + '--loglevel=silent', + '--browser=' + join(__dirname, '/_script.sh') ], opts, function (err, code, stdout, stderr) { - t.ifError(err, "bugs ran without issue") - t.notOk(stderr, "should have no stderr") - t.equal(code, 0, "exit ok") - var res = fs.readFileSync(outFile, "ascii") + t.ifError(err, 'bugs ran without issue') + t.notOk(stderr, 'should have no stderr') + t.equal(code, 0, 'exit ok') + var res = fs.readFileSync(outFile, 'ascii') s.close() - t.equal(res, "https://www.npmjs.org/package/test-repo-url-http\n") + t.equal(res, 'https://www.npmjs.org/package/test-repo-url-http\n') rimraf.sync(outFile) t.end() }) }) }) -test("npm bugs test-repo-url-https - non-github (https://)", function (t) { - mr({port : common.port}, function (er, s) { +test('npm bugs test-repo-url-https - non-github (https://)', function (t) { + mr({ port: common.port }, function (er, s) { common.npm([ - "bugs", "test-repo-url-https", - "--registry=" + common.registry, - "--loglevel=silent", - "--browser=" + join(__dirname, "/_script.sh") + 'bugs', 'test-repo-url-https', + '--registry=' + common.registry, + '--loglevel=silent', + '--browser=' + join(__dirname, '/_script.sh') ], opts, function (err, code, stdout, stderr) { - t.ifError(err, "bugs ran without issue") - t.notOk(stderr, "should have no stderr") - t.equal(code, 0, "exit ok") - var res = fs.readFileSync(outFile, "ascii") + t.ifError(err, 'bugs ran without issue') + t.notOk(stderr, 'should have no stderr') + t.equal(code, 0, 'exit ok') + var res = fs.readFileSync(outFile, 'ascii') s.close() - t.equal(res, "https://www.npmjs.org/package/test-repo-url-https\n") + t.equal(res, 'https://www.npmjs.org/package/test-repo-url-https\n') rimraf.sync(outFile) t.end() }) }) }) -test("npm bugs test-repo-url-ssh - non-github (ssh://)", function (t) { - mr({port : common.port}, function (er, s) { +test('npm bugs test-repo-url-ssh - non-github (ssh://)', function (t) { + mr({ port: common.port }, function (er, s) { common.npm([ - "bugs", "test-repo-url-ssh", - "--registry=" + common.registry, - "--loglevel=silent", - "--browser=" + join(__dirname, "/_script.sh") + 'bugs', 'test-repo-url-ssh', + '--registry=' + common.registry, + '--loglevel=silent', + '--browser=' + join(__dirname, '/_script.sh') ], opts, function (err, code, stdout, stderr) { - t.ifError(err, "bugs ran without issue") - t.notOk(stderr, "should have no stderr") - t.equal(code, 0, "exit ok") - var res = fs.readFileSync(outFile, "ascii") + t.ifError(err, 'bugs ran without issue') + t.notOk(stderr, 'should have no stderr') + t.equal(code, 0, 'exit ok') + var res = fs.readFileSync(outFile, 'ascii') s.close() - t.equal(res, "https://www.npmjs.org/package/test-repo-url-ssh\n") + t.equal(res, 'https://www.npmjs.org/package/test-repo-url-ssh\n') rimraf.sync(outFile) t.end() }) }) }) -test("cleanup", function (t) { - fs.unlinkSync(join(__dirname, "/_script.sh")) - t.pass("cleaned up") +test('cleanup', function (t) { + fs.unlinkSync(join(__dirname, '/_script.sh')) + t.pass('cleaned up') t.end() }) diff --git a/test/tap/build-already-built.js b/test/tap/build-already-built.js index 8e5546fe4..45aa1ba1c 100644 --- a/test/tap/build-already-built.js +++ b/test/tap/build-already-built.js @@ -1,64 +1,64 @@ // if "npm rebuild" is run with bundled dependencies, // message "already built" should not be error -var test = require("tap").test -var path = require("path") -var osenv = require("osenv") -var rimraf = require("rimraf") -var npmlog = require("npmlog") -var mkdirp = require("mkdirp") -var requireInject = require("require-inject") +var test = require('tap').test +var path = require('path') +var osenv = require('osenv') +var rimraf = require('rimraf') +var npmlog = require('npmlog') +var mkdirp = require('mkdirp') +var requireInject = require('require-inject') -var npm = require("../../lib/npm.js") +var npm = require('../../lib/npm.js') -var PKG_DIR = path.resolve(__dirname, "build-already-built") -var fakePkg = "foo" +var PKG_DIR = path.resolve(__dirname, 'build-already-built') +var fakePkg = 'foo' -test("setup", function (t) { +test('setup', function (t) { cleanup() t.end() }) test("issue #6735 build 'already built' message", function (t) { - npm.load({loglevel : "warn"}, function () { + npm.load({ loglevel: 'warn' }, function () { // capture log messages with level - var log = "" - npmlog.on("log", function (chunk) { - log += chunk.level + " " + chunk.message + "\n" + var log = '' + npmlog.on('log', function (chunk) { + log += chunk.level + ' ' + chunk.message + '\n' }) mkdirp.sync(fakePkg) var folder = path.resolve(fakePkg) - var global = npm.config.get("global") + var global = npm.config.get('global') - var build = requireInject("../../lib/build", { + var build = requireInject('../../lib/build', { }) - t.test("pin previous behavior", function (t) { + t.test('pin previous behavior', function (t) { build([fakePkg], global, false, false, function (err) { - t.ok(err, "build failed as expected") - t.similar(err.message, /package.json/, "missing package.json as expected") - t.notSimilar(log, /already built/, "no already built message written") + t.ok(err, 'build failed as expected') + t.similar(err.message, /package.json/, 'missing package.json as expected') + t.notSimilar(log, /already built/, 'no already built message written') t.end() }) }) - t.test("simulate rebuild of bundledDependency", function (t) { + t.test('simulate rebuild of bundledDependency', function (t) { - log = "" + log = '' build._didBuild[folder] = true build([fakePkg], global, false, false, function (err) { - t.ok(err, "build failed as expected") - t.similar(err.message, /package.json/, "missing package.json as expected") + t.ok(err, 'build failed as expected') + t.similar(err.message, /package.json/, 'missing package.json as expected') - t.similar(log, /already built/, "already built message written") - t.notSimilar(log, /ERR! already built/, "already built message written is not error") - t.similar(log, /info already built/, "already built message written is info") + t.similar(log, /already built/, 'already built message written') + t.notSimilar(log, /ERR! already built/, 'already built message written is not error') + t.similar(log, /info already built/, 'already built message written is info') t.end() }) @@ -68,8 +68,7 @@ test("issue #6735 build 'already built' message", function (t) { }) }) - -test("cleanup", function (t) { +test('cleanup', function (t) { cleanup() t.end() diff --git a/test/tap/builtin-config.js b/test/tap/builtin-config.js index eb5bb2a16..333282e68 100644 --- a/test/tap/builtin-config.js +++ b/test/tap/builtin-config.js @@ -1,60 +1,58 @@ -var fs = require("fs") +var fs = require('fs') -if (process.argv[2] === "write-builtin") { +if (process.argv[2] === 'write-builtin') { var pid = process.argv[3] - fs.writeFileSync("npmrc", "foo=bar\npid=" + pid + "\n") - return + fs.writeFileSync('npmrc', 'foo=bar\npid=' + pid + '\n') + process.exit(0) } -var rcdata = "foo=bar\npid=" + process.pid + "\n" -var common = require("../common-tap.js") -var path = require("path") -var rimraf = require("rimraf") -var mkdirp = require("mkdirp") -var folder = path.resolve(__dirname, "builtin-config") -var test = require("tap").test -var npm = path.resolve(__dirname, "../..") -var spawn = require("child_process").spawn +var common = require('../common-tap.js') +var path = require('path') +var rimraf = require('rimraf') +var mkdirp = require('mkdirp') +var folder = path.resolve(__dirname, 'builtin-config') +var test = require('tap').test +var npm = path.resolve(__dirname, '../..') +var spawn = require('child_process').spawn var node = process.execPath -test("setup", function (t) { +test('setup', function (t) { t.plan(1) rimraf.sync(folder) - mkdirp.sync(folder + "/first") - mkdirp.sync(folder + "/second") - mkdirp.sync(folder + "/cache") - mkdirp.sync(folder + "/tmp") + mkdirp.sync(folder + '/first') + mkdirp.sync(folder + '/second') + mkdirp.sync(folder + '/cache') + mkdirp.sync(folder + '/tmp') - t.pass("finished setup") + t.pass('finished setup') t.end() }) - -test("install npm into first folder", function (t) { +test('install npm into first folder', function (t) { t.plan(1) - var args = ["install", npm, "-g", - "--prefix=" + folder + "/first", - "--ignore-scripts", - "--cache=" + folder + "/cache", - "--loglevel=silent", - "--tmp=" + folder + "/tmp"] - common.npm(args, {stdio: "inherit"}, function (er, code) { + var args = ['install', npm, '-g', + '--prefix=' + folder + '/first', + '--ignore-scripts', + '--cache=' + folder + '/cache', + '--loglevel=silent', + '--tmp=' + folder + '/tmp'] + common.npm(args, {stdio: 'inherit'}, function (er, code) { if (er) throw er t.equal(code, 0) t.end() }) }) -test("write npmrc file", function (t) { +test('write npmrc file', function (t) { t.plan(1) - common.npm(["explore", "npm", "-g", - "--prefix=" + folder + "/first", - "--cache=" + folder + "/cache", - "--tmp=" + folder + "/tmp", - "--", - node, __filename, "write-builtin", process.pid + common.npm(['explore', 'npm', '-g', + '--prefix=' + folder + '/first', + '--cache=' + folder + '/cache', + '--tmp=' + folder + '/tmp', + '--', + node, __filename, 'write-builtin', process.pid ], - {"stdio": "inherit"}, + {'stdio': 'inherit'}, function (er, code) { if (er) throw er t.equal(code, 0) @@ -62,66 +60,73 @@ test("write npmrc file", function (t) { }) }) -test("use first npm to install second npm", function (t) { +test('use first npm to install second npm', function (t) { t.plan(3) // get the root location - common.npm([ "root", "-g", - "--prefix=" + folder + "/first", - "--cache=" + folder + "/cache", - "--tmp=" + folder + "/tmp", - ], {}, function (er, code, so) { - if (er) throw er - t.equal(code, 0) - var root = so.trim() - t.ok(fs.statSync(root).isDirectory()) + common.npm( + [ + 'root', '-g', + '--prefix=' + folder + '/first', + '--cache=' + folder + '/cache', + '--tmp=' + folder + '/tmp' + ], + {}, + function (er, code, so) { + if (er) throw er + t.equal(code, 0) + var root = so.trim() + t.ok(fs.statSync(root).isDirectory()) - var bin = path.resolve(root, "npm/bin/npm-cli.js") - spawn( node - , [ bin - , "install", npm - , "-g" - , "--prefix=" + folder + "/second" - , "--cache=" + folder + "/cache" - , "--tmp=" + folder + "/tmp" - ]) - .on("error", function (er) { throw er }) - .on("close", function (code) { - t.equal(code, 0, "code is zero") - t.end() - }) - }) + var bin = path.resolve(root, 'npm/bin/npm-cli.js') + spawn( + node, + [ + bin, + 'install', npm, + '-g', + '--prefix=' + folder + '/second', + '--cache=' + folder + '/cache', + '--tmp=' + folder + '/tmp' + ] + ) + .on('error', function (er) { throw er }) + .on('close', function (code) { + t.equal(code, 0, 'code is zero') + t.end() + }) + } + ) }) -test("verify that the builtin config matches", function (t) { +test('verify that the builtin config matches', function (t) { t.plan(3) - common.npm([ "root", "-g", - "--prefix=" + folder + "/first", - "--cache=" + folder + "/cache", - "--tmp=" + folder + "/tmp" + common.npm([ 'root', '-g', + '--prefix=' + folder + '/first', + '--cache=' + folder + '/cache', + '--tmp=' + folder + '/tmp' ], {}, function (er, code, so) { if (er) throw er t.equal(code, 0) var firstRoot = so.trim() - common.npm([ "root", "-g", - "--prefix=" + folder + "/second", - "--cache=" + folder + "/cache", - "--tmp=" + folder + "/tmp" + common.npm([ 'root', '-g', + '--prefix=' + folder + '/second', + '--cache=' + folder + '/cache', + '--tmp=' + folder + '/tmp' ], {}, function (er, code, so) { if (er) throw er t.equal(code, 0) var secondRoot = so.trim() - var firstRc = path.resolve(firstRoot, "npm", "npmrc") - var secondRc = path.resolve(secondRoot, "npm", "npmrc") - var firstData = fs.readFileSync(firstRc, "utf8") - var secondData = fs.readFileSync(secondRc, "utf8") + var firstRc = path.resolve(firstRoot, 'npm', 'npmrc') + var secondRc = path.resolve(secondRoot, 'npm', 'npmrc') + var firstData = fs.readFileSync(firstRc, 'utf8') + var secondData = fs.readFileSync(secondRc, 'utf8') t.equal(firstData, secondData) t.end() }) }) }) - -test("clean", function (t) { +test('clean', function (t) { rimraf.sync(folder) t.end() }) diff --git a/test/tap/cache-add-localdir-fallback.js b/test/tap/cache-add-localdir-fallback.js index facd95c3a..ca8696d22 100644 --- a/test/tap/cache-add-localdir-fallback.js +++ b/test/tap/cache-add-localdir-fallback.js @@ -1,84 +1,84 @@ -var path = require("path") -var test = require("tap").test -var npm = require("../../lib/npm.js") -var requireInject = require("require-inject") +var path = require('path') +var test = require('tap').test +var npm = require('../../lib/npm.js') +var requireInject = require('require-inject') -var realizePackageSpecifier = requireInject("realize-package-specifier", { - "fs": { +var realizePackageSpecifier = requireInject('realize-package-specifier', { + 'fs': { stat: function (file, cb) { process.nextTick(function () { switch (file) { - case path.resolve("named"): - cb(new Error("ENOENT")) + case path.resolve('named'): + cb(new Error('ENOENT')) break - case path.resolve("file.tgz"): + case path.resolve('file.tgz'): cb(null, { isDirectory: function () { return false } }) break - case path.resolve("dir-no-package"): + case path.resolve('dir-no-package'): cb(null, { isDirectory: function () { return true } }) break - case path.resolve("dir-no-package/package.json"): - cb(new Error("ENOENT")) + case path.resolve('dir-no-package/package.json'): + cb(new Error('ENOENT')) break - case path.resolve("dir-with-package"): + case path.resolve('dir-with-package'): cb(null, { isDirectory: function () { return true } }) break - case path.resolve("dir-with-package/package.json"): + case path.resolve('dir-with-package/package.json'): cb(null, {}) break - case path.resolve(__dirname, "dir-with-package"): + case path.resolve(__dirname, 'dir-with-package'): cb(null, { isDirectory: function () { return true } }) break - case path.join(__dirname, "dir-with-package", "package.json"): + case path.join(__dirname, 'dir-with-package', 'package.json'): cb(null, {}) break - case path.resolve(__dirname, "file.tgz"): + case path.resolve(__dirname, 'file.tgz'): cb(null, { isDirectory: function () { return false } }) break default: - throw new Error("Unknown test file passed to stat: " + file) + throw new Error('Unknown test file passed to stat: ' + file) } }) } } }) -npm.load({loglevel : "silent"}, function () { - var cache = requireInject("../../lib/cache.js", { - "realize-package-specifier": realizePackageSpecifier, - "../../lib/cache/add-named.js": function addNamed (name, version, data, cb) { - cb(null, "addNamed") +npm.load({ loglevel: 'silent' }, function () { + var cache = requireInject('../../lib/cache.js', { + 'realize-package-specifier': realizePackageSpecifier, + '../../lib/cache/add-named.js': function addNamed (name, version, data, cb) { + cb(null, 'addNamed') }, - "../../lib/cache/add-local.js": function addLocal (name, data, cb) { - cb(null, "addLocal") + '../../lib/cache/add-local.js': function addLocal (name, data, cb) { + cb(null, 'addLocal') } }) - test("npm install localdir fallback", function (t) { + test('npm install localdir fallback', function (t) { t.plan(12) - cache.add("named", null, null, false, function (er, which) { - t.ifError(er, "named was cached") - t.is(which, "addNamed", "registry package name") + cache.add('named', null, null, false, function (er, which) { + t.ifError(er, 'named was cached') + t.is(which, 'addNamed', 'registry package name') }) - cache.add("file.tgz", null, null, false, function (er, which) { - t.ifError(er, "file.tgz was cached") - t.is(which, "addLocal", "local file") + cache.add('file.tgz', null, null, false, function (er, which) { + t.ifError(er, 'file.tgz was cached') + t.is(which, 'addLocal', 'local file') }) - cache.add("dir-no-package", null, null, false, function (er, which) { - t.ifError(er, "local directory was cached") - t.is(which, "addNamed", "local directory w/o package.json") + cache.add('dir-no-package', null, null, false, function (er, which) { + t.ifError(er, 'local directory was cached') + t.is(which, 'addNamed', 'local directory w/o package.json') }) - cache.add("dir-with-package", null, null, false, function (er, which) { - t.ifError(er, "local directory with package was cached") - t.is(which,"addLocal", "local directory with package.json") + cache.add('dir-with-package', null, null, false, function (er, which) { + t.ifError(er, 'local directory with package was cached') + t.is(which, 'addLocal', 'local directory with package.json') }) - cache.add("file:./dir-with-package", null, __dirname, false, function (er, which) { - t.ifError(er, "local directory (as URI) with package was cached") - t.is(which, "addLocal", "file: URI to local directory with package.json") + cache.add('file:./dir-with-package', null, __dirname, false, function (er, which) { + t.ifError(er, 'local directory (as URI) with package was cached') + t.is(which, 'addLocal', 'file: URI to local directory with package.json') }) - cache.add("file:./file.tgz", null, __dirname, false, function (er, which) { - t.ifError(er, "local file (as URI) with package was cached") - t.is(which, "addLocal", "file: URI to local file with package.json") + cache.add('file:./file.tgz', null, __dirname, false, function (er, which) { + t.ifError(er, 'local file (as URI) with package was cached') + t.is(which, 'addLocal', 'file: URI to local file with package.json') }) }) }) diff --git a/test/tap/cache-add-unpublished.js b/test/tap/cache-add-unpublished.js index fe26929fc..fe6807f19 100644 --- a/test/tap/cache-add-unpublished.js +++ b/test/tap/cache-add-unpublished.js @@ -1,22 +1,21 @@ -var common = require("../common-tap.js") -var test = require("tap").test -var mr = require("npm-registry-mock") +var common = require('../common-tap.js') +var test = require('tap').test -test("cache add", function (t) { +test('cache add', function (t) { setup(function (er, s) { if (er) { throw er } common.npm([ - "cache", - "add", - "superfoo", - "--registry=http://localhost:1337/" + 'cache', + 'add', + 'superfoo', + '--registry=http://localhost:1337/' ], {}, function (er, c, so, se) { if (er) throw er - t.ok(c, "got non-zero exit code") - t.equal(so, "", "nothing printed to stdout") - t.similar(se, /404 Not Found: superfoo/, "got expected error") + t.ok(c, 'got non-zero exit code') + t.equal(so, '', 'nothing printed to stdout') + t.similar(se, /404 Not Found: superfoo/, 'got expected error') s.close() t.end() }) @@ -24,9 +23,9 @@ test("cache add", function (t) { }) function setup (cb) { - var s = require("http").createServer(function (req, res) { + var s = require('http').createServer(function (req, res) { res.statusCode = 404 - res.end("{\"error\":\"not_found\"}\n") + res.end('{\"error\":\"not_found\"}\n') }) s.listen(1337, function () { cb(null, s) diff --git a/test/tap/cache-shasum-fork.js b/test/tap/cache-shasum-fork.js index c87e8c10a..01c2f68fb 100644 --- a/test/tap/cache-shasum-fork.js +++ b/test/tap/cache-shasum-fork.js @@ -18,8 +18,8 @@ var pkg = path.resolve(__dirname, 'cache-shasum-fork') var cache = path.join(pkg, 'cache') var server -var installed_output = path.join(__dirname,"cache-shasum-fork") + - "\n`-- underscore@1.5.1 \n\n" +var installed_output = path.join(__dirname, 'cache-shasum-fork') + + '\n`-- underscore@1.5.1 \n\n' test('setup', function (t) { setup() diff --git a/test/tap/cache-shasum.js b/test/tap/cache-shasum.js index f86037cc8..90915ed85 100644 --- a/test/tap/cache-shasum.js +++ b/test/tap/cache-shasum.js @@ -1,58 +1,57 @@ -var npm = require.resolve("../../") -var test = require("tap").test -var path = require("path") -var rimraf = require("rimraf") -var mkdirp = require("mkdirp") -var mr = require("npm-registry-mock") -var common = require("../common-tap.js") -var cache = path.resolve(__dirname, "cache-shasum") -var spawn = require("child_process").spawn -var sha = require("sha") +var npm = require.resolve('../../') +var test = require('tap').test +var path = require('path') +var rimraf = require('rimraf') +var mkdirp = require('mkdirp') +var mr = require('npm-registry-mock') +var common = require('../common-tap.js') +var cache = path.resolve(__dirname, 'cache-shasum') +var spawn = require('child_process').spawn +var sha = require('sha') var server -test("mock reg", function (t) { +test('mock reg', function (t) { rimraf.sync(cache) mkdirp.sync(cache) - mr({port : common.port}, function (er, s) { + mr({ port: common.port }, function (er, s) { server = s - t.pass("ok") + t.pass('ok') t.end() }) }) -test("npm cache add request", function (t) { +test('npm cache add request', function (t) { var c = spawn(process.execPath, [ - npm, "cache", "add", "request@2.27.0", - "--cache=" + cache, - "--registry=" + common.registry, - "--loglevel=quiet" + npm, 'cache', 'add', 'request@2.27.0', + '--cache=' + cache, + '--registry=' + common.registry, + '--loglevel=quiet' ]) c.stderr.pipe(process.stderr) - c.stdout.on("data", function (d) { - t.fail("Should not get data on stdout: " + d) + c.stdout.on('data', function (d) { + t.fail('Should not get data on stdout: ' + d) }) - c.on("close", function (code) { - t.notOk(code, "exit ok") + c.on('close', function (code) { + t.notOk(code, 'exit ok') t.end() }) }) -test("compare", function (t) { - var d = path.resolve(__dirname, "cache-shasum/request") - var p = path.resolve(d, "2.27.0/package.tgz") - var r = require("./cache-shasum/localhost_1337/request/.cache.json") - var rshasum = r.versions["2.27.0"].dist.shasum +test('compare', function (t) { + var d = path.resolve(__dirname, 'cache-shasum/request') + var p = path.resolve(d, '2.27.0/package.tgz') + var r = require('./cache-shasum/localhost_1337/request/.cache.json') + var rshasum = r.versions['2.27.0'].dist.shasum sha.get(p, function (er, pshasum) { - if (er) - throw er + if (er) throw er t.equal(pshasum, rshasum) t.end() }) }) -test("cleanup", function (t) { +test('cleanup', function (t) { server.close() rimraf.sync(cache) t.end() diff --git a/test/tap/config-basic.js b/test/tap/config-basic.js index d5a950a8e..82fa8ab58 100644 --- a/test/tap/config-basic.js +++ b/test/tap/config-basic.js @@ -1,57 +1,58 @@ -var test = require("tap").test -var npmconf = require("../../lib/config/core.js") -var common = require("./00-config-setup.js") -var path = require("path") +var test = require('tap').test +var npmconf = require('../../lib/config/core.js') +var common = require('./00-config-setup.js') +var path = require('path') var projectData = { - "save-prefix": "~", - "proprietary-attribs": false + 'save-prefix': '~', + 'proprietary-attribs': false } var ucData = common.ucData var envData = common.envData var envDataFix = common.envDataFix -var gcData = { "package-config:foo": "boo" } +var gcData = { 'package-config:foo': 'boo' } var biData = {} -var cli = { foo: "bar", umask: 022 } +var cli = { foo: 'bar', umask: parseInt('022', 8) } -var expectList = -[ cli, +var expectList = [ + cli, envDataFix, projectData, ucData, gcData, - biData ] + biData +] var expectSources = { cli: { data: cli }, env: { data: envDataFix, source: envData, - prefix: "" + prefix: '' }, project: { - path: path.resolve(__dirname, "..", "..", ".npmrc"), - type: "ini", + path: path.resolve(__dirname, '..', '..', '.npmrc'), + type: 'ini', data: projectData }, user: { path: common.userconfig, - type: "ini", + type: 'ini', data: ucData }, global: { path: common.globalconfig, - type: "ini", + type: 'ini', data: gcData }, builtin: { data: biData } } -test("no builtin", function (t) { +test('no builtin', function (t) { npmconf.load(cli, function (er, conf) { if (er) throw er t.same(conf.list, expectList) @@ -59,8 +60,8 @@ test("no builtin", function (t) { t.same(npmconf.rootConf.list, []) t.equal(npmconf.rootConf.root, npmconf.defs.defaults) t.equal(conf.root, npmconf.defs.defaults) - t.equal(conf.get("umask"), 022) - t.equal(conf.get("heading"), "npm") + t.equal(conf.get('umask'), parseInt('022', 8)) + t.equal(conf.get('heading'), 'npm') t.end() }) }) diff --git a/test/tap/config-builtin.js b/test/tap/config-builtin.js index 5a1589ff6..708eb3056 100644 --- a/test/tap/config-builtin.js +++ b/test/tap/config-builtin.js @@ -1,22 +1,22 @@ -var test = require("tap").test -var npmconf = require("../../lib/config/core.js") -var common = require("./00-config-setup.js") -var path = require("path") +var test = require('tap').test +var npmconf = require('../../lib/config/core.js') +var common = require('./00-config-setup.js') +var path = require('path') var ucData = common.ucData var envData = common.envData var envDataFix = common.envDataFix -var gcData = { "package-config:foo": "boo" } +var gcData = { 'package-config:foo': 'boo' } -var biData = { "builtin-config": true } +var biData = { 'builtin-config': true } -var cli = { foo: "bar", heading: "foo", "git-tag-version": false } +var cli = { foo: 'bar', heading: 'foo', 'git-tag-version': false } var projectData = { - "save-prefix": "~", - "proprietary-attribs": false + 'save-prefix': '~', + 'proprietary-attribs': false } var expectList = [ @@ -33,27 +33,27 @@ var expectSources = { env: { data: envDataFix, source: envData, - prefix: "" + prefix: '' }, project: { - path: path.resolve(__dirname, "..", "..", ".npmrc"), - type: "ini", + path: path.resolve(__dirname, '..', '..', '.npmrc'), + type: 'ini', data: projectData }, user: { path: common.userconfig, - type: "ini", + type: 'ini', data: ucData }, global: { path: common.globalconfig, - type: "ini", + type: 'ini', data: gcData }, builtin: { data: biData } } -test("with builtin", function (t) { +test('with builtin', function (t) { npmconf.load(cli, common.builtin, function (er, conf) { if (er) throw er t.same(conf.list, expectList) @@ -61,8 +61,8 @@ test("with builtin", function (t) { t.same(npmconf.rootConf.list, []) t.equal(npmconf.rootConf.root, npmconf.defs.defaults) t.equal(conf.root, npmconf.defs.defaults) - t.equal(conf.get("heading"), "foo") - t.equal(conf.get("git-tag-version"), false) + t.equal(conf.get('heading'), 'foo') + t.equal(conf.get('git-tag-version'), false) t.end() }) }) diff --git a/test/tap/config-certfile.js b/test/tap/config-certfile.js index 25de9963a..223ff3419 100644 --- a/test/tap/config-certfile.js +++ b/test/tap/config-certfile.js @@ -1,18 +1,18 @@ -require("./00-config-setup.js") +require('./00-config-setup.js') -var path = require("path") -var fs = require("fs") -var test = require("tap").test -var npmconf = require("../../lib/config/core.js") +var path = require('path') +var fs = require('fs') +var test = require('tap').test +var npmconf = require('../../lib/config/core.js') -test("cafile loads as ca", function (t) { - var cafile = path.join(__dirname, "..", "fixtures", "config", "multi-ca") +test('cafile loads as ca', function (t) { + var cafile = path.join(__dirname, '..', 'fixtures', 'config', 'multi-ca') npmconf.load({cafile: cafile}, function (er, conf) { if (er) throw er - t.same(conf.get("cafile"), cafile) - t.same(conf.get("ca").join("\n"), fs.readFileSync(cafile, "utf8").trim()) + t.same(conf.get('cafile'), cafile) + t.same(conf.get('ca').join('\n'), fs.readFileSync(cafile, 'utf8').trim()) t.end() }) }) diff --git a/test/tap/config-credentials.js b/test/tap/config-credentials.js index 1cb2a7eb4..c1b981d0a 100644 --- a/test/tap/config-credentials.js +++ b/test/tap/config-credentials.js @@ -1,350 +1,350 @@ -var test = require("tap").test +var test = require('tap').test -var npmconf = require("../../lib/config/core.js") -var common = require("./00-config-setup.js") +var npmconf = require('../../lib/config/core.js') +var common = require('./00-config-setup.js') -var URI = "https://registry.lvh.me:8661/" +var URI = 'https://registry.lvh.me:8661/' -test("getting scope with no credentials set", function (t) { +test('getting scope with no credentials set', function (t) { npmconf.load({}, function (er, conf) { - t.ifError(er, "configuration loaded") + t.ifError(er, 'configuration loaded') var basic = conf.getCredentialsByURI(URI) - t.equal(basic.scope, "//registry.lvh.me:8661/", "nerfed URL extracted") + t.equal(basic.scope, '//registry.lvh.me:8661/', 'nerfed URL extracted') t.end() }) }) -test("trying to set credentials with no URI", function (t) { +test('trying to set credentials with no URI', function (t) { npmconf.load(common.builtin, function (er, conf) { - t.ifError(er, "configuration loaded") + t.ifError(er, 'configuration loaded') t.throws(function () { conf.setCredentialsByURI() - }, "enforced missing URI") + }, 'enforced missing URI') t.end() }) }) -test("trying to clear credentials with no URI", function (t) { +test('trying to clear credentials with no URI', function (t) { npmconf.load(common.builtin, function (er, conf) { - t.ifError(er, "configuration loaded") + t.ifError(er, 'configuration loaded') t.throws(function () { conf.clearCredentialsByURI() - }, "enforced missing URI") + }, 'enforced missing URI') t.end() }) }) -test("set with missing credentials object", function (t) { +test('set with missing credentials object', function (t) { npmconf.load(common.builtin, function (er, conf) { - t.ifError(er, "configuration loaded") + t.ifError(er, 'configuration loaded') t.throws(function () { conf.setCredentialsByURI(URI) - }, "enforced missing credentials") + }, 'enforced missing credentials') t.end() }) }) -test("set with empty credentials object", function (t) { +test('set with empty credentials object', function (t) { npmconf.load(common.builtin, function (er, conf) { - t.ifError(er, "configuration loaded") + t.ifError(er, 'configuration loaded') t.throws(function () { conf.setCredentialsByURI(URI, {}) - }, "enforced missing credentials") + }, 'enforced missing credentials') t.end() }) }) -test("set with token", function (t) { +test('set with token', function (t) { npmconf.load(common.builtin, function (er, conf) { - t.ifError(er, "configuration loaded") + t.ifError(er, 'configuration loaded') t.doesNotThrow(function () { - conf.setCredentialsByURI(URI, {token : "simple-token"}) - }, "needs only token") + conf.setCredentialsByURI(URI, { token: 'simple-token' }) + }, 'needs only token') var expected = { - scope : "//registry.lvh.me:8661/", - token : "simple-token", - username : undefined, - password : undefined, - email : undefined, - auth : undefined, - alwaysAuth : undefined + scope: '//registry.lvh.me:8661/', + token: 'simple-token', + username: undefined, + password: undefined, + email: undefined, + auth: undefined, + alwaysAuth: undefined } - t.same(conf.getCredentialsByURI(URI), expected, "got bearer token and scope") + t.same(conf.getCredentialsByURI(URI), expected, 'got bearer token and scope') t.end() }) }) -test("clear with token", function (t) { +test('clear with token', function (t) { npmconf.load(common.builtin, function (er, conf) { - t.ifError(er, "configuration loaded") + t.ifError(er, 'configuration loaded') t.doesNotThrow(function () { - conf.setCredentialsByURI(URI, {token : "simple-token"}) - }, "needs only token") + conf.setCredentialsByURI(URI, { token: 'simple-token' }) + }, 'needs only token') t.doesNotThrow(function () { conf.clearCredentialsByURI(URI) - }, "needs only URI") + }, 'needs only URI') - t.notOk(conf.getCredentialsByURI(URI).token, "token all gone") + t.notOk(conf.getCredentialsByURI(URI).token, 'token all gone') t.end() }) }) -test("set with missing username", function (t) { +test('set with missing username', function (t) { npmconf.load(common.builtin, function (er, conf) { - t.ifError(er, "configuration loaded") + t.ifError(er, 'configuration loaded') var credentials = { - password : "password", - email : "ogd@aoaioxxysz.net" + password: 'password', + email: 'ogd@aoaioxxysz.net' } t.throws(function () { conf.setCredentialsByURI(URI, credentials) - }, "enforced missing email") + }, 'enforced missing email') t.end() }) }) -test("set with missing password", function (t) { +test('set with missing password', function (t) { npmconf.load(common.builtin, function (er, conf) { - t.ifError(er, "configuration loaded") + t.ifError(er, 'configuration loaded') var credentials = { - username : "username", - email : "ogd@aoaioxxysz.net" + username: 'username', + email: 'ogd@aoaioxxysz.net' } t.throws(function () { conf.setCredentialsByURI(URI, credentials) - }, "enforced missing email") + }, 'enforced missing email') t.end() }) }) -test("set with missing email", function (t) { +test('set with missing email', function (t) { npmconf.load(common.builtin, function (er, conf) { - t.ifError(er, "configuration loaded") + t.ifError(er, 'configuration loaded') var credentials = { - username : "username", - password : "password" + username: 'username', + password: 'password' } t.throws(function () { conf.setCredentialsByURI(URI, credentials) - }, "enforced missing email") + }, 'enforced missing email') t.end() }) }) -test("set with old-style credentials", function (t) { +test('set with old-style credentials', function (t) { npmconf.load(common.builtin, function (er, conf) { - t.ifError(er, "configuration loaded") + t.ifError(er, 'configuration loaded') var credentials = { - username : "username", - password : "password", - email : "ogd@aoaioxxysz.net" + username: 'username', + password: 'password', + email: 'ogd@aoaioxxysz.net' } t.doesNotThrow(function () { conf.setCredentialsByURI(URI, credentials) - }, "requires all of username, password, and email") + }, 'requires all of username, password, and email') var expected = { - scope : "//registry.lvh.me:8661/", - token : undefined, - username : "username", - password : "password", - email : "ogd@aoaioxxysz.net", - auth : "dXNlcm5hbWU6cGFzc3dvcmQ=", - alwaysAuth : false + scope: '//registry.lvh.me:8661/', + token: undefined, + username: 'username', + password: 'password', + email: 'ogd@aoaioxxysz.net', + auth: 'dXNlcm5hbWU6cGFzc3dvcmQ=', + alwaysAuth: false } - t.same(conf.getCredentialsByURI(URI), expected, "got credentials") + t.same(conf.getCredentialsByURI(URI), expected, 'got credentials') t.end() }) }) -test("clear with old-style credentials", function (t) { +test('clear with old-style credentials', function (t) { npmconf.load(common.builtin, function (er, conf) { - t.ifError(er, "configuration loaded") + t.ifError(er, 'configuration loaded') var credentials = { - username : "username", - password : "password", - email : "ogd@aoaioxxysz.net" + username: 'username', + password: 'password', + email: 'ogd@aoaioxxysz.net' } t.doesNotThrow(function () { conf.setCredentialsByURI(URI, credentials) - }, "requires all of username, password, and email") + }, 'requires all of username, password, and email') t.doesNotThrow(function () { conf.clearCredentialsByURI(URI) - }, "clearing only required URI") + }, 'clearing only required URI') - t.notOk(conf.getCredentialsByURI(URI).username, "username cleared") - t.notOk(conf.getCredentialsByURI(URI).password, "password cleared") + t.notOk(conf.getCredentialsByURI(URI).username, 'username cleared') + t.notOk(conf.getCredentialsByURI(URI).password, 'password cleared') t.end() }) }) -test("get old-style credentials for default registry", function (t) { +test('get old-style credentials for default registry', function (t) { npmconf.load(common.builtin, function (er, conf) { - var actual = conf.getCredentialsByURI(conf.get("registry")) + var actual = conf.getCredentialsByURI(conf.get('registry')) var expected = { - scope : "//registry.npmjs.org/", - token : undefined, - password : "password", - username : "username", - email : "i@izs.me", - auth : "dXNlcm5hbWU6cGFzc3dvcmQ=", - alwaysAuth : false + scope: '//registry.npmjs.org/', + token: undefined, + password: 'password', + username: 'username', + email: 'i@izs.me', + auth: 'dXNlcm5hbWU6cGFzc3dvcmQ=', + alwaysAuth: false } t.same(actual, expected) t.end() }) }) -test("set with always-auth enabled", function (t) { +test('set with always-auth enabled', function (t) { npmconf.load(common.builtin, function (er, conf) { - t.ifError(er, "configuration loaded") + t.ifError(er, 'configuration loaded') var credentials = { - username : "username", - password : "password", - email : "ogd@aoaioxxysz.net", - alwaysAuth : true + username: 'username', + password: 'password', + email: 'ogd@aoaioxxysz.net', + alwaysAuth: true } conf.setCredentialsByURI(URI, credentials) var expected = { - scope : "//registry.lvh.me:8661/", - token : undefined, - username : "username", - password : "password", - email : "ogd@aoaioxxysz.net", - auth : "dXNlcm5hbWU6cGFzc3dvcmQ=", - alwaysAuth : true + scope: '//registry.lvh.me:8661/', + token: undefined, + username: 'username', + password: 'password', + email: 'ogd@aoaioxxysz.net', + auth: 'dXNlcm5hbWU6cGFzc3dvcmQ=', + alwaysAuth: true } - t.same(conf.getCredentialsByURI(URI), expected, "got credentials") + t.same(conf.getCredentialsByURI(URI), expected, 'got credentials') t.end() }) }) -test("set with always-auth disabled", function (t) { +test('set with always-auth disabled', function (t) { npmconf.load(common.builtin, function (er, conf) { - t.ifError(er, "configuration loaded") + t.ifError(er, 'configuration loaded') var credentials = { - username : "username", - password : "password", - email : "ogd@aoaioxxysz.net", - alwaysAuth : false + username: 'username', + password: 'password', + email: 'ogd@aoaioxxysz.net', + alwaysAuth: false } conf.setCredentialsByURI(URI, credentials) var expected = { - scope : "//registry.lvh.me:8661/", - token : undefined, - username : "username", - password : "password", - email : "ogd@aoaioxxysz.net", - auth : "dXNlcm5hbWU6cGFzc3dvcmQ=", - alwaysAuth : false + scope: '//registry.lvh.me:8661/', + token: undefined, + username: 'username', + password: 'password', + email: 'ogd@aoaioxxysz.net', + auth: 'dXNlcm5hbWU6cGFzc3dvcmQ=', + alwaysAuth: false } - t.same(conf.getCredentialsByURI(URI), expected, "got credentials") + t.same(conf.getCredentialsByURI(URI), expected, 'got credentials') t.end() }) }) -test("set with global always-auth enabled", function (t) { +test('set with global always-auth enabled', function (t) { npmconf.load(common.builtin, function (er, conf) { - t.ifError(er, "configuration loaded") - var original = conf.get("always-auth") - conf.set("always-auth", true) + t.ifError(er, 'configuration loaded') + var original = conf.get('always-auth') + conf.set('always-auth', true) var credentials = { - username : "username", - password : "password", - email : "ogd@aoaioxxysz.net" + username: 'username', + password: 'password', + email: 'ogd@aoaioxxysz.net' } conf.setCredentialsByURI(URI, credentials) var expected = { - scope : "//registry.lvh.me:8661/", - token : undefined, - username : "username", - password : "password", - email : "ogd@aoaioxxysz.net", - auth : "dXNlcm5hbWU6cGFzc3dvcmQ=", - alwaysAuth : true + scope: '//registry.lvh.me:8661/', + token: undefined, + username: 'username', + password: 'password', + email: 'ogd@aoaioxxysz.net', + auth: 'dXNlcm5hbWU6cGFzc3dvcmQ=', + alwaysAuth: true } - t.same(conf.getCredentialsByURI(URI), expected, "got credentials") + t.same(conf.getCredentialsByURI(URI), expected, 'got credentials') - conf.set("always-auth", original) + conf.set('always-auth', original) t.end() }) }) -test("set with global always-auth disabled", function (t) { +test('set with global always-auth disabled', function (t) { npmconf.load(common.builtin, function (er, conf) { - t.ifError(er, "configuration loaded") - var original = conf.get("always-auth") - conf.set("always-auth", false) + t.ifError(er, 'configuration loaded') + var original = conf.get('always-auth') + conf.set('always-auth', false) var credentials = { - username : "username", - password : "password", - email : "ogd@aoaioxxysz.net" + username: 'username', + password: 'password', + email: 'ogd@aoaioxxysz.net' } conf.setCredentialsByURI(URI, credentials) var expected = { - scope : "//registry.lvh.me:8661/", - token : undefined, - username : "username", - password : "password", - email : "ogd@aoaioxxysz.net", - auth : "dXNlcm5hbWU6cGFzc3dvcmQ=", - alwaysAuth : false + scope: '//registry.lvh.me:8661/', + token: undefined, + username: 'username', + password: 'password', + email: 'ogd@aoaioxxysz.net', + auth: 'dXNlcm5hbWU6cGFzc3dvcmQ=', + alwaysAuth: false } - t.same(conf.getCredentialsByURI(URI), expected, "got credentials") + t.same(conf.getCredentialsByURI(URI), expected, 'got credentials') - conf.set("always-auth", original) + conf.set('always-auth', original) t.end() }) }) diff --git a/test/tap/config-edit.js b/test/tap/config-edit.js index 97a54d2ec..f9e09aba3 100644 --- a/test/tap/config-edit.js +++ b/test/tap/config-edit.js @@ -1,39 +1,39 @@ -var fs = require("fs") -var path = require("path") +var fs = require('fs') +var path = require('path') -var mkdirp = require("mkdirp") -var rimraf = require("rimraf") -var test = require("tap").test -var common = require("../common-tap.js") +var mkdirp = require('mkdirp') +var rimraf = require('rimraf') +var test = require('tap').test +var common = require('../common-tap.js') -var pkg = path.resolve(__dirname, "npm-global-edit") +var pkg = path.resolve(__dirname, 'npm-global-edit') var editorSrc = function () {/* #!/usr/bin/env node -var fs = require("fs") +var fs = require('fs') if (fs.existsSync(process.argv[2])) { - console.log("success") + console.log('success') } else { - console.log("error") + console.log('error') process.exit(1) } -*/}.toString().split("\n").slice(1, -1).join("\n") -var editorPath = path.join(pkg, "editor") +*/}.toString().split('\n').slice(1, -1).join('\n') +var editorPath = path.join(pkg, 'editor') -test("setup", function (t) { +test('setup', function (t) { cleanup(function (er) { - t.ifError(er, "old directory removed") + t.ifError(er, 'old directory removed') - mkdirp(pkg, "0777", function (er) { + mkdirp(pkg, '0777', function (er) { fs.writeFileSync(editorPath, editorSrc) - fs.chmodSync(editorPath, "0777") - t.ifError(er, "created package directory correctly") + fs.chmodSync(editorPath, '0777') + t.ifError(er, 'created package directory correctly') t.end() }) }) }) -test("saving configs", function (t) { +test('saving configs', function (t) { var opts = { cwd: pkg, env: { @@ -43,26 +43,26 @@ test("saving configs", function (t) { } common.npm( [ - "config", - "--prefix", pkg, - "--global", - "edit" + 'config', + '--prefix', pkg, + '--global', + 'edit' ], opts, function (err, code, stdout, stderr) { - t.ifError(err, "command ran without issue") + t.ifError(err, 'command ran without issue') - t.equal(stderr, "", "got nothing on stderr") - t.equal(code, 0, "exit ok") - t.equal(stdout, "success\n", "got success message") + t.equal(stderr, '', 'got nothing on stderr') + t.equal(code, 0, 'exit ok') + t.equal(stdout, 'success\n', 'got success message') t.end() } ) }) -test("cleanup", function (t) { +test('cleanup', function (t) { cleanup(function (er) { - t.ifError(er, "test directory removed OK") + t.ifError(er, 'test directory removed OK') t.end() }) }) diff --git a/test/tap/config-malformed.js b/test/tap/config-malformed.js index 045022146..4f74ea538 100644 --- a/test/tap/config-malformed.js +++ b/test/tap/config-malformed.js @@ -1,7 +1,7 @@ var test = require('tap').test -var npmconf = require("../../lib/config/core.js") -var common = require("./00-config-setup.js") +var npmconf = require('../../lib/config/core.js') +var common = require('./00-config-setup.js') test('with malformed', function (t) { npmconf.load({}, common.malformed, function (er, conf) { diff --git a/test/tap/config-meta.js b/test/tap/config-meta.js index 3da27a872..bb40e2038 100644 --- a/test/tap/config-meta.js +++ b/test/tap/config-meta.js @@ -4,34 +4,34 @@ // b) Documented // c) Defined in the `npmconf` package. -var test = require("tap").test -var fs = require("fs") -var path = require("path") -var root = path.resolve(__dirname, "..", "..") -var lib = path.resolve(root, "lib") -var nm = path.resolve(root, "node_modules") -var doc = path.resolve(root, "doc/misc/npm-config.md") +var test = require('tap').test +var fs = require('fs') +var path = require('path') +var root = path.resolve(__dirname, '..', '..') +var lib = path.resolve(root, 'lib') +var nm = path.resolve(root, 'node_modules') +var doc = path.resolve(root, 'doc/misc/npm-config.md') var FILES = [] var CONFS = {} var DOC = {} var exceptions = [ - path.resolve(lib, "adduser.js"), - path.resolve(lib, "config.js"), - path.resolve(lib, "publish.js"), - path.resolve(lib, "utils", "lifecycle.js"), - path.resolve(lib, "utils", "map-to-registry.js"), - path.resolve(nm, "npm-registry-client", "lib", "publish.js"), - path.resolve(nm, "npm-registry-client", "lib", "request.js") + path.resolve(lib, 'adduser.js'), + path.resolve(lib, 'config.js'), + path.resolve(lib, 'publish.js'), + path.resolve(lib, 'utils', 'lifecycle.js'), + path.resolve(lib, 'utils', 'map-to-registry.js'), + path.resolve(nm, 'npm-registry-client', 'lib', 'publish.js'), + path.resolve(nm, 'npm-registry-client', 'lib', 'request.js') ] -test("get files", function (t) { +test('get files', function (t) { walk(nm) walk(lib) - t.pass("got files") + t.pass('got files') t.end() - function walk(lib) { + function walk (lib) { var files = fs.readdirSync(lib).map(function (f) { return path.resolve(lib, f) }) @@ -41,86 +41,89 @@ test("get files", function (t) { } catch (er) { return } - if (s.isDirectory()) + if (s.isDirectory()) { walk(f) - else if (f.match(/\.js$/)) + } else if (f.match(/\.js$/)) { FILES.push(f) + } }) } }) -test("get lines", function (t) { +test('get lines', function (t) { FILES.forEach(function (f) { - var lines = fs.readFileSync(f, "utf8").split(/\r|\n/) + var lines = fs.readFileSync(f, 'utf8').split(/\r|\n/) lines.forEach(function (l, i) { var matches = l.split(/conf(?:ig)?\.get\(/g) matches.shift() matches.forEach(function (m) { - m = m.split(")").shift() - var literal = m.match(/^['"].+?['"]/) + m = m.split(')').shift() + var literal = m.match(/^[''].+?['']/) if (literal) { m = literal[0].slice(1, -1) - if (!m.match(/^\_/) && m !== "argv") + if (!m.match(/^\_/) && m !== 'argv') { CONFS[m] = { file: f, line: i } + } } else if (exceptions.indexOf(f) === -1) { - t.fail("non-string-literal config used in " + f + ":" + i) + t.fail('non-string-literal config used in ' + f + ':' + i) } }) }) }) - t.pass("got lines") + t.pass('got lines') t.end() }) -test("get docs", function (t) { - var d = fs.readFileSync(doc, "utf8").split(/\r|\n/) - // walk down until the "## Config Settings" section - for (var i = 0; i < d.length && d[i] !== "## Config Settings"; i++); +test('get docs', function (t) { + var d = fs.readFileSync(doc, 'utf8').split(/\r|\n/) + // walk down until the '## Config Settings' section + for (var i = 0; i < d.length && d[i] !== '## Config Settings'; i++); i++ // now gather up all the ^###\s lines until the next ^##\s for (; i < d.length && !d[i].match(/^## /); i++) { - if (d[i].match(/^### /)) - DOC[ d[i].replace(/^### /, "").trim() ] = true + if (d[i].match(/^### /)) { + DOC[ d[i].replace(/^### /, '').trim() ] = true + } } - t.pass("read the docs") + t.pass('read the docs') t.end() }) -test("check configs", function (t) { - var defs = require("../../lib/config/defaults.js") +test('check configs', function (t) { + var defs = require('../../lib/config/defaults.js') var types = Object.keys(defs.types) var defaults = Object.keys(defs.defaults) for (var c1 in CONFS) { if (CONFS[c1].file.indexOf(lib) === 0) { - t.ok(DOC[c1], "should be documented " + c1 + " " - + CONFS[c1].file + ":" + CONFS[c1].line) - t.ok(types.indexOf(c1) !== -1, "should be defined in npmconf " + c1) - t.ok(defaults.indexOf(c1) !== -1, "should have default in npmconf " + c1) + t.ok(DOC[c1], 'should be documented ' + c1 + ' ' + + CONFS[c1].file + ':' + CONFS[c1].line) + t.ok(types.indexOf(c1) !== -1, 'should be defined in npmconf ' + c1) + t.ok(defaults.indexOf(c1) !== -1, 'should have default in npmconf ' + c1) } } for (var c2 in DOC) { - if (c2 !== "versions" && c2 !== "version" && c2 !== "init.version") { - t.ok(CONFS[c2], "config in doc should be used somewhere " + c2) - t.ok(types.indexOf(c2) !== -1, "should be defined in npmconf " + c2) - t.ok(defaults.indexOf(c2) !== -1, "should have default in npmconf " + c2) + if (c2 !== 'versions' && c2 !== 'version' && c2 !== 'init.version') { + t.ok(CONFS[c2], 'config in doc should be used somewhere ' + c2) + t.ok(types.indexOf(c2) !== -1, 'should be defined in npmconf ' + c2) + t.ok(defaults.indexOf(c2) !== -1, 'should have default in npmconf ' + c2) } } types.forEach(function (c) { - if (!c.match(/^\_/) && c !== "argv" && !c.match(/^versions?$/)) { - t.ok(DOC[c], "defined type should be documented " + c) - t.ok(CONFS[c], "defined type should be used " + c) + if (!c.match(/^\_/) && c !== 'argv' && !c.match(/^versions?$/)) { + t.ok(DOC[c], 'defined type should be documented ' + c) + t.ok(CONFS[c], 'defined type should be used ' + c) } }) defaults.forEach(function (c) { - if (!c.match(/^\_/) && c !== "argv" && !c.match(/^versions?$/)) { - t.ok(DOC[c], "defaulted type should be documented " + c) - t.ok(CONFS[c], "defaulted type should be used " + c) + if (!c.match(/^\_/) && c !== 'argv' && !c.match(/^versions?$/)) { + t.ok(DOC[c], 'defaulted type should be documented ' + c) + t.ok(CONFS[c], 'defaulted type should be used ' + c) } }) diff --git a/test/tap/config-private.js b/test/tap/config-private.js index 37e283eec..97c6a73f1 100644 --- a/test/tap/config-private.js +++ b/test/tap/config-private.js @@ -1,81 +1,81 @@ -var fs = require("fs") -var path = require("path") -var test = require("tap").test -var rimraf = require("rimraf") -var mkdirp = require("mkdirp") -var common = require("../common-tap.js") +var fs = require('fs') +var path = require('path') +var test = require('tap').test +var rimraf = require('rimraf') +var mkdirp = require('mkdirp') +var common = require('../common-tap.js') -var pkg = path.resolve(__dirname, "config-private") +var pkg = path.resolve(__dirname, 'config-private') var opts = { cwd: pkg } -test("setup", function (t) { +test('setup', function (t) { rimraf.sync(pkg) mkdirp.sync(pkg) t.end() }) -test("config get private var (old auth)", function (t) { +test('config get private var (old auth)', function (t) { common.npm([ - "config", - "get", - "_auth" + 'config', + 'get', + '_auth' ], opts, function (err, code, stdout, stderr) { t.ifError(err) - t.similar(stderr, /sekretz/, "password blocked on stderr") - t.equal(stdout, "", "no output") + t.similar(stderr, /sekretz/, 'password blocked on stderr') + t.equal(stdout, '', 'no output') t.end() } ) }) -test("config get private var (new auth)", function (t) { +test('config get private var (new auth)', function (t) { common.npm([ - "config", - "get", - "//registry.npmjs.org/:_password" + 'config', + 'get', + '//registry.npmjs.org/:_password' ], opts, function (err, code, stdout, stderr) { t.ifError(err) - t.similar(stderr, /sekretz/, "password blocked on stderr") - t.equal(stdout, "", "no output") + t.similar(stderr, /sekretz/, 'password blocked on stderr') + t.equal(stdout, '', 'no output') t.end() } ) }) -test("config get public var (new username)", function (t) { - var FIXTURE_PATH = path.resolve(pkg, "fixture_npmrc") - var s = "//registry.lvh.me/:username = wombat\n" + - "//registry.lvh.me/:_password = YmFkIHBhc3N3b3Jk\n" + - "//registry.lvh.me/:email = lindsay@wdu.org.au\n" - fs.writeFileSync(FIXTURE_PATH, s, "ascii") - fs.chmodSync(FIXTURE_PATH, "0444") +test('config get public var (new username)', function (t) { + var FIXTURE_PATH = path.resolve(pkg, 'fixture_npmrc') + var s = '//registry.lvh.me/:username = wombat\n' + + '//registry.lvh.me/:_password = YmFkIHBhc3N3b3Jk\n' + + '//registry.lvh.me/:email = lindsay@wdu.org.au\n' + fs.writeFileSync(FIXTURE_PATH, s, 'ascii') + fs.chmodSync(FIXTURE_PATH, '0444') common.npm( [ - "config", - "get", - "//registry.lvh.me/:username", - "--userconfig=" + FIXTURE_PATH, - "--registry=http://registry.lvh.me/" + 'config', + 'get', + '//registry.lvh.me/:username', + '--userconfig=' + FIXTURE_PATH, + '--registry=http://registry.lvh.me/' ], opts, function (err, code, stdout, stderr) { t.ifError(err) - t.equal(stderr, "", "stderr is empty") - t.equal(stdout, "wombat\n", "got usename is output") + t.equal(stderr, '', 'stderr is empty') + t.equal(stdout, 'wombat\n', 'got usename is output') t.end() } ) }) -test("clean", function (t) { +test('clean', function (t) { rimraf.sync(pkg) t.end() }) diff --git a/test/tap/config-project.js b/test/tap/config-project.js index 337355bf2..b9e8b7ac0 100644 --- a/test/tap/config-project.js +++ b/test/tap/config-project.js @@ -1,21 +1,21 @@ -var test = require("tap").test -var path = require("path") -var fix = path.resolve(__dirname, "..", "fixtures", "config") -var projectRc = path.resolve(fix, ".npmrc") -var npmconf = require("../../lib/config/core.js") -var common = require("./00-config-setup.js") +var test = require('tap').test +var path = require('path') +var fix = path.resolve(__dirname, '..', 'fixtures', 'config') +var projectRc = path.resolve(fix, '.npmrc') +var npmconf = require('../../lib/config/core.js') +var common = require('./00-config-setup.js') -var projectData = { just: "testing" } +var projectData = { just: 'testing' } var ucData = common.ucData var envData = common.envData var envDataFix = common.envDataFix -var gcData = { "package-config:foo": "boo" } +var gcData = { 'package-config:foo': 'boo' } var biData = {} -var cli = { foo: "bar", umask: 022, prefix: fix } +var cli = { foo: 'bar', umask: parseInt('022', 8), prefix: fix } var expectList = [ cli, @@ -31,27 +31,27 @@ var expectSources = { env: { data: envDataFix, source: envData, - prefix: "" + prefix: '' }, project: { path: projectRc, - type: "ini", + type: 'ini', data: projectData }, user: { path: common.userconfig, - type: "ini", + type: 'ini', data: ucData }, global: { path: common.globalconfig, - type: "ini", + type: 'ini', data: gcData }, builtin: { data: biData } } -test("no builtin", function (t) { +test('no builtin', function (t) { npmconf.load(cli, function (er, conf) { if (er) throw er t.same(conf.list, expectList) @@ -59,8 +59,8 @@ test("no builtin", function (t) { t.same(npmconf.rootConf.list, []) t.equal(npmconf.rootConf.root, npmconf.defs.defaults) t.equal(conf.root, npmconf.defs.defaults) - t.equal(conf.get("umask"), 022) - t.equal(conf.get("heading"), "npm") + t.equal(conf.get('umask'), parseInt('022', 8)) + t.equal(conf.get('heading'), 'npm') t.end() }) }) diff --git a/test/tap/config-save.js b/test/tap/config-save.js index 88526a38a..903bac7ae 100644 --- a/test/tap/config-save.js +++ b/test/tap/config-save.js @@ -1,88 +1,87 @@ -var fs = require("fs") -var ini = require("ini") -var test = require("tap").test -var npmconf = require("../../lib/config/core.js") -var common = require("./00-config-setup.js") +var fs = require('fs') +var ini = require('ini') +var test = require('tap').test +var npmconf = require('../../lib/config/core.js') +var common = require('./00-config-setup.js') var expectConf = [ - "globalconfig = " + common.globalconfig, - "email = i@izs.me", - "env-thing = asdf", - "init.author.name = Isaac Z. Schlueter", - "init.author.email = i@izs.me", - "init.author.url = http://blog.izs.me/", - "init.version = 1.2.3", - "proprietary-attribs = false", - "npm:publishtest = true", - "_npmjs.org:couch = https://admin:password@localhost:5984/registry", - "npm-www:nocache = 1", - "sign-git-tag = false", - "message = v%s", - "strict-ssl = false", - "_auth = dXNlcm5hbWU6cGFzc3dvcmQ=", - "", - "[_token]", - "AuthSession = yabba-dabba-doodle", - "version = 1", - "expires = 1345001053415", - "path = /", - "httponly = true", - "" -].join("\n") + 'globalconfig = ' + common.globalconfig, + 'email = i@izs.me', + 'env-thing = asdf', + 'init.author.name = Isaac Z. Schlueter', + 'init.author.email = i@izs.me', + 'init.author.url = http://blog.izs.me/', + 'init.version = 1.2.3', + 'proprietary-attribs = false', + 'npm:publishtest = true', + '_npmjs.org:couch = https://admin:password@localhost:5984/registry', + 'npm-www:nocache = 1', + 'sign-git-tag = false', + 'message = v%s', + 'strict-ssl = false', + '_auth = dXNlcm5hbWU6cGFzc3dvcmQ=', + '', + '[_token]', + 'AuthSession = yabba-dabba-doodle', + 'version = 1', + 'expires = 1345001053415', + 'path = /', + 'httponly = true', + '' +].join('\n') var expectFile = [ - "globalconfig = " + common.globalconfig, - "email = i@izs.me", - "env-thing = asdf", - "init.author.name = Isaac Z. Schlueter", - "init.author.email = i@izs.me", - "init.author.url = http://blog.izs.me/", - "init.version = 1.2.3", - "proprietary-attribs = false", - "npm:publishtest = true", - "_npmjs.org:couch = https://admin:password@localhost:5984/registry", - "npm-www:nocache = 1", - "sign-git-tag = false", - "message = v%s", - "strict-ssl = false", - "_auth = dXNlcm5hbWU6cGFzc3dvcmQ=", - "", - "[_token]", - "AuthSession = yabba-dabba-doodle", - "version = 1", - "expires = 1345001053415", - "path = /", - "httponly = true", - "" -].join("\n") + 'globalconfig = ' + common.globalconfig, + 'email = i@izs.me', + 'env-thing = asdf', + 'init.author.name = Isaac Z. Schlueter', + 'init.author.email = i@izs.me', + 'init.author.url = http://blog.izs.me/', + 'init.version = 1.2.3', + 'proprietary-attribs = false', + 'npm:publishtest = true', + '_npmjs.org:couch = https://admin:password@localhost:5984/registry', + 'npm-www:nocache = 1', + 'sign-git-tag = false', + 'message = v%s', + 'strict-ssl = false', + '_auth = dXNlcm5hbWU6cGFzc3dvcmQ=', + '', + '[_token]', + 'AuthSession = yabba-dabba-doodle', + 'version = 1', + 'expires = 1345001053415', + 'path = /', + 'httponly = true', + '' +].join('\n') -test("saving configs", function (t) { +test('saving configs', function (t) { npmconf.load(function (er, conf) { - if (er) - throw er - conf.set("sign-git-tag", false, "user") - conf.del("nodedir") - conf.del("tmp") + if (er) throw er + + conf.set('sign-git-tag', false, 'user') + conf.del('nodedir') + conf.del('tmp') var foundConf = ini.stringify(conf.sources.user.data) t.same(ini.parse(foundConf), ini.parse(expectConf)) fs.unlinkSync(common.userconfig) - conf.save("user", function (er) { - if (er) - throw er - var uc = fs.readFileSync(conf.get("userconfig"), "utf8") + conf.save('user', function (er) { + if (er) throw er + + var uc = fs.readFileSync(conf.get('userconfig'), 'utf8') t.same(ini.parse(uc), ini.parse(expectFile)) t.end() }) }) }) -test("setting prefix", function (t) { +test('setting prefix', function (t) { npmconf.load(function (er, conf) { - if (er) - throw er + if (er) throw er - conf.prefix = "newvalue" - t.same(conf.prefix, "newvalue") + conf.prefix = 'newvalue' + t.same(conf.prefix, 'newvalue') t.end() }) }) diff --git a/test/tap/dedupe-scoped.js b/test/tap/dedupe-scoped.js index 355fc138a..27e27d39d 100644 --- a/test/tap/dedupe-scoped.js +++ b/test/tap/dedupe-scoped.js @@ -60,7 +60,6 @@ var secondUnique = { 'version': '1.2.0' } - test('setup', function (t) { setup() t.end() diff --git a/test/tap/dedupe.js b/test/tap/dedupe.js index c6106f814..4c3424818 100644 --- a/test/tap/dedupe.js +++ b/test/tap/dedupe.js @@ -25,32 +25,31 @@ var json = { } var shrinkwrap = { - name: "dedupe", - version: "0.0.0", + name: 'dedupe', + version: '0.0.0', dependencies: { clean: { - version: "2.1.6", + version: '2.1.6', dependencies: { checker: { - version: "0.5.2", + version: '0.5.2', dependencies: { - async: { version: "0.2.10" } + async: { version: '0.2.10' } } }, - minimist: { version: "0.0.5" } + minimist: { version: '0.0.5' } } }, optimist: { - version: "0.6.0", + version: '0.6.0', dependencies: { - wordwrap: { version: "0.0.2" }, - minimist: { version: "0.0.5" } + wordwrap: { version: '0.0.2' }, + minimist: { version: '0.0.5' } } } } } - test('setup', function (t) { t.comment('test for https://github.com/npm/npm/issues/4675') setup(function () { @@ -78,8 +77,14 @@ test('dedupe finds the common module and moves it up one level', function (t) { t.notOk(code, 'npm dedupe exited with code') t.ok(existsSync(path.join(pkg, 'node_modules', 'minimist')), 'minimist module exists') - t.notOk(existsSync(path.join(pkg, 'node_modules', 'clean','node_modules','minimist')), 'no clean/minimist') - t.notOk(existsSync(path.join(pkg, 'node_modules', 'optimist','node_modules','minimist')), 'no optmist/minimist') + t.notOk( + existsSync(path.join(pkg, 'node_modules', 'clean', 'node_modules', 'minimist')), + 'no clean/minimist' + ) + t.notOk( + existsSync(path.join(pkg, 'node_modules', 'optimist', 'node_modules', 'minimist')), + 'no optmist/minimist' + ) t.end() } ) diff --git a/test/tap/dist-tag.js b/test/tap/dist-tag.js index 08a5ca438..62ecab2c0 100644 --- a/test/tap/dist-tag.js +++ b/test/tap/dist-tag.js @@ -1,62 +1,62 @@ -var fs = require("fs") -var path = require("path") -var mkdirp = require("mkdirp") -var rimraf = require("rimraf") -var mr = require("npm-registry-mock") +var fs = require('fs') +var path = require('path') +var mkdirp = require('mkdirp') +var rimraf = require('rimraf') +var mr = require('npm-registry-mock') -var test = require("tap").test -var common = require("../common-tap.js") +var test = require('tap').test +var common = require('../common-tap.js') -var pkg = path.resolve(__dirname, "dist-tag") +var pkg = path.resolve(__dirname, 'dist-tag') var server var scoped = { - name : "@scoped/pkg", - version : "1.1.1" + name: '@scoped/pkg', + version: '1.1.1' } function mocks (server) { // ls current package - server.get("/-/package/@scoped%2fpkg/dist-tags") - .reply(200, { latest : "1.0.0", a : "0.0.1", b : "0.5.0" }) + server.get('/-/package/@scoped%2fpkg/dist-tags') + .reply(200, { latest: '1.0.0', a: '0.0.1', b: '0.5.0' }) // ls named package - server.get("/-/package/@scoped%2fanother/dist-tags") - .reply(200, { latest : "2.0.0", a : "0.0.2", b : "0.6.0" }) + server.get('/-/package/@scoped%2fanother/dist-tags') + .reply(200, { latest: '2.0.0', a: '0.0.2', b: '0.6.0' }) // add c - server.get("/-/package/@scoped%2fanother/dist-tags") - .reply(200, { latest : "2.0.0", a : "0.0.2", b : "0.6.0" }) - server.put("/-/package/@scoped%2fanother/dist-tags/c", "\"7.7.7\"") - .reply(200, { latest : "7.7.7", a : "0.0.2", b : "0.6.0", c : "7.7.7" }) + server.get('/-/package/@scoped%2fanother/dist-tags') + .reply(200, { latest: '2.0.0', a: '0.0.2', b: '0.6.0' }) + server.put('/-/package/@scoped%2fanother/dist-tags/c', '\"7.7.7\"') + .reply(200, { latest: '7.7.7', a: '0.0.2', b: '0.6.0', c: '7.7.7' }) // set same version - server.get("/-/package/@scoped%2fanother/dist-tags") - .reply(200, { latest : "2.0.0", b : "0.6.0" }) + server.get('/-/package/@scoped%2fanother/dist-tags') + .reply(200, { latest: '2.0.0', b: '0.6.0' }) // rm - server.get("/-/package/@scoped%2fanother/dist-tags") - .reply(200, { latest : "2.0.0", a : "0.0.2", b : "0.6.0", c : "7.7.7" }) - server.delete("/-/package/@scoped%2fanother/dist-tags/c") - .reply(200, { c : "7.7.7" }) + server.get('/-/package/@scoped%2fanother/dist-tags') + .reply(200, { latest: '2.0.0', a: '0.0.2', b: '0.6.0', c: '7.7.7' }) + server.delete('/-/package/@scoped%2fanother/dist-tags/c') + .reply(200, { c: '7.7.7' }) // rm - server.get("/-/package/@scoped%2fanother/dist-tags") - .reply(200, { latest : "4.0.0" }) + server.get('/-/package/@scoped%2fanother/dist-tags') + .reply(200, { latest: '4.0.0' }) } -test("setup", function (t) { +test('setup', function (t) { mkdirp(pkg, function (er) { - t.ifError(er, pkg + " made successfully") + t.ifError(er, pkg + ' made successfully') - mr({port : common.port, plugin : mocks}, function (er, s) { + mr({ port: common.port, plugin: mocks }, function (er, s) { server = s fs.writeFile( - path.join(pkg, "package.json"), + path.join(pkg, 'package.json'), JSON.stringify(scoped), function (er) { - t.ifError(er, "wrote package.json") + t.ifError(er, 'wrote package.json') t.end() } ) @@ -64,131 +64,131 @@ test("setup", function (t) { }) }) -test("npm dist-tags ls in current package", function (t) { +test('npm dist-tags ls in current package', function (t) { common.npm( [ - "dist-tags", "ls", - "--registry", common.registry, - "--loglevel", "silent" + 'dist-tags', 'ls', + '--registry', common.registry, + '--loglevel', 'silent' ], - { cwd : pkg }, + { cwd: pkg }, function (er, code, stdout, stderr) { - t.ifError(er, "npm access") - t.notOk(code, "exited OK") - t.notOk(stderr, "no error output") - t.equal(stdout, "a: 0.0.1\nb: 0.5.0\nlatest: 1.0.0\n") + t.ifError(er, 'npm access') + t.notOk(code, 'exited OK') + t.notOk(stderr, 'no error output') + t.equal(stdout, 'a: 0.0.1\nb: 0.5.0\nlatest: 1.0.0\n') t.end() } ) }) -test("npm dist-tags ls on named package", function (t) { +test('npm dist-tags ls on named package', function (t) { common.npm( [ - "dist-tags", - "ls", "@scoped/another", - "--registry", common.registry, - "--loglevel", "silent" + 'dist-tags', + 'ls', '@scoped/another', + '--registry', common.registry, + '--loglevel', 'silent' ], - { cwd : pkg }, + { cwd: pkg }, function (er, code, stdout, stderr) { - t.ifError(er, "npm access") - t.notOk(code, "exited OK") - t.notOk(stderr, "no error output") - t.equal(stdout, "a: 0.0.2\nb: 0.6.0\nlatest: 2.0.0\n") + t.ifError(er, 'npm access') + t.notOk(code, 'exited OK') + t.notOk(stderr, 'no error output') + t.equal(stdout, 'a: 0.0.2\nb: 0.6.0\nlatest: 2.0.0\n') t.end() } ) }) -test("npm dist-tags add @scoped/another@7.7.7 c", function (t) { +test('npm dist-tags add @scoped/another@7.7.7 c', function (t) { common.npm( [ - "dist-tags", - "add", "@scoped/another@7.7.7", "c", - "--registry", common.registry, - "--loglevel", "silent" + 'dist-tags', + 'add', '@scoped/another@7.7.7', 'c', + '--registry', common.registry, + '--loglevel', 'silent' ], - { cwd : pkg }, + { cwd: pkg }, function (er, code, stdout, stderr) { - t.ifError(er, "npm access") - t.notOk(code, "exited OK") - t.notOk(stderr, "no error output") - t.equal(stdout, "+c: @scoped/another@7.7.7\n") + t.ifError(er, 'npm access') + t.notOk(code, 'exited OK') + t.notOk(stderr, 'no error output') + t.equal(stdout, '+c: @scoped/another@7.7.7\n') t.end() } ) }) -test("npm dist-tags set same version", function (t) { +test('npm dist-tags set same version', function (t) { common.npm( [ - "dist-tag", - "set", "@scoped/another@0.6.0", "b", - "--registry", common.registry, - "--loglevel", "warn" + 'dist-tag', + 'set', '@scoped/another@0.6.0', 'b', + '--registry', common.registry, + '--loglevel', 'warn' ], - { cwd : pkg }, + { cwd: pkg }, function (er, code, stdout, stderr) { - t.ifError(er, "npm access") - t.notOk(code, "exited OK") + t.ifError(er, 'npm access') + t.notOk(code, 'exited OK') t.equal( stderr, - "npm WARN dist-tag add b is already set to version 0.6.0\n", - "warned about setting same version" + 'npm WARN dist-tag add b is already set to version 0.6.0\n', + 'warned about setting same version' ) - t.notOk(stdout, "only expecting warning message") + t.notOk(stdout, 'only expecting warning message') t.end() } ) }) -test("npm dist-tags rm @scoped/another c", function (t) { +test('npm dist-tags rm @scoped/another c', function (t) { common.npm( [ - "dist-tags", - "rm", "@scoped/another", "c", - "--registry", common.registry, - "--loglevel", "silent" + 'dist-tags', + 'rm', '@scoped/another', 'c', + '--registry', common.registry, + '--loglevel', 'silent' ], - { cwd : pkg }, + { cwd: pkg }, function (er, code, stdout, stderr) { - t.ifError(er, "npm access") - t.notOk(code, "exited OK") - t.notOk(stderr, "no error output") - t.equal(stdout, "-c: @scoped/another@7.7.7\n") + t.ifError(er, 'npm access') + t.notOk(code, 'exited OK') + t.notOk(stderr, 'no error output') + t.equal(stdout, '-c: @scoped/another@7.7.7\n') t.end() } ) }) -test("npm dist-tags rm @scoped/another nonexistent", function (t) { +test('npm dist-tags rm @scoped/another nonexistent', function (t) { common.npm( [ - "dist-tags", - "rm", "@scoped/another", "nonexistent", - "--registry", common.registry, - "--loglevel", "silent" + 'dist-tags', + 'rm', '@scoped/another', 'nonexistent', + '--registry', common.registry, + '--loglevel', 'silent' ], - { cwd : pkg }, + { cwd: pkg }, function (er, code, stdout, stderr) { - t.ifError(er, "npm dist-tag") - t.ok(code, "expecting nonzero exit code") - t.notOk(stderr, "no error output") - t.notOk(stdout, "not expecting output") + t.ifError(er, 'npm dist-tag') + t.ok(code, 'expecting nonzero exit code') + t.notOk(stderr, 'no error output') + t.notOk(stdout, 'not expecting output') t.end() } ) }) -test("cleanup", function (t) { - t.pass("cleaned up") +test('cleanup', function (t) { + t.pass('cleaned up') rimraf.sync(pkg) server.close() t.end() diff --git a/test/tap/false-name.js b/test/tap/false-name.js index 89e890e37..1e2a4d43d 100644 --- a/test/tap/false-name.js +++ b/test/tap/false-name.js @@ -54,14 +54,14 @@ test('not every pkg.name can be required', function (t) { function (err, code) { t.ifErr(err, 'install finished without error') t.equal(code, 0, 'install exited ok') - t.ok(existsSync(path.join( - pkg, - 'node_modules','test-package-with-one-dep' - )), 'test-package-with-one-dep installed OK') - t.ok(existsSync(path.join( - pkg, - 'node_modules','test-package' - )), 'test-pacakge subdep installed OK') + t.ok( + existsSync(path.join(pkg, 'node_modules', 'test-package-with-one-dep')), + 'test-package-with-one-dep installed OK' + ) + t.ok( + existsSync(path.join(pkg, 'node_modules', 'test-package')), + 'test-pacakge subdep installed OK' + ) t.end() } ) diff --git a/test/tap/gently-rm-overeager.js b/test/tap/gently-rm-overeager.js index 35f46cc21..c266f1c4d 100644 --- a/test/tap/gently-rm-overeager.js +++ b/test/tap/gently-rm-overeager.js @@ -1,53 +1,50 @@ -var resolve = require("path").resolve -var fs = require("graceful-fs") -var test = require("tap").test -var mkdirp = require("mkdirp") -var rimraf = require("rimraf") +var resolve = require('path').resolve +var fs = require('graceful-fs') +var test = require('tap').test +var mkdirp = require('mkdirp') +var rimraf = require('rimraf') -var common = require("../common-tap.js") +var common = require('../common-tap.js') -var pkg = resolve(__dirname, "gently-rm-overeager") -var dep = resolve(__dirname, "test-whoops") +var pkg = resolve(__dirname, 'gently-rm-overeager') +var dep = resolve(__dirname, 'test-whoops') -var EXEC_OPTS = { - cwd : pkg -} +var EXEC_OPTS = { cwd: pkg } var fixture = { - name: "@test/whoops", - version: "1.0.0", + name: '@test/whoops', + version: '1.0.0', scripts: { - postinstall: "echo \"nope\" && exit 1" + postinstall: 'echo \'nope\' && exit 1' } } -test("setup", function (t) { +test('setup', function (t) { cleanup() setup() t.end() }) -test("cache add", function (t) { - common.npm(["install", "../test-whoops"], EXEC_OPTS, function (er, c) { +test('cache add', function (t) { + common.npm(['install', '../test-whoops'], EXEC_OPTS, function (er, c) { t.ifError(er, "test-whoops install didn't explode") - t.ok(c, "test-whoops install also failed") + t.ok(c, 'test-whoops install also failed') fs.readdir(pkg, function (er, files) { - t.ifError(er, "package directory is still there") - t.deepEqual(files, ["npm-debug.log"], "only debug log remains") + t.ifError(er, 'package directory is still there') + t.deepEqual(files, ['npm-debug.log'], 'only debug log remains') t.end() }) }) }) -test("cleanup", function (t) { +test('cleanup', function (t) { cleanup() t.end() }) - function cleanup () { rimraf.sync(pkg) rimraf.sync(dep) @@ -56,7 +53,7 @@ function cleanup () { function setup () { mkdirp.sync(pkg) // so it doesn't try to install into npm's own node_modules - mkdirp.sync(resolve(pkg, "node_modules")) + mkdirp.sync(resolve(pkg, 'node_modules')) mkdirp.sync(dep) - fs.writeFileSync(resolve(dep, "package.json"), JSON.stringify(fixture)) + fs.writeFileSync(resolve(dep, 'package.json'), JSON.stringify(fixture)) } diff --git a/test/tap/gently-rm-symlink.js b/test/tap/gently-rm-symlink.js index 3a743c894..93ed3edaa 100644 --- a/test/tap/gently-rm-symlink.js +++ b/test/tap/gently-rm-symlink.js @@ -1,73 +1,70 @@ -var resolve = require("path").resolve -var fs = require("graceful-fs") -var test = require("tap").test -var mkdirp = require("mkdirp") -var rimraf = require("rimraf") +var resolve = require('path').resolve +var fs = require('graceful-fs') +var test = require('tap').test +var mkdirp = require('mkdirp') +var rimraf = require('rimraf') -var common = require("../common-tap.js") +var common = require('../common-tap.js') -var pkg = resolve(__dirname, "gently-rm-linked") -var dep = resolve(__dirname, "test-linked") -var glb = resolve(__dirname, "test-global") -var lnk = resolve(__dirname, "test-global-link") - -var EXEC_OPTS = { - cwd : pkg -} +var pkg = resolve(__dirname, 'gently-rm-linked') +var dep = resolve(__dirname, 'test-linked') +var glb = resolve(__dirname, 'test-global') +var lnk = resolve(__dirname, 'test-global-link') +var EXEC_OPTS = { cwd: pkg } var index = "module.exports = function () { console.log('whoop whoop') }" var fixture = { - name: "@test/linked", - version: "1.0.0", + name: '@test/linked', + version: '1.0.0', bin: { - linked: "./index.js" + linked: './index.js' } } -test("setup", function (t) { +test('setup', function (t) { cleanup() setup() t.end() }) -test("install and link", function (t) { +test('install and link', function (t) { common.npm( [ - "--global", - "--prefix", lnk, - "--loglevel", "silent", - "install", "../test-linked" + '--global', + '--prefix', lnk, + '--loglevel', 'silent', + 'install', '../test-linked' ], EXEC_OPTS, function (er, code, stdout, stderr) { t.ifError(er, "test-linked install didn't explode") - t.notOk(code, "test-linked install also failed") - t.notOk(stderr, "no log output") + t.notOk(code, 'test-linked install also failed') + t.notOk(stderr, 'no log output') verify(t, stdout) // again, to make sure unlinking works properlyt common.npm( [ - "--global", - "--prefix", lnk, - "--loglevel", "silent", - "install", "../test-linked" + '--global', + '--prefix', lnk, + '--loglevel', 'silent', + 'install', '../test-linked' ], EXEC_OPTS, function (er, code, stdout, stderr) { t.ifError(er, "test-linked install didn't explode") - t.notOk(code, "test-linked install also failed") - t.notOk(stderr, "no log output") + t.notOk(code, 'test-linked install also failed') + t.notOk(stderr, 'no log output') verify(t, stdout) fs.readdir(pkg, function (er, files) { - t.ifError(er, "package directory is still there") - t.deepEqual(files, ["node_modules"], "only stub modules dir remains") + t.ifError(er, 'package directory is still there') + t.deepEqual(files, ['node_modules'], 'only stub modules dir remains') t.end() }) @@ -77,7 +74,7 @@ test("install and link", function (t) { ) }) -test("cleanup", function (t) { +test('cleanup', function (t) { cleanup() t.end() @@ -88,16 +85,16 @@ function removeBlank (line) { } function verify (t, stdout) { - var binPath = resolve(lnk, "bin", "linked") - var pkgPath = resolve(lnk, "lib", "node_modules", "@test", "linked") - var trgPath = resolve(pkgPath, "index.js") + var binPath = resolve(lnk, 'bin', 'linked') + var pkgPath = resolve(lnk, 'lib', 'node_modules', '@test', 'linked') + var trgPath = resolve(pkgPath, 'index.js') t.deepEqual( stdout.split('\n').filter(removeBlank), - [ binPath+" -> "+trgPath, + [ binPath + ' -> ' + trgPath, resolve(lnk, 'lib'), '└── @test/linked@1.0.0 ' ], - "got expected install output" + 'got expected install output' ) } @@ -113,8 +110,8 @@ function setup () { mkdirp.sync(glb) fs.symlinkSync(glb, lnk) // so it doesn't try to install into npm's own node_modules - mkdirp.sync(resolve(pkg, "node_modules")) + mkdirp.sync(resolve(pkg, 'node_modules')) mkdirp.sync(dep) - fs.writeFileSync(resolve(dep, "package.json"), JSON.stringify(fixture)) - fs.writeFileSync(resolve(dep, "index.js"), index) + fs.writeFileSync(resolve(dep, 'package.json'), JSON.stringify(fixture)) + fs.writeFileSync(resolve(dep, 'index.js'), index) } diff --git a/test/tap/get.js b/test/tap/get.js index 983243025..62bb05fda 100644 --- a/test/tap/get.js +++ b/test/tap/get.js @@ -1,52 +1,50 @@ -var common = require("../common-tap.js") -var test = require("tap").test -var cacheFile = require("npm-cache-filename") -var npm = require("../../") -var mkdirp = require("mkdirp") -var rimraf = require("rimraf") -var path = require("path") -var mr = require("npm-registry-mock") -var fs = require("graceful-fs") +var common = require('../common-tap.js') +var test = require('tap').test +var cacheFile = require('npm-cache-filename') +var npm = require('../../') +var mkdirp = require('mkdirp') +var rimraf = require('rimraf') +var path = require('path') +var mr = require('npm-registry-mock') +var fs = require('graceful-fs') function nop () {} -var URI = "https://npm.registry:8043/rewrite" -var TIMEOUT = 3600 -var FOLLOW = false +var URI = 'https://npm.registry:8043/rewrite' +var TIMEOUT = 3600 +var FOLLOW = false var STALE_OK = true -var TOKEN = "lolbutts" -var AUTH = { - token : TOKEN +var TOKEN = 'lolbutts' +var AUTH = { token: TOKEN } +var PARAMS = { + timeout: TIMEOUT, + follow: FOLLOW, + staleOk: STALE_OK, + auth: AUTH } -var PARAMS = { - timeout : TIMEOUT, - follow : FOLLOW, - staleOk : STALE_OK, - auth : AUTH -} -var PKG_DIR = path.resolve(__dirname, "get-basic") -var CACHE_DIR = path.resolve(PKG_DIR, "cache") +var PKG_DIR = path.resolve(__dirname, 'get-basic') +var CACHE_DIR = path.resolve(PKG_DIR, 'cache') var BIGCO_SAMPLE = { - name : "@bigco/sample", - version : "1.2.3" + name: '@bigco/sample', + version: '1.2.3' } // mock server reference var server var mocks = { - "get": { - "/@bigco%2fsample/1.2.3" : [200, BIGCO_SAMPLE] + 'get': { + '/@bigco%2fsample/1.2.3': [200, BIGCO_SAMPLE] } } var mapper = cacheFile(CACHE_DIR) function getCachePath (uri) { - return path.join(mapper(uri), ".cache.json") + return path.join(mapper(uri), '.cache.json') } -test("setup", function (t) { +test('setup', function (t) { mkdirp.sync(CACHE_DIR) mr({port: common.port, mocks: mocks}, function (er, s) { @@ -59,66 +57,66 @@ test("setup", function (t) { }) }) -test("get call contract", function (t) { +test('get call contract', function (t) { t.throws(function () { npm.registry.get(undefined, PARAMS, nop) - }, "requires a URI") + }, 'requires a URI') t.throws(function () { npm.registry.get([], PARAMS, nop) - }, "requires URI to be a string") + }, 'requires URI to be a string') t.throws(function () { npm.registry.get(URI, undefined, nop) - }, "requires params object") + }, 'requires params object') t.throws(function () { - npm.registry.get(URI, "", nop) - }, "params must be object") + npm.registry.get(URI, '', nop) + }, 'params must be object') t.throws(function () { npm.registry.get(URI, PARAMS, undefined) - }, "requires callback") + }, 'requires callback') t.throws(function () { - npm.registry.get(URI, PARAMS, "callback") - }, "callback must be function") + npm.registry.get(URI, PARAMS, 'callback') + }, 'callback must be function') t.end() }) -test("basic request", function (t) { +test('basic request', function (t) { t.plan(9) - var versioned = common.registry + "/underscore/1.3.3" + var versioned = common.registry + '/underscore/1.3.3' npm.registry.get(versioned, PARAMS, function (er, data) { - t.ifError(er, "loaded specified version underscore data") - t.equal(data.version, "1.3.3") + t.ifError(er, 'loaded specified version underscore data') + t.equal(data.version, '1.3.3') fs.stat(getCachePath(versioned), function (er) { - t.ifError(er, "underscore 1.3.3 cache data written") + t.ifError(er, 'underscore 1.3.3 cache data written') }) }) - var rollup = common.registry + "/underscore" + var rollup = common.registry + '/underscore' npm.registry.get(rollup, PARAMS, function (er, data) { - t.ifError(er, "loaded all metadata") - t.deepEqual(data.name, "underscore") + t.ifError(er, 'loaded all metadata') + t.deepEqual(data.name, 'underscore') fs.stat(getCachePath(rollup), function (er) { - t.ifError(er, "underscore rollup cache data written") + t.ifError(er, 'underscore rollup cache data written') }) }) - var scoped = common.registry + "/@bigco%2fsample/1.2.3" + var scoped = common.registry + '/@bigco%2fsample/1.2.3' npm.registry.get(scoped, PARAMS, function (er, data) { - t.ifError(er, "loaded all metadata") - t.equal(data.name, "@bigco/sample") + t.ifError(er, 'loaded all metadata') + t.equal(data.name, '@bigco/sample') fs.stat(getCachePath(scoped), function (er) { - t.ifError(er, "scoped cache data written") + t.ifError(er, 'scoped cache data written') }) }) }) -test("cleanup", function (t) { +test('cleanup', function (t) { server.close() rimraf.sync(PKG_DIR) diff --git a/test/tap/git-cache-no-hooks.js b/test/tap/git-cache-no-hooks.js index 32731fa1b..e5d862919 100644 --- a/test/tap/git-cache-no-hooks.js +++ b/test/tap/git-cache-no-hooks.js @@ -1,63 +1,63 @@ -var test = require("tap").test - , fs = require("fs") - , path = require("path") - , rimraf = require("rimraf") - , mkdirp = require("mkdirp") - , spawn = require("child_process").spawn - , npmCli = require.resolve("../../bin/npm-cli.js") - , node = process.execPath - , pkg = path.resolve(__dirname, "git-cache-no-hooks") - , tmp = path.join(pkg, "tmp") - , cache = path.join(pkg, "cache") - - -test("setup", function (t) { +var test = require('tap').test +var fs = require('fs') +var path = require('path') +var rimraf = require('rimraf') +var mkdirp = require('mkdirp') +var spawn = require('child_process').spawn +var npmCli = require.resolve('../../bin/npm-cli.js') +var node = process.execPath +var pkg = path.resolve(__dirname, 'git-cache-no-hooks') +var tmp = path.join(pkg, 'tmp') +var cache = path.join(pkg, 'cache') + +test('setup', function (t) { rimraf.sync(pkg) mkdirp.sync(pkg) mkdirp.sync(cache) mkdirp.sync(tmp) - mkdirp.sync(path.resolve(pkg, "node_modules")) + mkdirp.sync(path.resolve(pkg, 'node_modules')) t.end() }) -test("git-cache-no-hooks: install a git dependency", function (t) { +test('git-cache-no-hooks: install a git dependency', function (t) { // disable git integration tests on Travis. if (process.env.TRAVIS) return t.end() - var command = [ npmCli - , "install" - , "git://github.com/nigelzor/npm-4503-a.git" - ] + var command = [ + npmCli, + 'install', + 'git://github.com/nigelzor/npm-4503-a.git' + ] var child = spawn(node, command, { cwd: pkg, env: { - "npm_config_cache" : cache, - "npm_config_tmp" : tmp, - "npm_config_prefix" : pkg, - "npm_config_global" : "false", - "npm_config_umask" : "00", - HOME : process.env.HOME, - Path : process.env.PATH, - PATH : process.env.PATH + 'npm_config_cache': cache, + 'npm_config_tmp': tmp, + 'npm_config_prefix': pkg, + 'npm_config_global': 'false', + 'npm_config_umask': '00', + HOME: process.env.HOME, + Path: process.env.PATH, + PATH: process.env.PATH }, - stdio: "inherit" + stdio: 'inherit' }) - child.on("close", function (code) { - t.equal(code, 0, "npm install should succeed") + child.on('close', function (code) { + t.equal(code, 0, 'npm install should succeed') // verify permissions on git hooks - var repoDir = "git-github-com-nigelzor-npm-4503-a-git-40c5cb24" - var hooksPath = path.join(cache, "_git-remotes", repoDir, "hooks") + var repoDir = 'git-github-com-nigelzor-npm-4503-a-git-40c5cb24' + var hooksPath = path.join(cache, '_git-remotes', repoDir, 'hooks') fs.readdir(hooksPath, function (err) { - t.equal(err && err.code, "ENOENT", "hooks are not brought along with repo") + t.equal(err && err.code, 'ENOENT', 'hooks are not brought along with repo') t.end() }) }) }) -test("cleanup", function (t) { +test('cleanup', function (t) { rimraf.sync(pkg) t.end() }) diff --git a/test/tap/git-dependency-install-link.js b/test/tap/git-dependency-install-link.js index cbb256d98..1eba7ff85 100644 --- a/test/tap/git-dependency-install-link.js +++ b/test/tap/git-dependency-install-link.js @@ -39,7 +39,6 @@ var pjChild = JSON.stringify({ version: '1.0.3' }, null, 2) + '\n' - test('setup', function (t) { bootstrap() setup(function (er, r) { diff --git a/test/tap/git-npmignore.js b/test/tap/git-npmignore.js index 5e915a706..4cd989872 100644 --- a/test/tap/git-npmignore.js +++ b/test/tap/git-npmignore.js @@ -1,62 +1,59 @@ -var cat = require("graceful-fs").writeFileSync -var exec = require("child_process").exec -var readdir = require("graceful-fs").readdirSync -var resolve = require("path").resolve - -var mkdirp = require("mkdirp") -var rimraf = require("rimraf") -var test = require("tap").test -var tmpdir = require("osenv").tmpdir -var which = require("which") - -var common = require("../common-tap.js") - -var pkg = resolve(__dirname, "git-npmignore") -var dep = resolve(pkg, "deps", "gitch") -var packname = "gitch-1.0.0.tgz" +var cat = require('graceful-fs').writeFileSync +var exec = require('child_process').exec +var readdir = require('graceful-fs').readdirSync +var resolve = require('path').resolve + +var mkdirp = require('mkdirp') +var rimraf = require('rimraf') +var test = require('tap').test +var tmpdir = require('osenv').tmpdir +var which = require('which') + +var common = require('../common-tap.js') + +var pkg = resolve(__dirname, 'git-npmignore') +var dep = resolve(pkg, 'deps', 'gitch') +var packname = 'gitch-1.0.0.tgz' var packed = resolve(pkg, packname) -var modules = resolve(pkg, "node_modules") -var installed = resolve(modules, "gitch") +var modules = resolve(pkg, 'node_modules') +var installed = resolve(modules, 'gitch') var expected = [ - "a.js", - "package.json", - ".npmignore" + 'a.js', + 'package.json', + '.npmignore' ].sort() -var EXEC_OPTS = { - cwd : pkg -} +var EXEC_OPTS = { cwd: pkg } -var gitignore = "node_modules/\n" -var npmignore = "t.js\n" +var gitignore = 'node_modules/\n' +var npmignore = 't.js\n' var a = "console.log('hi');" var t = "require('tap').test(function (t) { t.pass('I am a test!'); t.end(); });" var fixture = { - "name" : "gitch", - "version" : "1.0.0", - "private" : true, - "main" : "a.js" + 'name': 'gitch', + 'version': '1.0.0', + 'private': true, + 'main': 'a.js' } - -test("setup", function (t) { +test('setup', function (t) { setup(function (er) { - t.ifError(er, "setup ran OK") + t.ifError(er, 'setup ran OK') t.end() }) }) -test("npm pack directly from directory", function (t) { +test('npm pack directly from directory', function (t) { packInstallTest(dep, t) }) -test("npm pack via git", function (t) { - packInstallTest("git+file://"+dep, t) +test('npm pack via git', function (t) { + packInstallTest('git+file://' + dep, t) }) -test("cleanup", function (t) { +test('cleanup', function (t) { cleanup() t.end() @@ -65,29 +62,29 @@ test("cleanup", function (t) { function packInstallTest (spec, t) { common.npm( [ - "--loglevel", "silent", - "pack", spec + '--loglevel', 'silent', + 'pack', spec ], EXEC_OPTS, function (err, code, stdout, stderr) { - t.ifError(err, "npm pack ran without error") - t.notOk(code, "npm pack exited cleanly") - t.notOk(stderr, "npm pack ran silently") - t.equal(stdout.trim(), packname, "got expected package name") + t.ifError(err, 'npm pack ran without error') + t.notOk(code, 'npm pack exited cleanly') + t.notOk(stderr, 'npm pack ran silently') + t.equal(stdout.trim(), packname, 'got expected package name') common.npm( [ - "--loglevel", "silent", - "install", packed + '--loglevel', 'silent', + 'install', packed ], EXEC_OPTS, function (err, code, stdout, stderr) { - t.ifError(err, "npm install ran without error") - t.notOk(code, "npm install exited cleanly") - t.notOk(stderr, "npm install ran silently") + t.ifError(err, 'npm install ran without error') + t.notOk(code, 'npm install exited cleanly') + t.notOk(stderr, 'npm install ran silently') var actual = readdir(installed).sort() - t.same(actual, expected, "no unexpected files in packed directory") + t.same(actual, expected, 'no unexpected files in packed directory') rimraf(packed, function () { t.end() @@ -111,59 +108,59 @@ function setup (cb) { process.chdir(dep) - cat(resolve(dep, ".npmignore"), npmignore) - cat(resolve(dep, ".gitignore"), gitignore) - cat(resolve(dep, "a.js"), a) - cat(resolve(dep, "t.js"), t) - cat(resolve(dep, "package.json"), JSON.stringify(fixture)) + cat(resolve(dep, '.npmignore'), npmignore) + cat(resolve(dep, '.gitignore'), gitignore) + cat(resolve(dep, 'a.js'), a) + cat(resolve(dep, 't.js'), t) + cat(resolve(dep, 'package.json'), JSON.stringify(fixture)) common.npm( [ - "--loglevel", "silent", - "cache", "clean" + '--loglevel', 'silent', + 'cache', 'clean' ], EXEC_OPTS, function (er, code, _, stderr) { if (er) return cb(er) - if (code) return cb(new Error("npm cache nonzero exit: "+code)) - if (stderr) return cb(new Error("npm cache clean error: "+stderr)) + if (code) return cb(new Error('npm cache nonzero exit: ' + code)) + if (stderr) return cb(new Error('npm cache clean error: ' + stderr)) - which("git", function found (er, git) { + which('git', function found (er, git) { if (er) return cb(er) - exec(git+" init", init) + exec(git + ' init', init) function init (er, _, stderr) { if (er) return cb(er) - if (stderr) return cb(new Error("git init error: "+stderr)) + if (stderr) return cb(new Error('git init error: ' + stderr)) - exec(git+" config user.name 'Phantom Faker'", user) + exec(git + " config user.name 'Phantom Faker'", user) } function user (er, _, stderr) { if (er) return cb(er) - if (stderr) return cb(new Error("git config error: "+stderr)) + if (stderr) return cb(new Error('git config error: ' + stderr)) - exec(git+" config user.email nope@not.real", email) + exec(git + ' config user.email nope@not.real', email) } function email (er, _, stderr) { if (er) return cb(er) - if (stderr) return cb(new Error("git config error: "+stderr)) + if (stderr) return cb(new Error('git config error: ' + stderr)) - exec(git+" add .", addAll) + exec(git + ' add .', addAll) } function addAll (er, _, stderr) { if (er) return cb(er) - if (stderr) return cb(new Error("git add . error: "+stderr)) + if (stderr) return cb(new Error('git add . error: ' + stderr)) - exec(git+" commit -m boot", commit) + exec(git + ' commit -m boot', commit) } function commit (er, _, stderr) { if (er) return cb(er) - if (stderr) return cb(new Error("git commit error: "+stderr)) + if (stderr) return cb(new Error('git commit error: ' + stderr)) cb() } diff --git a/test/tap/global-prefix-set-in-userconfig.js b/test/tap/global-prefix-set-in-userconfig.js index f820a2772..422bcb247 100644 --- a/test/tap/global-prefix-set-in-userconfig.js +++ b/test/tap/global-prefix-set-in-userconfig.js @@ -1,36 +1,36 @@ -var common = require("../common-tap.js") -var test = require("tap").test -var rimraf = require("rimraf") -var prefix = __filename.replace(/\.js$/, "") -var rcfile = __filename.replace(/\.js$/, ".npmrc") -var fs = require("fs") -var conf = "prefix = " + prefix + "\n" +var common = require('../common-tap.js') +var test = require('tap').test +var rimraf = require('rimraf') +var prefix = __filename.replace(/\.js$/, '') +var rcfile = __filename.replace(/\.js$/, '.npmrc') +var fs = require('fs') +var conf = 'prefix = ' + prefix + '\n' -test("setup", function (t) { +test('setup', function (t) { rimraf.sync(prefix) fs.writeFileSync(rcfile, conf) - t.pass("ready") + t.pass('ready') t.end() }) -test("run command", function (t) { - var args = ["prefix", "-g", "--userconfig=" + rcfile] +test('run command', function (t) { + var args = ['prefix', '-g', '--userconfig=' + rcfile] common.npm(args, {env: {}}, function (er, code, so) { if (er) throw er - t.notOk(code, "npm prefix exited with code 0") + t.notOk(code, 'npm prefix exited with code 0') t.equal(so.trim(), prefix) t.end() }) }) -test("made dir", function (t) { +test('made dir', function (t) { t.ok(fs.statSync(prefix).isDirectory()) t.end() }) -test("cleanup", function (t) { +test('cleanup', function (t) { rimraf.sync(prefix) rimraf.sync(rcfile) - t.pass("clean") + t.pass('clean') t.end() }) diff --git a/test/tap/graceful-restart.js b/test/tap/graceful-restart.js index 532647480..21da0d990 100644 --- a/test/tap/graceful-restart.js +++ b/test/tap/graceful-restart.js @@ -107,8 +107,9 @@ function createChild (args, cb) { 'npm_config_loglevel': 'silent' } - if (process.platform === 'win32') + if (process.platform === 'win32') { env.npm_config_cache = '%APPDATA%\\npm-cache' + } return common.npm(args, { cwd: pkg, diff --git a/test/tap/ignore-install-link.js b/test/tap/ignore-install-link.js index 45db51d30..684c6a05b 100644 --- a/test/tap/ignore-install-link.js +++ b/test/tap/ignore-install-link.js @@ -1,68 +1,73 @@ -if (process.platform === "win32") { - console.log("ok - symlinks are weird on windows, skip this test") - return +if (process.platform === 'win32') { + console.log('ok - symlinks are weird on windows, skip this test') + process.exit(0) } -var common = require("../common-tap.js") -var test = require("tap").test -var path = require("path") -var fs = require("fs") -var rimraf = require("rimraf") -var mkdirp = require("mkdirp") +var common = require('../common-tap.js') +var test = require('tap').test +var path = require('path') +var fs = require('fs') +var rimraf = require('rimraf') +var mkdirp = require('mkdirp') -var root = path.resolve(__dirname, "ignore-install-link") -var pkg = path.resolve(root, "pkg") -var dep = path.resolve(root, "dep") -var target = path.resolve(pkg, "node_modules", "dep") -var cache = path.resolve(root, "cache") -var globalPath = path.resolve(root, "global") +var root = path.resolve(__dirname, 'ignore-install-link') +var pkg = path.resolve(root, 'pkg') +var dep = path.resolve(root, 'dep') +var target = path.resolve(pkg, 'node_modules', 'dep') +var cache = path.resolve(root, 'cache') +var globalPath = path.resolve(root, 'global') -var pkgj = { "name":"pkg", "version": "1.2.3" - , "dependencies": { "dep": "1.2.3" } } -var depj = { "name": "dep", "version": "1.2.3" } +var pkgj = { + 'name': 'pkg', + 'version': '1.2.3', + 'dependencies': { + 'dep': '1.2.3' + } +} +var depj = { 'name': 'dep', 'version': '1.2.3' } -var myreg = require("http").createServer(function (q, s) { +var myreg = require('http').createServer(function (q, s) { s.statusCode = 403 - s.end(JSON.stringify({"error":"forbidden"}) + "\n") + s.end(JSON.stringify({'error': 'forbidden'}) + '\n') }).listen(common.port) -test("setup", function (t) { +test('setup', function (t) { rimraf.sync(root) mkdirp.sync(root) - mkdirp.sync(path.resolve(pkg, "node_modules")) + mkdirp.sync(path.resolve(pkg, 'node_modules')) mkdirp.sync(dep) mkdirp.sync(cache) mkdirp.sync(globalPath) - fs.writeFileSync(path.resolve(pkg, "package.json"), JSON.stringify(pkgj)) - fs.writeFileSync(path.resolve(dep, "package.json"), JSON.stringify(depj)) - fs.symlinkSync(dep, target, "dir") + fs.writeFileSync(path.resolve(pkg, 'package.json'), JSON.stringify(pkgj)) + fs.writeFileSync(path.resolve(dep, 'package.json'), JSON.stringify(depj)) + fs.symlinkSync(dep, target, 'dir') t.end() }) -test("ignore install if package is linked", function (t) { - common.npm(["install"], { +test('ignore install if package is linked', function (t) { + common.npm(['install'], { cwd: pkg, env: { PATH: process.env.PATH || process.env.Path, HOME: process.env.HOME, - "npm_config_prefix": globalPath, - "npm_config_cache": cache, - "npm_config_registry": common.registry, - "npm_config_loglevel": "silent" + 'npm_config_prefix': globalPath, + 'npm_config_cache': cache, + 'npm_config_registry': common.registry, + 'npm_config_loglevel': 'silent' }, - stdio: "inherit" + stdio: 'inherit' }, function (er, code) { if (er) throw er - t.equal(code, 0, "npm install exited with code") + t.equal(code, 0, 'npm install exited with code') t.end() }) }) -test("still a symlink", function (t) { +test('still a symlink', function (t) { t.equal(true, fs.lstatSync(target).isSymbolicLink()) t.end() }) -test("cleanup", function (t) { +test('cleanup', function (t) { rimraf.sync(root) myreg.close() t.end() diff --git a/test/tap/init-interrupt.js b/test/tap/init-interrupt.js index 962ab7244..2e85a5d1b 100644 --- a/test/tap/init-interrupt.js +++ b/test/tap/init-interrupt.js @@ -1,52 +1,52 @@ -// if "npm init" is interrupted with ^C, don't report -// "init written successfully" -var test = require("tap").test -var path = require("path") -var osenv = require("osenv") -var rimraf = require("rimraf") -var npmlog = require("npmlog") -var requireInject = require("require-inject") +// if 'npm init' is interrupted with ^C, don't report +// 'init written successfully' +var test = require('tap').test +var path = require('path') +var osenv = require('osenv') +var rimraf = require('rimraf') +var npmlog = require('npmlog') +var requireInject = require('require-inject') -var npm = require("../../lib/npm.js") +var npm = require('../../lib/npm.js') -var PKG_DIR = path.resolve(__dirname, "init-interrupt") +var PKG_DIR = path.resolve(__dirname, 'init-interrupt') -test("setup", function (t) { +test('setup', function (t) { cleanup() t.end() }) -test("issue #6684 remove confusing message", function (t) { +test('issue #6684 remove confusing message', function (t) { var initJsonMock = function (dir, input, config, cb) { process.nextTick(function () { - cb({message : "canceled"}) + cb({ message: 'canceled' }) }) } initJsonMock.yes = function () { return true } - npm.load({loglevel : "silent"}, function () { - var log = "" - var init = requireInject("../../lib/init", { - "init-package-json": initJsonMock + npm.load({ loglevel: 'silent' }, function () { + var log = '' + var init = requireInject('../../lib/init', { + 'init-package-json': initJsonMock }) // capture log messages - npmlog.on("log", function (chunk) { log += chunk.message + "\n" } ) + npmlog.on('log', function (chunk) { log += chunk.message + '\n' }) init([], function (err, code) { - t.ifError(err, "init ran successfully") - t.notOk(code, "exited without issue") - t.notSimilar(log, /written successfully/, "no success message written") - t.similar(log, /canceled/, "alerted that init was canceled") + t.ifError(err, 'init ran successfully') + t.notOk(code, 'exited without issue') + t.notSimilar(log, /written successfully/, 'no success message written') + t.similar(log, /canceled/, 'alerted that init was canceled') t.end() }) }) }) -test("cleanup", function (t) { +test('cleanup', function (t) { cleanup() t.end() diff --git a/test/tap/install-bad-man.js b/test/tap/install-bad-man.js index 9ec8a8473..756b4a590 100644 --- a/test/tap/install-bad-man.js +++ b/test/tap/install-bad-man.js @@ -1,53 +1,52 @@ -var fs = require("fs") -var resolve = require("path").resolve +var fs = require('fs') +var resolve = require('path').resolve -var osenv = require("osenv") -var mkdirp = require("mkdirp") -var rimraf = require("rimraf") -var test = require("tap").test +var osenv = require('osenv') +var mkdirp = require('mkdirp') +var rimraf = require('rimraf') +var test = require('tap').test -var common = require("../common-tap.js") +var common = require('../common-tap.js') -var pkg = resolve(__dirname, "install-bad-man") -var target = resolve(__dirname, "install-bad-man-target") +var pkg = resolve(__dirname, 'install-bad-man') +var target = resolve(__dirname, 'install-bad-man-target') var EXEC_OPTS = { cwd: target } var json = { - name : "install-bad-man", - version : "1.2.3", - man : [ "./install-bad-man.1.lol" ] + name: 'install-bad-man', + version: '1.2.3', + man: [ './install-bad-man.1.lol' ] } - -test("setup", function (t) { +test('setup', function (t) { setup() - t.pass("setup ran") + t.pass('setup ran') t.end() }) test("install from repo on 'OS X'", function (t) { common.npm( [ - "install", - "--prefix", target, - "--global", + 'install', + '--prefix', target, + '--global', pkg ], EXEC_OPTS, function (err, code, stdout, stderr) { - t.ifError(err, "npm command ran from test") - t.equals(code, 1, "install exited with failure (1)") - t.notOk(stdout, "no output indicating success") + t.ifError(err, 'npm command ran from test') + t.equals(code, 1, 'install exited with failure (1)') + t.notOk(stdout, 'no output indicating success') t.notOk( stderr.match(/Cannot read property '1' of null/), - "no longer has cryptic error output" + 'no longer has cryptic error output' ) t.ok( stderr.match(/install-bad-man\.1\.lol is not a valid name/), - "got expected error output" + 'got expected error output' ) t.end() @@ -55,9 +54,9 @@ test("install from repo on 'OS X'", function (t) { ) }) -test("clean", function (t) { +test('clean', function (t) { cleanup() - t.pass("cleaned up") + t.pass('cleaned up') t.end() }) @@ -65,12 +64,12 @@ function setup () { cleanup() mkdirp.sync(pkg) // make sure it installs locally - mkdirp.sync(resolve(target, "node_modules")) + mkdirp.sync(resolve(target, 'node_modules')) fs.writeFileSync( - resolve(pkg, "package.json"), - JSON.stringify(json, null, 2)+"\n" + resolve(pkg, 'package.json'), + JSON.stringify(json, null, 2) + '\n' ) - fs.writeFileSync(resolve(pkg, "install-bad-man.1.lol"), "lol\n") + fs.writeFileSync(resolve(pkg, 'install-bad-man.1.lol'), 'lol\n') } function cleanup () { diff --git a/test/tap/install-man.js b/test/tap/install-man.js index ebba5d87b..d309788b2 100644 --- a/test/tap/install-man.js +++ b/test/tap/install-man.js @@ -1,48 +1,48 @@ -var fs = require("fs") -var resolve = require("path").resolve +var fs = require('fs') +var resolve = require('path').resolve -var osenv = require("osenv") -var mkdirp = require("mkdirp") -var rimraf = require("rimraf") -var test = require("tap").test +var osenv = require('osenv') +var mkdirp = require('mkdirp') +var rimraf = require('rimraf') +var test = require('tap').test -var common = require("../common-tap.js") +var common = require('../common-tap.js') -var pkg = resolve(__dirname, "install-man") -var target = resolve(__dirname, "install-man-target") +var pkg = resolve(__dirname, 'install-man') +var target = resolve(__dirname, 'install-man-target') var EXEC_OPTS = { cwd: target } var json = { - name : "install-man", - version : "1.2.3", - man : [ "./install-man.1" ] + name: 'install-man', + version: '1.2.3', + man: [ './install-man.1' ] } -test("setup", function (t) { +test('setup', function (t) { setup() - t.pass("setup ran") + t.pass('setup ran') t.end() }) -test("install man page", function (t) { +test('install man page', function (t) { common.npm( [ - "install", - "--prefix", target, - "--global", + 'install', + '--prefix', target, + '--global', pkg ], EXEC_OPTS, function (err, code, stdout, stderr) { - t.ifError(err, "npm command ran from test") - t.equals(code, 0, "install exited with success (0)") - t.ok(stdout, "output indicating success") + t.ifError(err, 'npm command ran from test') + t.equals(code, 0, 'install exited with success (0)') + t.ok(stdout, 'output indicating success') t.ok( - fs.existsSync(resolve(target, "share", "man", "man1", "install-man.1")), - "man page link was created" + fs.existsSync(resolve(target, 'share', 'man', 'man1', 'install-man.1')), + 'man page link was created' ) t.end() @@ -50,9 +50,9 @@ test("install man page", function (t) { ) }) -test("clean", function (t) { +test('clean', function (t) { cleanup() - t.pass("cleaned up") + t.pass('cleaned up') t.end() }) @@ -60,12 +60,12 @@ function setup () { cleanup() mkdirp.sync(pkg) // make sure it installs locally - mkdirp.sync(resolve(target, "node_modules")) + mkdirp.sync(resolve(target, 'node_modules')) fs.writeFileSync( - resolve(pkg, "package.json"), - JSON.stringify(json, null, 2)+"\n" + resolve(pkg, 'package.json'), + JSON.stringify(json, null, 2) + '\n' ) - fs.writeFileSync(resolve(pkg, "install-man.1"), "THIS IS A MANPAGE\n") + fs.writeFileSync(resolve(pkg, 'install-man.1'), 'THIS IS A MANPAGE\n') } function cleanup () { diff --git a/test/tap/install-scoped-already-installed.js b/test/tap/install-scoped-already-installed.js index 412d06940..f3c191ddb 100644 --- a/test/tap/install-scoped-already-installed.js +++ b/test/tap/install-scoped-already-installed.js @@ -125,7 +125,7 @@ test('cleanup', function (t) { }) function contains (list, element) { - var matcher = new RegExp(element+'$') + var matcher = new RegExp(element + '$') for (var i = 0; i < list.length; ++i) { if (matcher.test(list[i])) { return true diff --git a/test/tap/invalid-cmd-exit-code.js b/test/tap/invalid-cmd-exit-code.js index c9918e5a7..f4bb444a1 100644 --- a/test/tap/invalid-cmd-exit-code.js +++ b/test/tap/invalid-cmd-exit-code.js @@ -1,28 +1,28 @@ -var test = require("tap").test -var common = require("../common-tap.js") +var test = require('tap').test +var common = require('../common-tap.js') var opts = { cwd: process.cwd() } -test("npm asdf should return exit code 1", function (t) { - common.npm(["asdf"], opts, function (er, c) { +test('npm asdf should return exit code 1', function (t) { + common.npm(['asdf'], opts, function (er, c) { if (er) throw er - t.ok(c, "exit code should not be zero") + t.ok(c, 'exit code should not be zero') t.end() }) }) -test("npm help should return exit code 0", function (t) { - common.npm(["help"], opts, function (er, c) { +test('npm help should return exit code 0', function (t) { + common.npm(['help'], opts, function (er, c) { if (er) throw er - t.equal(c, 0, "exit code should be 0") + t.equal(c, 0, 'exit code should be 0') t.end() }) }) -test("npm help fadf should return exit code 0", function (t) { - common.npm(["help", "fadf"], opts, function (er, c) { +test('npm help fadf should return exit code 0', function (t) { + common.npm(['help', 'fadf'], opts, function (er, c) { if (er) throw er - t.equal(c, 0, "exit code should be 0") + t.equal(c, 0, 'exit code should be 0') t.end() }) }) diff --git a/test/tap/lifecycle.js b/test/tap/lifecycle.js index aa0efc526..1bd77c383 100644 --- a/test/tap/lifecycle.js +++ b/test/tap/lifecycle.js @@ -1,12 +1,12 @@ -var test = require("tap").test -var npm = require("../../") -var lifecycle = require("../../lib/utils/lifecycle") +var test = require('tap').test +var npm = require('../../') +var lifecycle = require('../../lib/utils/lifecycle') -test("lifecycle: make env correctly", function (t) { +test('lifecycle: make env correctly', function (t) { npm.load({enteente: Infinity}, function () { var env = lifecycle.makeEnv({}, null, process.env) - t.equal("Infinity", env.npm_config_enteente) + t.equal('Infinity', env.npm_config_enteente) t.end() }) }) diff --git a/test/tap/link.js b/test/tap/link.js index ea47e8296..684fcf7e1 100644 --- a/test/tap/link.js +++ b/test/tap/link.js @@ -44,7 +44,6 @@ var installJSON = { license: 'ISC' } - test('setup', function (t) { setup() common.npm(['ls', '-g', '--depth=0'], OPTS, function (err, c, out) { diff --git a/test/tap/locker.js b/test/tap/locker.js index bc43c30e9..8c548095f 100644 --- a/test/tap/locker.js +++ b/test/tap/locker.js @@ -1,54 +1,54 @@ -var test = require("tap").test - , path = require("path") - , fs = require("graceful-fs") - , crypto = require("crypto") - , rimraf = require("rimraf") - , osenv = require("osenv") - , mkdirp = require("mkdirp") - , npm = require("../../") - , locker = require("../../lib/utils/locker.js") - , lock = locker.lock - , unlock = locker.unlock +var test = require('tap').test +var path = require('path') +var fs = require('graceful-fs') +var crypto = require('crypto') +var rimraf = require('rimraf') +var osenv = require('osenv') +var mkdirp = require('mkdirp') +var npm = require('../../') +var locker = require('../../lib/utils/locker.js') +var lock = locker.lock +var unlock = locker.unlock -var pkg = path.join(__dirname, "/locker") - , cache = path.join(pkg, "/cache") - , tmp = path.join(pkg, "/tmp") - , nm = path.join(pkg, "/node_modules") +var pkg = path.join(__dirname, '/locker') +var cache = path.join(pkg, '/cache') +var tmp = path.join(pkg, '/tmp') +var nm = path.join(pkg, '/node_modules') function cleanup () { process.chdir(osenv.tmpdir()) rimraf.sync(pkg) } -test("setup", function (t) { +test('setup', function (t) { cleanup() mkdirp.sync(cache) mkdirp.sync(tmp) t.end() }) -test("locking file puts lock in correct place", function (t) { +test('locking file puts lock in correct place', function (t) { npm.load({cache: cache, tmpdir: tmp}, function (er) { - t.ifError(er, "npm bootstrapped OK") + t.ifError(er, 'npm bootstrapped OK') - var n = "correct" - , c = n.replace(/[^a-zA-Z0-9]+/g, "-").replace(/^-+|-+$/g, "") - , p = path.resolve(nm, n) - , h = crypto.createHash("sha1").update(p).digest("hex") - , l = c.substr(0, 24)+"-"+h.substr(0, 16)+".lock" - , v = path.join(cache, "_locks", l) + var n = 'correct' + var c = n.replace(/[^a-zA-Z0-9]+/g, '-').replace(/^-+|-+$/g, '') + var p = path.resolve(nm, n) + var h = crypto.createHash('sha1').update(p).digest('hex') + var l = c.substr(0, 24) + '-' + h.substr(0, 16) + '.lock' + var v = path.join(cache, '_locks', l) lock(nm, n, function (er) { - t.ifError(er, "locked path") + t.ifError(er, 'locked path') fs.exists(v, function (found) { - t.ok(found, "lock found OK") + t.ok(found, 'lock found OK') unlock(nm, n, function (er) { - t.ifError(er, "unlocked path") + t.ifError(er, 'unlocked path') fs.exists(v, function (found) { - t.notOk(found, "lock deleted OK") + t.notOk(found, 'lock deleted OK') t.end() }) }) @@ -57,33 +57,33 @@ test("locking file puts lock in correct place", function (t) { }) }) -test("unlocking out of order errors out", function (t) { +test('unlocking out of order errors out', function (t) { npm.load({cache: cache, tmpdir: tmp}, function (er) { - t.ifError(er, "npm bootstrapped OK") + t.ifError(er, 'npm bootstrapped OK') - var n = "busted" - , c = n.replace(/[^a-zA-Z0-9]+/g, "-").replace(/^-+|-+$/g, "") - , p = path.resolve(nm, n) - , h = crypto.createHash("sha1").update(p).digest("hex") - , l = c.substr(0, 24)+"-"+h.substr(0, 16)+".lock" - , v = path.join(cache, "_locks", l) + var n = 'busted' + var c = n.replace(/[^a-zA-Z0-9]+/g, '-').replace(/^-+|-+$/g, '') + var p = path.resolve(nm, n) + var h = crypto.createHash('sha1').update(p).digest('hex') + var l = c.substr(0, 24) + '-' + h.substr(0, 16) + '.lock' + var v = path.join(cache, '_locks', l) fs.exists(v, function (found) { - t.notOk(found, "no lock to unlock") + t.notOk(found, 'no lock to unlock') t.throws(function () { unlock(nm, n, function () { t.fail("shouldn't get here") t.end() }) - }, "blew up as expected") + }, 'blew up as expected') t.end() }) }) }) -test("cleanup", function (t) { +test('cleanup', function (t) { cleanup() t.end() }) diff --git a/test/tap/logout.js b/test/tap/logout.js index 1d9392ad1..3a62cc273 100644 --- a/test/tap/logout.js +++ b/test/tap/logout.js @@ -1,58 +1,58 @@ -var fs = require("fs") -var path = require("path") +var fs = require('fs') +var path = require('path') -var mkdirp = require("mkdirp") -var mr = require("npm-registry-mock") -var rimraf = require("rimraf") -var test = require("tap").test +var mkdirp = require('mkdirp') +var mr = require('npm-registry-mock') +var rimraf = require('rimraf') +var test = require('tap').test -var common = require("../common-tap.js") +var common = require('../common-tap.js') -var pkg = path.resolve(__dirname, "logout") -var outfile = path.join(pkg, "_npmrc") +var pkg = path.resolve(__dirname, 'logout') +var outfile = path.join(pkg, '_npmrc') var opts = { cwd: pkg } var contents = function () {/* foo=boo //localhost:1337/:_authToken=glarb -*/}.toString().split("\n").slice(1, -1).join("\n") +*/}.toString().split('\n').slice(1, -1).join('\n') function mocks (server) { - server.delete("/-/user/token/glarb") + server.delete('/-/user/token/glarb') .reply(200, {}) } -test("setup", function (t) { +test('setup', function (t) { cleanup() setup() t.end() }) -test("npm logout", function (t) { +test('npm logout', function (t) { mr({ port: common.port, plugin: mocks }, function (err, s) { if (err) throw err common.npm( [ - "logout", - "--registry", common.registry, - "--loglevel", "silent", - "--userconfig", outfile + 'logout', + '--registry', common.registry, + '--loglevel', 'silent', + '--userconfig', outfile ], opts, function (err, code) { - t.ifError(err, "no error output") - t.notOk(code, "exited OK") + t.ifError(err, 'no error output') + t.notOk(code, 'exited OK') - var config = fs.readFileSync(outfile, "utf8") - t.equal(config, "foo=boo\n", "creds gone") + var config = fs.readFileSync(outfile, 'utf8') + t.equal(config, 'foo=boo\n', 'creds gone') s.close() t.end() }) }) }) -test("cleanup", function (t) { +test('cleanup', function (t) { cleanup() t.end() }) diff --git a/test/tap/ls-l-depth-0.js b/test/tap/ls-l-depth-0.js index d723b9c92..ab3189f2e 100644 --- a/test/tap/ls-l-depth-0.js +++ b/test/tap/ls-l-depth-0.js @@ -62,7 +62,9 @@ test('#6311: npm ll --depth=0 duplicates listing', function (t) { t.notOk(stderr, 'npm install ran silently') t.equal( stdout.trim(), - resolve(__dirname,'ls-l-depth-0')+'\n└─┬ glock@1.8.7 \n └── underscore@1.5.1', + resolve(__dirname, 'ls-l-depth-0') + + '\n└─┬ glock@1.8.7 ' + + '\n └── underscore@1.5.1', 'got expected install output' ) diff --git a/test/tap/ls-no-results.js b/test/tap/ls-no-results.js index 10f3ce001..9792774c6 100644 --- a/test/tap/ls-no-results.js +++ b/test/tap/ls-no-results.js @@ -1,11 +1,11 @@ -var test = require("tap").test -var spawn = require("child_process").spawn +var test = require('tap').test +var spawn = require('child_process').spawn var node = process.execPath -var npm = require.resolve("../../") -var args = [ npm, "ls", "ceci n’est pas une package" ] -test("ls exits non-zero when nothing found", function (t) { +var npm = require.resolve('../../') +var args = [ npm, 'ls', 'ceci n’est pas une package' ] +test('ls exits non-zero when nothing found', function (t) { var child = spawn(node, args) - child.on("exit", function (code) { + child.on('exit', function (code) { t.notEqual(code, 0) t.end() }) diff --git a/test/tap/nerf-dart.js b/test/tap/nerf-dart.js index 157f6c7df..a6df7272c 100644 --- a/test/tap/nerf-dart.js +++ b/test/tap/nerf-dart.js @@ -1,32 +1,32 @@ // taken from https://raw.githubusercontent.com/indexzero/npm/bd3cad01fbd3ab481d2f5da441b9eead16029123/test/tap/config-nerf-dart.js // originally written by Charlie Robbins, https://github.com/indexzero -var test = require("tap").test -var toNerfDart = require("../../lib/config/nerf-dart.js") +var test = require('tap').test +var toNerfDart = require('../../lib/config/nerf-dart.js') function validNerfDart (uri, valid) { - if (!valid) valid = "//registry.npmjs.org/" + if (!valid) valid = '//registry.npmjs.org/' test(uri, function (t) { t.equal(toNerfDart(uri), valid) t.end() }) } -validNerfDart("http://registry.npmjs.org") -validNerfDart("http://registry.npmjs.org/some-package") -validNerfDart("http://registry.npmjs.org/some-package?write=true") -validNerfDart("http://user:pass@registry.npmjs.org/some-package?write=true") -validNerfDart("http://registry.npmjs.org/#random-hash") -validNerfDart("http://registry.npmjs.org/some-package#random-hash") +validNerfDart('http://registry.npmjs.org') +validNerfDart('http://registry.npmjs.org/some-package') +validNerfDart('http://registry.npmjs.org/some-package?write=true') +validNerfDart('http://user:pass@registry.npmjs.org/some-package?write=true') +validNerfDart('http://registry.npmjs.org/#random-hash') +validNerfDart('http://registry.npmjs.org/some-package#random-hash') validNerfDart( - "http://relative.couchapp.npm/design/-/rewrite/", - "//relative.couchapp.npm/design/-/rewrite/" + 'http://relative.couchapp.npm/design/-/rewrite/', + '//relative.couchapp.npm/design/-/rewrite/' ) validNerfDart( - "http://relative.couchapp.npm:8080/design/-/rewrite/", - "//relative.couchapp.npm:8080/design/-/rewrite/" + 'http://relative.couchapp.npm:8080/design/-/rewrite/', + '//relative.couchapp.npm:8080/design/-/rewrite/' ) validNerfDart( - "http://relative.couchapp.npm:8080/design/-/rewrite/some-package", - "//relative.couchapp.npm:8080/design/-/rewrite/" + 'http://relative.couchapp.npm:8080/design/-/rewrite/some-package', + '//relative.couchapp.npm:8080/design/-/rewrite/' ) diff --git a/test/tap/nested-extraneous.js b/test/tap/nested-extraneous.js index fcba0418e..99d4bea5b 100644 --- a/test/tap/nested-extraneous.js +++ b/test/tap/nested-extraneous.js @@ -1,42 +1,42 @@ -var common = require("../common-tap.js") -var test = require("tap").test -var mkdirp = require("mkdirp") -var fs = require("fs") -var rimraf = require("rimraf") -var path = require("path") +var common = require('../common-tap.js') +var test = require('tap').test +var mkdirp = require('mkdirp') +var fs = require('fs') +var rimraf = require('rimraf') +var path = require('path') -var pkg = path.resolve(__dirname, "nested-extraneous") +var pkg = path.resolve(__dirname, 'nested-extraneous') var pj = { - name: "nested-extraneous", - version: "1.2.3" + name: 'nested-extraneous', + version: '1.2.3' } -var dep = path.resolve(pkg, "node_modules", "dep") +var dep = path.resolve(pkg, 'node_modules', 'dep') var deppj = { - name: "nested-extraneous-dep", - version: "1.2.3", + name: 'nested-extraneous-dep', + version: '1.2.3', dependencies: { - "nested-extra-depdep": "*" + 'nested-extra-depdep': '*' } } -var depdep = path.resolve(dep, "node_modules", "depdep") +var depdep = path.resolve(dep, 'node_modules', 'depdep') var depdeppj = { - name: "nested-extra-depdep", - version: "1.2.3" + name: 'nested-extra-depdep', + version: '1.2.3' } -test("setup", function (t) { +test('setup', function (t) { rimraf.sync(pkg) mkdirp.sync(depdep) - fs.writeFileSync(path.resolve(pkg, "package.json"), JSON.stringify(pj)) - fs.writeFileSync(path.resolve(dep, "package.json"), JSON.stringify(deppj)) - fs.writeFileSync(path.resolve(depdep, "package.json"), JSON.stringify(depdeppj)) + fs.writeFileSync(path.resolve(pkg, 'package.json'), JSON.stringify(pj)) + fs.writeFileSync(path.resolve(dep, 'package.json'), JSON.stringify(deppj)) + fs.writeFileSync(path.resolve(depdep, 'package.json'), JSON.stringify(depdeppj)) t.end() }) -test("test", function (t) { - common.npm(["ls"], { +test('test', function (t) { + common.npm(['ls'], { cwd: pkg }, function (er, code, sto, ste) { if (er) throw er @@ -47,7 +47,7 @@ test("test", function (t) { }) }) -test("clean", function (t) { +test('clean', function (t) { rimraf.sync(pkg) t.end() }) diff --git a/test/tap/noargs-install-config-save.js b/test/tap/noargs-install-config-save.js index b6900b431..81b23cca9 100644 --- a/test/tap/noargs-install-config-save.js +++ b/test/tap/noargs-install-config-save.js @@ -1,46 +1,47 @@ -var common = require("../common-tap.js") -var test = require("tap").test -var npm = require.resolve("../../bin/npm-cli.js") -var path = require("path") -var fs = require("fs") -var rimraf = require("rimraf") -var mkdirp = require("mkdirp") +var common = require('../common-tap.js') +var test = require('tap').test +var npm = require.resolve('../../bin/npm-cli.js') +var path = require('path') +var fs = require('fs') +var rimraf = require('rimraf') +var mkdirp = require('mkdirp') -var mr = require("npm-registry-mock") +var mr = require('npm-registry-mock') -var spawn = require("child_process").spawn +var spawn = require('child_process').spawn var node = process.execPath -var pkg = path.resolve(process.env.npm_config_tmp || "/tmp", - "noargs-install-config-save") +var pkg = path.resolve(process.env.npm_config_tmp || '/tmp', + 'noargs-install-config-save') -function writePackageJson() { +function writePackageJson () { rimraf.sync(pkg) mkdirp.sync(pkg) - mkdirp.sync(pkg + "/cache") + mkdirp.sync(pkg + '/cache') - fs.writeFileSync(pkg + "/package.json", JSON.stringify({ - "author": "Rocko Artischocko", - "name": "noargs", - "version": "0.0.0", - "devDependencies": { - "underscore": "1.3.1" + fs.writeFileSync(pkg + '/package.json', JSON.stringify({ + 'author': 'Rocko Artischocko', + 'name': 'noargs', + 'version': '0.0.0', + 'devDependencies': { + 'underscore': '1.3.1' } - }), "utf8") + }), 'utf8') } function createChild (args) { var env = { - "npm_config_save": true, - "npm_config_registry": common.registry, - "npm_config_cache": pkg + "/cache", + 'npm_config_save': true, + 'npm_config_registry': common.registry, + 'npm_config_cache': pkg + '/cache', HOME: process.env.HOME, Path: process.env.PATH, PATH: process.env.PATH } - if (process.platform === "win32") - env.npm_config_cache = "%APPDATA%\\npm-cache" + if (process.platform === 'win32') { + env.npm_config_cache = '%APPDATA%\\npm-cache' + } return spawn(node, args, { cwd: pkg, @@ -48,35 +49,35 @@ function createChild (args) { }) } -test("does not update the package.json with empty arguments", function (t) { +test('does not update the package.json with empty arguments', function (t) { writePackageJson() t.plan(1) - mr({port : common.port}, function (er, s) { - var child = createChild([npm, "install"]) - child.on("close", function () { - var text = JSON.stringify(fs.readFileSync(pkg + "/package.json", "utf8")) + mr({ port: common.port }, function (er, s) { + var child = createChild([npm, 'install']) + child.on('close', function () { + var text = JSON.stringify(fs.readFileSync(pkg + '/package.json', 'utf8')) s.close() - t.ok(text.indexOf("\"dependencies") === -1) + t.ok(text.indexOf('"dependencies') === -1) }) }) }) -test("updates the package.json (adds dependencies) with an argument", function (t) { +test('updates the package.json (adds dependencies) with an argument', function (t) { writePackageJson() t.plan(1) - mr({port : common.port}, function (er, s) { - var child = createChild([npm, "install", "underscore"]) - child.on("close", function () { + mr({ port: common.port }, function (er, s) { + var child = createChild([npm, 'install', 'underscore']) + child.on('close', function () { s.close() - var text = JSON.stringify(fs.readFileSync(pkg + "/package.json", "utf8")) - t.ok(text.indexOf("\"dependencies") !== -1) + var text = JSON.stringify(fs.readFileSync(pkg + '/package.json', 'utf8')) + t.ok(text.indexOf('"dependencies') !== -1) }) }) }) -test("cleanup", function (t) { - rimraf.sync(pkg + "/cache") +test('cleanup', function (t) { + rimraf.sync(pkg + '/cache') t.end() }) diff --git a/test/tap/npm-api-not-loaded-error.js b/test/tap/npm-api-not-loaded-error.js index afedfbcd0..48b71e521 100644 --- a/test/tap/npm-api-not-loaded-error.js +++ b/test/tap/npm-api-not-loaded-error.js @@ -1,47 +1,47 @@ -var test = require("tap").test -var npm = require("../..") -var path = require("path") -var rimraf = require("rimraf") -var npmrc = path.join(__dirname, "npmrc") -var fs = require("fs") +var test = require('tap').test +var npm = require('../..') +var path = require('path') +var rimraf = require('rimraf') +var npmrc = path.join(__dirname, 'npmrc') +var fs = require('fs') -test("setup", function (t) { - fs.writeFileSync(npmrc, "foo = bar\n", "ascii") +test('setup', function (t) { + fs.writeFileSync(npmrc, 'foo = bar\n', 'ascii') t.end() }) -test("calling set/get on config pre-load should throw", function (t) { +test('calling set/get on config pre-load should throw', function (t) { var threw = true try { - npm.config.get("foo") + npm.config.get('foo') threw = false } catch (er) { - t.equal(er.message, "npm.load() required") + t.equal(er.message, 'npm.load() required') } finally { - t.ok(threw, "get before load should throw") + t.ok(threw, 'get before load should throw') } threw = true try { - npm.config.set("foo", "bar") + npm.config.set('foo', 'bar') threw = false } catch (er) { - t.equal(er.message, "npm.load() required") + t.equal(er.message, 'npm.load() required') } finally { - t.ok(threw, "set before load should throw") + t.ok(threw, 'set before load should throw') } npm.load({ userconfig: npmrc }, function (er) { - if (er) - throw er - t.equal(npm.config.get("foo"), "bar") - npm.config.set("foo", "baz") - t.equal(npm.config.get("foo"), "baz") + if (er) throw er + + t.equal(npm.config.get('foo'), 'bar') + npm.config.set('foo', 'baz') + t.equal(npm.config.get('foo'), 'baz') t.end() }) }) -test("cleanup", function (t) { +test('cleanup', function (t) { rimraf.sync(npmrc) t.end() }) diff --git a/test/tap/optional-metadep-rollback-collision.js b/test/tap/optional-metadep-rollback-collision.js index 53befd593..10a33319d 100644 --- a/test/tap/optional-metadep-rollback-collision.js +++ b/test/tap/optional-metadep-rollback-collision.js @@ -63,7 +63,6 @@ var opdep = { } } - var badServer = function () {/* var createServer = require('http').createServer var spawn = require('child_process').spawn diff --git a/test/tap/outdated-depth-deep.js b/test/tap/outdated-depth-deep.js index 8d4a6428a..c39e029aa 100644 --- a/test/tap/outdated-depth-deep.js +++ b/test/tap/outdated-depth-deep.js @@ -1,26 +1,26 @@ -var common = require("../common-tap") - , path = require("path") - , test = require("tap").test - , rimraf = require("rimraf") - , npm = require("../../") - , mr = require("npm-registry-mock") - , pkg = path.resolve(__dirname, "outdated-depth-deep") - , cache = path.resolve(pkg, "cache") +var common = require('../common-tap') +var path = require('path') +var test = require('tap').test +var rimraf = require('rimraf') +var npm = require('../../') +var mr = require('npm-registry-mock') +var pkg = path.resolve(__dirname, 'outdated-depth-deep') +var cache = path.resolve(pkg, 'cache') -var osenv = require("osenv") -var mkdirp = require("mkdirp") -var fs = require("fs") +var osenv = require('osenv') +var mkdirp = require('mkdirp') +var fs = require('fs') var pj = JSON.stringify({ - "name": "whatever", - "description": "yeah idk", - "version": "1.2.3", - "main": "index.js", - "dependencies": { - "underscore": "1.3.1", - "npm-test-peer-deps": "0.0.0" + 'name': 'whatever', + 'description': 'yeah idk', + 'version': '1.2.3', + 'main': 'index.js', + 'dependencies': { + 'underscore': '1.3.1', + 'npm-test-peer-deps': '0.0.0' }, - "repository": "git://github.com/luk-/whatever" + 'repository': 'git://github.com/luk-/whatever' }, null, 2) function cleanup () { @@ -31,51 +31,49 @@ function cleanup () { function setup () { mkdirp.sync(pkg) process.chdir(pkg) - fs.writeFileSync(path.resolve(pkg, "package.json"), pj) + fs.writeFileSync(path.resolve(pkg, 'package.json'), pj) } -test("setup", function (t) { +test('setup', function (t) { cleanup() setup() t.end() }) -test("outdated depth deep (9999)", function (t) { - var underscoreOutdated = ["underscore", "1.3.1", "1.3.1", "1.5.1", "1.3.1"] - var childPkg = path.resolve(pkg, "node_modules", "npm-test-peer-deps") +test('outdated depth deep (9999)', function (t) { + var underscoreOutdated = ['underscore', '1.3.1', '1.3.1', '1.5.1', '1.3.1'] + var childPkg = path.resolve(pkg, 'node_modules', 'npm-test-peer-deps') var expected = [ [childPkg].concat(underscoreOutdated).concat([null]), [pkg].concat(underscoreOutdated).concat([null]) ] process.chdir(pkg) - mr({port : common.port}, function (er, s) { + mr({ port: common.port }, function (er, s) { npm.load({ - cache: cache - , loglevel: "silent" - , registry: common.registry - , depth: 9999 - } - , function () { - npm.install(".", function (er) { + cache: cache, + loglevel: 'silent', + registry: common.registry, + depth: 9999 + }, + function () { + npm.install('.', function (er) { + if (er) throw new Error(er) + npm.explore('npm-test-peer-deps', 'npm', 'install', 'underscore', function (er) { if (er) throw new Error(er) - npm.explore("npm-test-peer-deps", "npm", "install", "underscore", function (er) { - if (er) throw new Error(er) - npm.outdated(function (err, d) { - if (err) throw new Error(err) - t.deepEqual(d, expected) - s.close() - t.end() - }) + npm.outdated(function (err, d) { + if (err) throw new Error(err) + t.deepEqual(d, expected) + s.close() + t.end() }) }) - } - ) + }) + }) }) }) - -test("cleanup", function (t) { +test('cleanup', function (t) { cleanup() t.end() }) diff --git a/test/tap/outdated-depth-integer.js b/test/tap/outdated-depth-integer.js index 6bfb304b1..ddd2dd7c3 100644 --- a/test/tap/outdated-depth-integer.js +++ b/test/tap/outdated-depth-integer.js @@ -1,24 +1,24 @@ var common = require('../common-tap') - , test = require('tap').test - , rimraf = require('rimraf') - , npm = require('../../') - , mr = require('npm-registry-mock') - , pkg = __dirname + '/outdated-depth-integer' +var test = require('tap').test +var rimraf = require('rimraf') +var npm = require('../../') +var mr = require('npm-registry-mock') +var pkg = __dirname + '/outdated-depth-integer' -var osenv = require("osenv") -var mkdirp = require("mkdirp") -var fs = require("fs") +var osenv = require('osenv') +var mkdirp = require('mkdirp') +var fs = require('fs') var pj = JSON.stringify({ - "name": "whatever", - "description": "yeah idk", - "version": "1.2.3", - "main": "index.js", - "dependencies": { - "underscore": "1.3.1" + 'name': 'whatever', + 'description': 'yeah idk', + 'version': '1.2.3', + 'main': 'index.js', + 'dependencies': { + 'underscore': '1.3.1' }, - "repository": "git://github.com/luk-/whatever" -}, null, 2); + 'repository': 'git://github.com/luk-/whatever' +}, null, 2) function cleanup () { process.chdir(osenv.tmpdir()) @@ -28,10 +28,10 @@ function cleanup () { function setup () { mkdirp.sync(pkg) process.chdir(pkg) - fs.writeFileSync("package.json", pj) + fs.writeFileSync('package.json', pj) } -test("setup", function (t) { +test('setup', function (t) { cleanup() setup() t.end() @@ -50,12 +50,12 @@ test('outdated depth integer', function (t) { null ]] - mr({port : common.port}, function (er, s) { + mr({ port: common.port }, function (er, s) { npm.load({ - cache: pkg + '/cache' - , loglevel: 'silent' - , registry: common.registry - , depth: 5 + cache: pkg + '/cache', + loglevel: 'silent', + registry: common.registry, + depth: 5 } , function () { npm.install('request@0.9.0', function (er) { @@ -72,7 +72,7 @@ test('outdated depth integer', function (t) { }) }) -test("cleanup", function (t) { +test('cleanup', function (t) { cleanup() t.end() }) diff --git a/test/tap/outdated-git.js b/test/tap/outdated-git.js index 2162c743c..1a61a0c4d 100644 --- a/test/tap/outdated-git.js +++ b/test/tap/outdated-git.js @@ -2,7 +2,7 @@ var path = require('path') var test = require('tap').test var mkdirp = require('mkdirp') -var fs = require("graceful-fs") +var fs = require('graceful-fs') var rimraf = require('rimraf') var common = require('../common-tap.js') diff --git a/test/tap/outdated-local.js b/test/tap/outdated-local.js index f9b8af442..067696ca9 100644 --- a/test/tap/outdated-local.js +++ b/test/tap/outdated-local.js @@ -65,7 +65,6 @@ var pjLocalOptimistBumped = JSON.stringify({ version: '0.5.0' }, null, 2) + '\n' - function mocks (server) { server.get('/local-module') .reply(404) diff --git a/test/tap/outdated-notarget.js b/test/tap/outdated-notarget.js index 6058ddee4..5fd2b0634 100644 --- a/test/tap/outdated-notarget.js +++ b/test/tap/outdated-notarget.js @@ -1,23 +1,23 @@ // Fixes Issue #1770 -var common = require("../common-tap.js") -var test = require("tap").test -var npm = require("../../") -var osenv = require("osenv") -var path = require("path") -var fs = require("fs") -var rimraf = require("rimraf") -var mkdirp = require("mkdirp") -var pkg = path.resolve(__dirname, "outdated-notarget") -var cache = path.resolve(pkg, "cache") -var mr = require("npm-registry-mock") +var common = require('../common-tap.js') +var test = require('tap').test +var npm = require('../../') +var osenv = require('osenv') +var path = require('path') +var fs = require('fs') +var rimraf = require('rimraf') +var mkdirp = require('mkdirp') +var pkg = path.resolve(__dirname, 'outdated-notarget') +var cache = path.resolve(pkg, 'cache') +var mr = require('npm-registry-mock') -test("outdated-target: if no viable version is found, show error", function (t) { +test('outdated-target: if no viable version is found, show error', function (t) { t.plan(1) setup() - mr({port : common.port}, function (er, s) { + mr({ port: common.port }, function (er, s) { npm.load({ cache: cache, registry: common.registry}, function () { npm.commands.update(function (er) { - t.equal(er.code, "ETARGET") + t.equal(er.code, 'ETARGET') s.close() t.end() }) @@ -25,23 +25,23 @@ test("outdated-target: if no viable version is found, show error", function (t) }) }) -test("cleanup", function (t) { +test('cleanup', function (t) { process.chdir(osenv.tmpdir()) rimraf.sync(pkg) t.end() }) -function setup() { +function setup () { mkdirp.sync(pkg) mkdirp.sync(cache) - fs.writeFileSync(path.resolve(pkg, "package.json"), JSON.stringify({ - author: "Evan Lucas", - name: "outdated-notarget", - version: "0.0.0", - description: "Test for outdated-target", + fs.writeFileSync(path.resolve(pkg, 'package.json'), JSON.stringify({ + author: 'Evan Lucas', + name: 'outdated-notarget', + version: '0.0.0', + description: 'Test for outdated-target', dependencies: { - underscore: "~199.7.1" + underscore: '~199.7.1' } - }), "utf8") + }), 'utf8') process.chdir(pkg) } diff --git a/test/tap/outdated-private.js b/test/tap/outdated-private.js index f7fb47587..1d5e460c6 100644 --- a/test/tap/outdated-private.js +++ b/test/tap/outdated-private.js @@ -1,79 +1,79 @@ -var common = require("../common-tap.js") -var test = require("tap").test -var npm = require("../../") -var rimraf = require("rimraf") -var path = require("path") -var mr = require("npm-registry-mock") -var osenv = require("osenv") -var mkdirp = require("mkdirp") -var fs = require("graceful-fs") +var common = require('../common-tap.js') +var test = require('tap').test +var npm = require('../../') +var rimraf = require('rimraf') +var path = require('path') +var mr = require('npm-registry-mock') +var osenv = require('osenv') +var mkdirp = require('mkdirp') +var fs = require('graceful-fs') -var pkg = path.resolve(__dirname, "outdated-private") -var pkgLocalPrivate = path.resolve(pkg, "local-private") -var pkgScopedLocalPrivate = path.resolve(pkg, "another-local-private") -var pkgLocalUnderscore = path.resolve(pkg, "underscore") +var pkg = path.resolve(__dirname, 'outdated-private') +var pkgLocalPrivate = path.resolve(pkg, 'local-private') +var pkgScopedLocalPrivate = path.resolve(pkg, 'another-local-private') +var pkgLocalUnderscore = path.resolve(pkg, 'underscore') var pjParent = JSON.stringify({ - name : "outdated-private", - version : "1.0.0", - dependencies : { - "local-private" : "file:local-private", - "@scoped/another-local-private" : "file:another-local-private", - "underscore" : "file:underscore" + name: 'outdated-private', + version: '1.0.0', + dependencies: { + 'local-private': 'file:local-private', + '@scoped/another-local-private': 'file:another-local-private', + 'underscore': 'file:underscore' } -}, null, 2) + "\n" +}, null, 2) + '\n' var pjLocalPrivate = JSON.stringify({ - name : "local-private", - version : "1.0.0", - private : true -}, null, 2) + "\n" + name: 'local-private', + version: '1.0.0', + 'private': true +}, null, 2) + '\n' var pjLocalPrivateBumped = JSON.stringify({ - name : "local-private", - version : "1.1.0", - private : true -}, null, 2) + "\n" + name: 'local-private', + version: '1.1.0', + 'private': true +}, null, 2) + '\n' var pjScopedLocalPrivate = JSON.stringify({ - name : "@scoped/another-local-private", - version : "1.0.0", - private : true -}, null, 2) + "\n" + name: '@scoped/another-local-private', + version: '1.0.0', + 'private': true +}, null, 2) + '\n' var pjLocalUnderscore = JSON.stringify({ - name : "underscore", - version : "1.3.1" -}, null, 2) + "\n" + name: 'underscore', + version: '1.3.1' +}, null, 2) + '\n' -test("setup", function (t) { +test('setup', function (t) { bootstrap() t.end() }) -test("outdated ignores private modules", function (t) { +test('outdated ignores private modules', function (t) { t.plan(3) process.chdir(pkg) - mr({ port : common.port }, function (err, s) { + mr({ port: common.port }, function (er, s) { npm.load( { - loglevel : "silent", - parseable : true, - registry : common.registry + loglevel: 'silent', + parseable: true, + registry: common.registry }, function () { - npm.install(".", function (err) { - t.ifError(err, "install success") + npm.install('.', function (err) { + t.ifError(err, 'install success') bumpLocalPrivate() npm.outdated(function (er, d) { - t.ifError(er, "outdated success") + t.ifError(er, 'outdated success') t.deepEqual(d, [[ - path.resolve(__dirname, "outdated-private"), - "underscore", - "1.3.1", - "1.5.1", - "1.5.1", - "underscore@1.5.1", + path.resolve(__dirname, 'outdated-private'), + 'underscore', + '1.3.1', + '1.5.1', + '1.5.1', + 'underscore@1.5.1', null ]]) s.close() @@ -84,27 +84,27 @@ test("outdated ignores private modules", function (t) { }) }) -test("cleanup", function (t) { +test('cleanup', function (t) { cleanup() t.end() }) function bootstrap () { mkdirp.sync(pkg) - fs.writeFileSync(path.resolve(pkg, "package.json"), pjParent) + fs.writeFileSync(path.resolve(pkg, 'package.json'), pjParent) mkdirp.sync(pkgLocalPrivate) - fs.writeFileSync(path.resolve(pkgLocalPrivate, "package.json"), pjLocalPrivate) + fs.writeFileSync(path.resolve(pkgLocalPrivate, 'package.json'), pjLocalPrivate) mkdirp.sync(pkgScopedLocalPrivate) - fs.writeFileSync(path.resolve(pkgScopedLocalPrivate, "package.json"), pjScopedLocalPrivate) + fs.writeFileSync(path.resolve(pkgScopedLocalPrivate, 'package.json'), pjScopedLocalPrivate) mkdirp.sync(pkgLocalUnderscore) - fs.writeFileSync(path.resolve(pkgLocalUnderscore, "package.json"), pjLocalUnderscore) + fs.writeFileSync(path.resolve(pkgLocalUnderscore, 'package.json'), pjLocalUnderscore) } function bumpLocalPrivate () { - fs.writeFileSync(path.resolve(pkgLocalPrivate, "package.json"), pjLocalPrivateBumped) + fs.writeFileSync(path.resolve(pkgLocalPrivate, 'package.json'), pjLocalPrivateBumped) } function cleanup () { diff --git a/test/tap/owner.js b/test/tap/owner.js index 938c21665..4bef1a0d8 100644 --- a/test/tap/owner.js +++ b/test/tap/owner.js @@ -1,79 +1,79 @@ -var mr = require("npm-registry-mock") -var test = require("tap").test +var mr = require('npm-registry-mock') +var test = require('tap').test -var common = require("../common-tap.js") +var common = require('../common-tap.js') var server var EXEC_OPTS = {} var jashkenas = { - name : "jashkenas", - email : "jashkenas@gmail.com" + name: 'jashkenas', + email: 'jashkenas@gmail.com' } var othiym23 = { - name : "othiym23", - email : "forrest@npmjs.com" + name: 'othiym23', + email: 'forrest@npmjs.com' } var bcoe = { - name : "bcoe", - email : "ben@npmjs.com" + name: 'bcoe', + email: 'ben@npmjs.com' } function shrt (user) { - return user.name+" <"+user.email+">\n" + return user.name + ' <' + user.email + '>\n' } function mocks (server) { - server.get("/-/user/org.couchdb.user:othiym23") + server.get('/-/user/org.couchdb.user:othiym23') .many().reply(200, othiym23) // test 1 - server.get("/underscore") - .reply(200, {_id:"underscore",_rev:1,maintainers:[jashkenas]}) + server.get('/underscore') + .reply(200, { _id: 'underscore', _rev: 1, maintainers: [jashkenas] }) server.put( - "/underscore/-rev/1", - {_id:"underscore",_rev:1,maintainers:[jashkenas,othiym23]}, + '/underscore/-rev/1', + { _id: 'underscore', _rev: 1, maintainers: [jashkenas, othiym23] }, {} - ).reply(200, {_id:"underscore",_rev:2,maintainers:[jashkenas,othiym23]}) + ).reply(200, { _id: 'underscore', _rev: 2, maintainers: [jashkenas, othiym23] }) // test 2 - server.get("/@xxx%2fscoped") - .reply(200, {_id:"@xxx/scoped",_rev:1,maintainers:[bcoe]}) + server.get('/@xxx%2fscoped') + .reply(200, { _id: '@xxx/scoped', _rev: 1, maintainers: [bcoe] }) server.put( - "/@xxx%2fscoped/-rev/1", - {_id:"@xxx/scoped",_rev:1,maintainers:[bcoe,othiym23]}, + '/@xxx%2fscoped/-rev/1', + { _id: '@xxx/scoped', _rev: 1, maintainers: [bcoe, othiym23] }, {} - ).reply(200, {_id:"@xxx/scoped",_rev:2,maintainers:[bcoe,othiym23]}) + ).reply(200, { _id: '@xxx/scoped', _rev: 2, maintainers: [bcoe, othiym23] }) // test 3 - server.get("/underscore") - .reply(200, {_id:"underscore",_rev:2,maintainers:[jashkenas,othiym23]}) + server.get('/underscore') + .reply(200, { _id: 'underscore', _rev: 2, maintainers: [jashkenas, othiym23] }) // test 4 - server.get("/underscore") - .reply(200, {_id:"underscore",_rev:2,maintainers:[jashkenas,othiym23]}) + server.get('/underscore') + .reply(200, { _id: 'underscore', _rev: 2, maintainers: [jashkenas, othiym23] }) server.put( - "/underscore/-rev/2", - {_id:"underscore",_rev:2,maintainers:[jashkenas]}, + '/underscore/-rev/2', + { _id: 'underscore', _rev: 2, maintainers: [jashkenas] }, {} - ).reply(200, {_id:"underscore",_rev:3,maintainers:[jashkenas]}) + ).reply(200, { _id: 'underscore', _rev: 3, maintainers: [jashkenas] }) } -test("setup", function (t) { +test('setup', function (t) { common.npm( [ - "--loglevel", "silent", - "cache", "clean" + '--loglevel', 'silent', + 'cache', 'clean' ], EXEC_OPTS, function (err, code) { - t.ifError(err, "npm cache clean ran without error") - t.notOk(code, "npm cache clean exited cleanly") + t.ifError(err, 'npm cache clean ran without error') + t.notOk(code, 'npm cache clean exited cleanly') - mr({ port : common.port, plugin : mocks }, function (err, s) { + mr({ port: common.port, plugin: mocks }, function (er, s) { server = s t.end() }) @@ -81,83 +81,83 @@ test("setup", function (t) { ) }) -test("npm owner add", function (t) { +test('npm owner add', function (t) { common.npm( [ - "--loglevel", "silent", - "--registry", common.registry, - "owner", "add", "othiym23", "underscore" + '--loglevel', 'silent', + '--registry', common.registry, + 'owner', 'add', 'othiym23', 'underscore' ], EXEC_OPTS, function (err, code, stdout, stderr) { - t.ifError(err, "npm owner add ran without error") - t.notOk(code, "npm owner add exited cleanly") - t.notOk(stderr, "npm owner add ran silently") - t.equal(stdout, "+ othiym23 (underscore)\n", "got expected add output") + t.ifError(err, 'npm owner add ran without error') + t.notOk(code, 'npm owner add exited cleanly') + t.notOk(stderr, 'npm owner add ran silently') + t.equal(stdout, '+ othiym23 (underscore)\n', 'got expected add output') t.end() } ) }) -test("npm owner add (scoped)", function (t) { +test('npm owner add (scoped)', function (t) { common.npm( [ - "--loglevel", "silent", - "--registry", common.registry, - "owner", "add", "othiym23", "@xxx/scoped" + '--loglevel', 'silent', + '--registry', common.registry, + 'owner', 'add', 'othiym23', '@xxx/scoped' ], EXEC_OPTS, function (err, code, stdout, stderr) { - t.ifError(err, "npm owner add (scoped) ran without error") - t.notOk(code, "npm owner add (scoped) exited cleanly") - t.notOk(stderr, "npm owner add (scoped) ran silently") - t.equal(stdout, "+ othiym23 (@xxx/scoped)\n", "got expected scoped add output") + t.ifError(err, 'npm owner add (scoped) ran without error') + t.notOk(code, 'npm owner add (scoped) exited cleanly') + t.notOk(stderr, 'npm owner add (scoped) ran silently') + t.equal(stdout, '+ othiym23 (@xxx/scoped)\n', 'got expected scoped add output') t.end() } ) }) -test("npm owner ls", function (t) { +test('npm owner ls', function (t) { common.npm( [ - "--loglevel", "silent", - "--registry", common.registry, - "owner", "ls", "underscore" + '--loglevel', 'silent', + '--registry', common.registry, + 'owner', 'ls', 'underscore' ], EXEC_OPTS, function (err, code, stdout, stderr) { - t.ifError(err, "npm owner ls ran without error") - t.notOk(code, "npm owner ls exited cleanly") - t.notOk(stderr, "npm owner ls ran silently") - t.equal(stdout, shrt(jashkenas)+shrt(othiym23), "got expected ls output") + t.ifError(err, 'npm owner ls ran without error') + t.notOk(code, 'npm owner ls exited cleanly') + t.notOk(stderr, 'npm owner ls ran silently') + t.equal(stdout, shrt(jashkenas) + shrt(othiym23), 'got expected ls output') t.end() } ) }) -test("npm owner rm", function (t) { +test('npm owner rm', function (t) { common.npm( [ - "--loglevel", "silent", - "--registry", common.registry, - "owner", "rm", "othiym23", "underscore" + '--loglevel', 'silent', + '--registry', common.registry, + 'owner', 'rm', 'othiym23', 'underscore' ], EXEC_OPTS, function (err, code, stdout, stderr) { - t.ifError(err, "npm owner rm ran without error") - t.notOk(code, "npm owner rm exited cleanly") - t.notOk(stderr, "npm owner rm ran silently") - t.equal(stdout, "- othiym23 (underscore)\n", "got expected rm output") + t.ifError(err, 'npm owner rm ran without error') + t.notOk(code, 'npm owner rm exited cleanly') + t.notOk(stderr, 'npm owner rm ran silently') + t.equal(stdout, '- othiym23 (underscore)\n', 'got expected rm output') t.end() } ) }) -test("cleanup", function (t) { +test('cleanup', function (t) { server.close() t.end() }) diff --git a/test/tap/pack-scoped.js b/test/tap/pack-scoped.js index 5c351339c..05b9d12a8 100644 --- a/test/tap/pack-scoped.js +++ b/test/tap/pack-scoped.js @@ -1,29 +1,29 @@ // verify that prepublish runs on pack and publish -var test = require("tap").test -var common = require("../common-tap") -var fs = require("graceful-fs") -var join = require("path").join -var mkdirp = require("mkdirp") -var rimraf = require("rimraf") +var test = require('tap').test +var common = require('../common-tap') +var fs = require('graceful-fs') +var join = require('path').join +var mkdirp = require('mkdirp') +var rimraf = require('rimraf') -var pkg = join(__dirname, "scoped_package") -var manifest = join(pkg, "package.json") -var tmp = join(pkg, "tmp") -var cache = join(pkg, "cache") +var pkg = join(__dirname, 'scoped_package') +var manifest = join(pkg, 'package.json') +var tmp = join(pkg, 'tmp') +var cache = join(pkg, 'cache') var data = { - name : "@scope/generic-package", - version : "90000.100001.5" + name: '@scope/generic-package', + version: '90000.100001.5' } -test("setup", function (t) { +test('setup', function (t) { var n = 0 rimraf.sync(pkg) - mkdirp(pkg, then()) + mkdirp(pkg, then()) mkdirp(cache, then()) - mkdirp(tmp, then()) + mkdirp(tmp, then()) function then () { n++ @@ -34,23 +34,23 @@ test("setup", function (t) { } function next () { - fs.writeFile(manifest, JSON.stringify(data), "ascii", done) + fs.writeFile(manifest, JSON.stringify(data), 'ascii', done) } function done (er) { t.ifError(er) - t.pass("setup done") + t.pass('setup done') t.end() } }) -test("test", function (t) { +test('test', function (t) { var env = { - "npm_config_cache" : cache, - "npm_config_tmp" : tmp, - "npm_config_prefix" : pkg, - "npm_config_global" : "false" + 'npm_config_cache': cache, + 'npm_config_tmp': tmp, + 'npm_config_prefix': pkg, + 'npm_config_global': 'false' } for (var i in process.env) { @@ -58,24 +58,24 @@ test("test", function (t) { } common.npm([ - "pack", - "--loglevel", "warn" + 'pack', + '--loglevel', 'warn' ], { cwd: pkg, env: env - }, function(err, code, stdout, stderr) { - t.ifErr(err, "npm pack finished without error") - t.equal(code, 0, "npm pack exited ok") - t.notOk(stderr, "got stderr data: " + JSON.stringify("" + stderr)) + }, function (err, code, stdout, stderr) { + t.ifErr(err, 'npm pack finished without error') + t.equal(code, 0, 'npm pack exited ok') + t.notOk(stderr, 'got stderr data: ' + JSON.stringify('' + stderr)) stdout = stdout.trim() - var regex = new RegExp("scope-generic-package-90000.100001.5.tgz", "ig") - t.ok(stdout.match(regex), "found package") + var regex = new RegExp('scope-generic-package-90000.100001.5.tgz', 'ig') + t.ok(stdout.match(regex), 'found package') t.end() }) }) -test("cleanup", function (t) { +test('cleanup', function (t) { rimraf.sync(pkg) - t.pass("cleaned up") + t.pass('cleaned up') t.end() }) diff --git a/test/tap/peer-deps-toplevel.js b/test/tap/peer-deps-toplevel.js index bd2309912..3a8d3c722 100644 --- a/test/tap/peer-deps-toplevel.js +++ b/test/tap/peer-deps-toplevel.js @@ -53,7 +53,7 @@ var expected = { version: '*', peerMissing: true, dependencies: {} - }, + } } } } diff --git a/test/tap/peer-deps-without-package-json.js b/test/tap/peer-deps-without-package-json.js index f60c99232..781686f62 100644 --- a/test/tap/peer-deps-without-package-json.js +++ b/test/tap/peer-deps-without-package-json.js @@ -31,7 +31,7 @@ var fileJS = function () { test('setup', function (t) { t.comment('test for https://github.com/npm/npm/issues/3049') cleanup() - mkdirp.sync(cache) + mkdirp.sync(cache) mkdirp.sync(nodeModules) fs.writeFileSync(path.join(pkg, 'file-js.js'), fileJS) process.chdir(pkg) @@ -53,7 +53,7 @@ test('installing a peerDeps-using package without package.json', function (t) { }, function () { npm.install(common.registry + '/ok.js', function (err, result) { t.ifError(err, 'installed ok.js') - + t.ok( fs.existsSync(path.join(nodeModules, 'npm-test-peer-deps-file')), 'passive peer dep installed' diff --git a/test/tap/prepublish.js b/test/tap/prepublish.js index 36391beeb..f065a656a 100644 --- a/test/tap/prepublish.js +++ b/test/tap/prepublish.js @@ -1,16 +1,16 @@ // verify that prepublish runs on pack and publish -var common = require("../common-tap") -var test = require("tap").test -var fs = require("graceful-fs") -var join = require("path").join -var mkdirp = require("mkdirp") -var rimraf = require("rimraf") +var common = require('../common-tap') +var test = require('tap').test +var fs = require('graceful-fs') +var join = require('path').join +var mkdirp = require('mkdirp') +var rimraf = require('rimraf') -var pkg = join(__dirname, "prepublish_package") -var tmp = join(pkg, "tmp") -var cache = join(pkg, "cache") +var pkg = join(__dirname, 'prepublish_package') +var tmp = join(pkg, 'tmp') +var cache = join(pkg, 'cache') -test("setup", function (t) { +test('setup', function (t) { var n = 0 cleanup() mkdirp(pkg, then()) @@ -25,58 +25,60 @@ test("setup", function (t) { } function next () { - fs.writeFile(join(pkg, "package.json"), JSON.stringify({ - name: "npm-test-prepublish", - version: "1.2.5", - scripts: { prepublish: "echo ok" } - }), "ascii", function (er) { + fs.writeFile(join(pkg, 'package.json'), JSON.stringify({ + name: 'npm-test-prepublish', + version: '1.2.5', + scripts: { prepublish: 'echo ok' } + }), 'ascii', function (er) { if (er) throw er - t.pass("setup done") + t.pass('setup done') t.end() }) } }) -test("test", function (t) { +test('test', function (t) { var env = { - "npm_config_cache" : cache, - "npm_config_tmp" : tmp, - "npm_config_prefix" : pkg, - "npm_config_global" : "false" + 'npm_config_cache': cache, + 'npm_config_tmp': tmp, + 'npm_config_prefix': pkg, + 'npm_config_global': 'false' } + for (var i in process.env) { - if (!/^npm_config_/.test(i)) + if (!/^npm_config_/.test(i)) { env[i] = process.env[i] + } } common.npm([ - "pack", - "--loglevel", "warn" - ], { cwd: pkg, env: env }, function(err, code, stdout, stderr) { - t.equal(code, 0, "pack finished successfully") - t.ifErr(err, "pack finished successfully") + 'pack', + '--loglevel', 'warn' + ], { cwd: pkg, env: env }, function (err, code, stdout, stderr) { + t.equal(code, 0, 'pack finished successfully') + t.ifErr(err, 'pack finished successfully') - t.notOk(stderr, "got stderr data:" + JSON.stringify("" + stderr)) + t.notOk(stderr, 'got stderr data:' + JSON.stringify('' + stderr)) var c = stdout.trim() - var regex = new RegExp("" + - "> npm-test-prepublish@1.2.5 prepublish [^\\r\\n]+\\r?\\n" + - "> echo ok\\r?\\n" + - "\\r?\\n" + - "ok\\r?\\n" + - "npm-test-prepublish-1.2.5.tgz", "ig") + var regex = new RegExp('' + + '> npm-test-prepublish@1.2.5 prepublish [^\\r\\n]+\\r?\\n' + + '> echo ok\\r?\\n' + + '\\r?\\n' + + 'ok\\r?\\n' + + 'npm-test-prepublish-1.2.5.tgz', 'ig') t.ok(c.match(regex)) t.end() }) }) -test("cleanup", function (t) { +test('cleanup', function (t) { cleanup() - t.pass("cleaned up") + t.pass('cleaned up') t.end() }) -function cleanup() { +function cleanup () { rimraf.sync(pkg) } diff --git a/test/tap/publish-access-scoped.js b/test/tap/publish-access-scoped.js index e734ebfd7..adc67a48e 100644 --- a/test/tap/publish-access-scoped.js +++ b/test/tap/publish-access-scoped.js @@ -1,15 +1,15 @@ -var fs = require("fs") -var path = require("path") +var fs = require('fs') +var path = require('path') -var test = require("tap").test -var mkdirp = require("mkdirp") -var rimraf = require("rimraf") -var nock = require("nock") +var test = require('tap').test +var mkdirp = require('mkdirp') +var rimraf = require('rimraf') +var nock = require('nock') -var npm = require("../../") -var common = require("../common-tap.js") +var npm = require('../../') +var common = require('../common-tap.js') -var pkg = path.join(__dirname, "publish-access") +var pkg = path.join(__dirname, 'publish-access') // TODO: nock uses setImmediate, breaks 0.8: replace with mockRegistry if (!global.setImmediate) { @@ -19,46 +19,46 @@ if (!global.setImmediate) { } } -test("setup", function (t) { - mkdirp(path.join(pkg, "cache"), function () { +test('setup', function (t) { + mkdirp(path.join(pkg, 'cache'), function () { var configuration = { - cache : path.join(pkg, "cache"), - loglevel : "silent", - registry : common.registry + cache: path.join(pkg, 'cache'), + loglevel: 'silent', + registry: common.registry } npm.load(configuration, next) }) function next (er) { - t.ifError(er, "npm loaded successfully") + t.ifError(er, 'npm loaded successfully') process.chdir(pkg) fs.writeFile( - path.join(pkg, "package.json"), + path.join(pkg, 'package.json'), JSON.stringify({ - name: "@bigco/publish-access", - version: "1.2.5" + name: '@bigco/publish-access', + version: '1.2.5' }), - "ascii", + 'ascii', function (er) { t.ifError(er) - t.pass("setup done") + t.pass('setup done') t.end() } ) } }) -test("scoped packages pass public access if set", function (t) { +test('scoped packages pass public access if set', function (t) { var put = nock(common.registry) - .put("/@bigco%2fpublish-access") + .put('/@bigco%2fpublish-access') .reply(201, verify) - npm.config.set("access", "public") + npm.config.set('access', 'public') npm.commands.publish([], false, function (er) { - t.ifError(er, "published without error") + t.ifError(er, 'published without error') put.done() t.end() @@ -67,14 +67,14 @@ test("scoped packages pass public access if set", function (t) { function verify (_, body) { t.doesNotThrow(function () { var parsed = JSON.parse(body) - t.equal(parsed.access, "public", "access level is correct") - }, "converted body back into object") + t.equal(parsed.access, 'public', 'access level is correct') + }, 'converted body back into object') return {ok: true} } }) -test("cleanup", function (t) { +test('cleanup', function (t) { process.chdir(__dirname) rimraf(pkg, function (er) { t.ifError(er) diff --git a/test/tap/publish-access-unscoped-restricted-fails.js b/test/tap/publish-access-unscoped-restricted-fails.js index 4d39b00b1..b97539938 100644 --- a/test/tap/publish-access-unscoped-restricted-fails.js +++ b/test/tap/publish-access-unscoped-restricted-fails.js @@ -1,14 +1,14 @@ -var fs = require("fs") -var path = require("path") +var fs = require('fs') +var path = require('path') -var test = require("tap").test -var mkdirp = require("mkdirp") -var rimraf = require("rimraf") +var test = require('tap').test +var mkdirp = require('mkdirp') +var rimraf = require('rimraf') -var npm = require("../../") -var common = require("../common-tap.js") +var npm = require('../../') +var common = require('../common-tap.js') -var pkg = path.join(__dirname, "publish-access-unscoped") +var pkg = path.join(__dirname, 'publish-access-unscoped') // TODO: nock uses setImmediate, breaks 0.8: replace with mockRegistry if (!global.setImmediate) { @@ -18,49 +18,49 @@ if (!global.setImmediate) { } } -test("setup", function (t) { - mkdirp(path.join(pkg, "cache"), function () { +test('setup', function (t) { + mkdirp(path.join(pkg, 'cache'), function () { var configuration = { - cache : path.join(pkg, "cache"), - loglevel : "silent", - registry : common.registry + cache: path.join(pkg, 'cache'), + loglevel: 'silent', + registry: common.registry } npm.load(configuration, next) }) function next (er) { - t.ifError(er, "npm loaded successfully") + t.ifError(er, 'npm loaded successfully') process.chdir(pkg) fs.writeFile( - path.join(pkg, "package.json"), + path.join(pkg, 'package.json'), JSON.stringify({ - name: "publish-access", - version: "1.2.5" + name: 'publish-access', + version: '1.2.5' }), - "ascii", + 'ascii', function (er) { t.ifError(er) - t.pass("setup done") + t.pass('setup done') t.end() } ) } }) -test("unscoped packages cannot be restricted", function (t) { - npm.config.set("access", "restricted") +test('unscoped packages cannot be restricted', function (t) { + npm.config.set('access', 'restricted') npm.commands.publish([], false, function (er) { - t.ok(er, "got an error back") + t.ok(er, 'got an error back') t.equal(er.message, "Can't restrict access to unscoped packages.") t.end() }) }) -test("cleanup", function (t) { +test('cleanup', function (t) { process.chdir(__dirname) rimraf(pkg, function (er) { t.ifError(er) diff --git a/test/tap/publish-access-unscoped.js b/test/tap/publish-access-unscoped.js index 023bfba5f..48b12ed52 100644 --- a/test/tap/publish-access-unscoped.js +++ b/test/tap/publish-access-unscoped.js @@ -1,15 +1,15 @@ -var fs = require("fs") -var path = require("path") +var fs = require('fs') +var path = require('path') -var test = require("tap").test -var mkdirp = require("mkdirp") -var rimraf = require("rimraf") -var nock = require("nock") +var test = require('tap').test +var mkdirp = require('mkdirp') +var rimraf = require('rimraf') +var nock = require('nock') -var npm = require("../../") -var common = require("../common-tap.js") +var npm = require('../../') +var common = require('../common-tap.js') -var pkg = path.join(__dirname, "publish-access-unscoped") +var pkg = path.join(__dirname, 'publish-access-unscoped') // TODO: nock uses setImmediate, breaks 0.8: replace with mockRegistry if (!global.setImmediate) { @@ -19,46 +19,46 @@ if (!global.setImmediate) { } } -test("setup", function (t) { - mkdirp(path.join(pkg, "cache"), function () { +test('setup', function (t) { + mkdirp(path.join(pkg, 'cache'), function () { var configuration = { - cache : path.join(pkg, "cache"), - loglevel : "silent", - registry : common.registry + cache: path.join(pkg, 'cache'), + loglevel: 'silent', + registry: common.registry } npm.load(configuration, next) }) function next (er) { - t.ifError(er, "npm loaded successfully") + t.ifError(er, 'npm loaded successfully') process.chdir(pkg) fs.writeFile( - path.join(pkg, "package.json"), + path.join(pkg, 'package.json'), JSON.stringify({ - name: "publish-access", - version: "1.2.5" + name: 'publish-access', + version: '1.2.5' }), - "ascii", + 'ascii', function (er) { t.ifError(er) - t.pass("setup done") + t.pass('setup done') t.end() } ) } }) -test("unscoped packages can be explicitly set as public", function (t) { +test('unscoped packages can be explicitly set as public', function (t) { var put = nock(common.registry) - .put("/publish-access") + .put('/publish-access') .reply(201, verify) - npm.config.set("access", "public") + npm.config.set('access', 'public') npm.commands.publish([], false, function (er) { - t.ifError(er, "published without error") + t.ifError(er, 'published without error') put.done() t.end() @@ -67,14 +67,14 @@ test("unscoped packages can be explicitly set as public", function (t) { function verify (_, body) { t.doesNotThrow(function () { var parsed = JSON.parse(body) - t.equal(parsed.access, "public", "access level is correct") - }, "converted body back into object") + t.equal(parsed.access, 'public', 'access level is correct') + }, 'converted body back into object') return {ok: true} } }) -test("cleanup", function (t) { +test('cleanup', function (t) { process.chdir(__dirname) rimraf(pkg, function (er) { t.ifError(er) diff --git a/test/tap/publish-config.js b/test/tap/publish-config.js index 1d063535b..57070f78b 100644 --- a/test/tap/publish-config.js +++ b/test/tap/publish-config.js @@ -1,37 +1,37 @@ -var common = require("../common-tap.js") -var test = require("tap").test -var fs = require("fs") -var osenv = require("osenv") -var pkg = process.env.npm_config_tmp || "/tmp" -pkg += "/npm-test-publish-config" +var common = require('../common-tap.js') +var test = require('tap').test +var fs = require('fs') +var osenv = require('osenv') +var pkg = process.env.npm_config_tmp || '/tmp' +pkg += '/npm-test-publish-config' -require("mkdirp").sync(pkg) +require('mkdirp').sync(pkg) -fs.writeFileSync(pkg + "/package.json", JSON.stringify({ - name: "npm-test-publish-config", - version: "1.2.3", +fs.writeFileSync(pkg + '/package.json', JSON.stringify({ + name: 'npm-test-publish-config', + version: '1.2.3', publishConfig: { registry: common.registry } -}), "utf8") +}), 'utf8') -fs.writeFileSync(pkg + "/fixture_npmrc", - "//localhost:1337/:email = fancy@feast.net\n" + - "//localhost:1337/:username = fancy\n" + - "//localhost:1337/:_password = " + new Buffer("feast").toString("base64") + "\n" + - "registry = http://localhost:1337/") +fs.writeFileSync(pkg + '/fixture_npmrc', + '//localhost:1337/:email = fancy@feast.net\n' + + '//localhost:1337/:username = fancy\n' + + '//localhost:1337/:_password = ' + new Buffer('feast').toString('base64') + '\n' + + 'registry = http://localhost:1337/') test(function (t) { var child t.plan(4) - require("http").createServer(function (req, res) { - t.pass("got request on the fakey fake registry") + require('http').createServer(function (req, res) { + t.pass('got request on the fakey fake registry') this.close() res.statusCode = 500 res.end(JSON.stringify({ - error: "sshhh. naptime nao. \\^O^/ <(YAWWWWN!)" + error: 'sshhh. naptime nao. \\^O^/ <(YAWWWWN!)' })) child.kill('SIGHUP') }).listen(common.port, function () { - t.pass("server is listening") + t.pass('server is listening') // don't much care about listening to the child's results // just wanna make sure it hits the server we just set up. @@ -40,20 +40,20 @@ test(function (t) { // itself functions normally. // // Make sure that we don't sit around waiting for lock files - child = common.npm(["publish", "--userconfig=" + pkg + "/fixture_npmrc"], { + child = common.npm(['publish', '--userconfig=' + pkg + '/fixture_npmrc'], { cwd: pkg, - stdio: "inherit", + stdio: 'inherit', env: { - "npm_config_cache_lock_stale": 1000, - "npm_config_cache_lock_wait": 1000, + 'npm_config_cache_lock_stale': 1000, + 'npm_config_cache_lock_wait': 1000, HOME: process.env.HOME, Path: process.env.PATH, PATH: process.env.PATH, USERPROFILE: osenv.home() } }, function (err, code) { - t.ifError(err, "publish command finished successfully") - t.notOk(code, "npm install exited with code 0") + t.ifError(err, 'publish command finished successfully') + t.notOk(code, 'npm install exited with code 0') }) }) }) diff --git a/test/tap/publish-scoped.js b/test/tap/publish-scoped.js index f74ca2e61..eb14ae504 100644 --- a/test/tap/publish-scoped.js +++ b/test/tap/publish-scoped.js @@ -1,60 +1,60 @@ -var fs = require("fs") -var path = require("path") +var fs = require('fs') +var path = require('path') -var test = require("tap").test -var mkdirp = require("mkdirp") -var rimraf = require("rimraf") -var nock = require("nock") +var test = require('tap').test +var mkdirp = require('mkdirp') +var rimraf = require('rimraf') +var nock = require('nock') -var npm = require("../../") -var common = require("../common-tap.js") +var npm = require('../../') +var common = require('../common-tap.js') -var pkg = path.join(__dirname, "prepublish_package") +var pkg = path.join(__dirname, 'prepublish_package') -test("setup", function (t) { - mkdirp(path.join(pkg, "cache"), next) +test('setup', function (t) { + mkdirp(path.join(pkg, 'cache'), next) function next () { process.chdir(pkg) fs.writeFile( - path.join(pkg, "package.json"), + path.join(pkg, 'package.json'), JSON.stringify({ - name: "@bigco/publish-organized", - version: "1.2.5" + name: '@bigco/publish-organized', + version: '1.2.5' }), - "ascii", + 'ascii', function (er) { t.ifError(er) - t.pass("setup done") + t.pass('setup done') t.end() } ) } }) -test("npm publish should honor scoping", function (t) { +test('npm publish should honor scoping', function (t) { var put = nock(common.registry) - .put("/@bigco%2fpublish-organized") + .put('/@bigco%2fpublish-organized') .reply(201, verify) var configuration = { - cache : path.join(pkg, "cache"), - loglevel : "silent", - registry : "http://nonexistent.lvh.me", - "//localhost:1337/:username" : "username", - "//localhost:1337/:_password" : new Buffer("password").toString("base64"), - "//localhost:1337/:email" : "ogd@aoaioxxysz.net" + cache: path.join(pkg, 'cache'), + loglevel: 'silent', + registry: 'http://nonexistent.lvh.me', + '//localhost:1337/:username': 'username', + '//localhost:1337/:_password': new Buffer('password').toString('base64'), + '//localhost:1337/:email': 'ogd@aoaioxxysz.net' } npm.load(configuration, onload) function onload (er) { - t.ifError(er, "npm bootstrapped successfully") + t.ifError(er, 'npm bootstrapped successfully') - npm.config.set("@bigco:registry", common.registry) + npm.config.set('@bigco:registry', common.registry) npm.commands.publish([], false, function (er) { - t.ifError(er, "published without error") + t.ifError(er, 'published without error') put.done() @@ -65,25 +65,25 @@ test("npm publish should honor scoping", function (t) { function verify (_, body) { t.doesNotThrow(function () { var parsed = JSON.parse(body) - var current = parsed.versions["1.2.5"] + var current = parsed.versions['1.2.5'] t.equal( current._npmVersion, - require(path.resolve(__dirname, "../../package.json")).version, - "npm version is correct" + require(path.resolve(__dirname, '../../package.json')).version, + 'npm version is correct' ) t.equal( current._nodeVersion, process.versions.node, - "node version is correct" + 'node version is correct' ) - }, "converted body back into object") + }, 'converted body back into object') return {ok: true} } }) -test("cleanup", function (t) { +test('cleanup', function (t) { process.chdir(__dirname) rimraf(pkg, function (er) { t.ifError(er) diff --git a/test/tap/pwd-prefix.js b/test/tap/pwd-prefix.js index 237096e0a..1b59f5c83 100644 --- a/test/tap/pwd-prefix.js +++ b/test/tap/pwd-prefix.js @@ -2,31 +2,31 @@ // thing when the cwd is where package.json is, and when // the package.json is one level up. -var test = require("tap").test -var common = require("../common-tap.js") -var path = require("path") -var root = path.resolve(__dirname, "../..") -var lib = path.resolve(root, "lib") -var commands = ["run", "version"] +var test = require('tap').test +var common = require('../common-tap.js') +var path = require('path') +var root = path.resolve(__dirname, '../..') +var lib = path.resolve(root, 'lib') +var commands = ['run', 'version'] commands.forEach(function (cmd) { // Should get the same stdout and stderr each time var stdout, stderr - test(cmd + " in root", function (t) { + test(cmd + ' in root', function (t) { common.npm([cmd], {cwd: root}, function (er, code, so, se) { if (er) throw er - t.notOk(code, "npm " + cmd + " exited with code 0") + t.notOk(code, 'npm ' + cmd + ' exited with code 0') stdout = so stderr = se t.end() }) }) - test(cmd + " in lib", function (t) { + test(cmd + ' in lib', function (t) { common.npm([cmd], {cwd: lib}, function (er, code, so, se) { if (er) throw er - t.notOk(code, "npm " + cmd + " exited with code 0") + t.notOk(code, 'npm ' + cmd + ' exited with code 0') t.equal(so, stdout) t.equal(se, stderr) t.end() diff --git a/test/tap/referer.js b/test/tap/referer.js index c1b173d97..8c3dbed72 100644 --- a/test/tap/referer.js +++ b/test/tap/referer.js @@ -1,16 +1,16 @@ -var common = require("../common-tap.js") -var test = require("tap").test -var http = require("http") +var common = require('../common-tap.js') +var test = require('tap').test +var http = require('http') -test("should send referer http header", function (t) { +test('should send referer http header', function (t) { http.createServer(function (q, s) { - t.equal(q.headers.referer, "install foo") + t.equal(q.headers.referer, 'install foo') s.statusCode = 404 - s.end(JSON.stringify({error: "whatever"})) + s.end(JSON.stringify({error: 'whatever'})) this.close() }).listen(common.port, function () { - var reg = "http://localhost:" + common.port - var args = [ "install", "foo", "--registry", reg ] + var reg = 'http://localhost:' + common.port + var args = [ 'install', 'foo', '--registry', reg ] common.npm(args, {}, function (er, code) { if (er) { throw er diff --git a/test/tap/registry.js b/test/tap/registry.js index 060d9b67b..7ff4075bf 100644 --- a/test/tap/registry.js +++ b/test/tap/registry.js @@ -1,34 +1,31 @@ // Run all the tests in the `npm-registry-couchapp` suite // This verifies that the server-side stuff still works. -var common = require("../common-tap") -var test = require("tap").test +var common = require('../common-tap') +var test = require('tap').test -var npmExec = require.resolve("../../bin/npm-cli.js") -var path = require("path") -var ca = path.resolve(__dirname, "../../node_modules/npm-registry-couchapp") +var npmExec = require.resolve('../../bin/npm-cli.js') +var path = require('path') +var ca = path.resolve(__dirname, '../../node_modules/npm-registry-couchapp') -var which = require("which") +var which = require('which') -var v = process.versions.node.split(".").map(function (n) { return parseInt(n, 10) }) +var v = process.versions.node.split('.').map(function (n) { return parseInt(n, 10) }) if (v[0] === 0 && v[1] < 10) { console.error( - "WARNING: need a recent Node for npm-registry-couchapp tests to run, have", + 'WARNING: need a recent Node for npm-registry-couchapp tests to run, have', process.versions.node ) -} -else { - which("couchdb", function (er) { +} else { + which('couchdb', function (er) { if (er) { - console.error("WARNING: need couch to run test: " + er.message) - } - else { + console.error('WARNING: need couch to run test: ' + er.message) + } else { runTests() } }) } - function runTests () { var env = { TAP: 1 } for (var i in process.env) env[i] = process.env[i] @@ -36,13 +33,13 @@ function runTests () { var opts = { cwd: ca, - stdio: "inherit" + stdio: 'inherit' } - common.npm(["install"], opts, function (err, code) { + common.npm(['install'], opts, function (err, code) { if (err) { throw err } if (code) { - return test("need install to work", function (t) { - t.fail("install failed with: " + code) + return test('need install to work', function (t) { + t.fail('install failed with: ' + code) t.end() }) @@ -50,22 +47,22 @@ function runTests () { opts = { cwd: ca, env: env, - stdio: "inherit" + stdio: 'inherit' } - common.npm(["test", "--", "-Rtap"], opts, function (err, code) { + common.npm(['test', '--', '-Rtap'], opts, function (err, code) { if (err) { throw err } if (code) { - return test("need test to work", function (t) { - t.fail("test failed with: " + code) + return test('need test to work', function (t) { + t.fail('test failed with: ' + code) t.end() }) } opts = { cwd: ca, env: env, - stdio: "inherit" + stdio: 'inherit' } - common.npm(["prune", "--production"], opts, function (err, code) { + common.npm(['prune', '--production'], opts, function (err, code) { if (err) { throw err } process.exit(code || 0) }) diff --git a/test/tap/repo.js b/test/tap/repo.js index df4e67410..292415705 100644 --- a/test/tap/repo.js +++ b/test/tap/repo.js @@ -1,76 +1,75 @@ -if (process.platform === "win32") { - console.error("skipping test, because windows and shebangs") - return +if (process.platform === 'win32') { + console.error('skipping test, because windows and shebangs') + process.exit(0) } -var common = require("../common-tap.js") -var mr = require("npm-registry-mock") +var common = require('../common-tap.js') +var mr = require('npm-registry-mock') -var test = require("tap").test -var npm = require.resolve("../../bin/npm-cli.js") -var node = process.execPath -var rimraf = require("rimraf") -var spawn = require("child_process").spawn -var fs = require("fs") +var test = require('tap').test +var rimraf = require('rimraf') +var fs = require('fs') var path = require('path') var outFile = path.join(__dirname, '/_output') var opts = { cwd: __dirname } -test("setup", function (t) { - var s = "#!/usr/bin/env bash\n" + - "echo \"$@\" > " + JSON.stringify(__dirname) + "/_output\n" - fs.writeFileSync(__dirname + "/_script.sh", s, "ascii") - fs.chmodSync(__dirname + "/_script.sh", "0755") - t.pass("made script") +test('setup', function (t) { + var s = '#!/usr/bin/env bash\n' + + 'echo \"$@\" > ' + JSON.stringify(__dirname) + '/_output\n' + fs.writeFileSync(__dirname + '/_script.sh', s, 'ascii') + fs.chmodSync(__dirname + '/_script.sh', '0755') + t.pass('made script') t.end() }) -test("npm repo underscore", function (t) { - mr({port : common.port}, function (er, s) { +test('npm repo underscore', function (t) { + mr({ port: common.port }, function (er, s) { common.npm([ 'repo', 'underscore', '--registry=' + common.registry, '--loglevel=silent', '--browser=' + __dirname + '/_script.sh' ], opts, function (err, code, stdout, stderr) { + t.ifError(err, 'repo command ran without error') t.equal(code, 0, 'exit ok') var res = fs.readFileSync(outFile, 'ascii') s.close() - t.equal(res, "https://github.com/jashkenas/underscore\n") + t.equal(res, 'https://github.com/jashkenas/underscore\n') rimraf.sync(outFile) t.end() }) }) }) - test('npm repo optimist - github (https://)', function (t) { - mr({port : common.port}, function (er, s) { + mr({ port: common.port }, function (er, s) { common.npm([ 'repo', 'optimist', '--registry=' + common.registry, '--loglevel=silent', '--browser=' + __dirname + '/_script.sh' ], opts, function (err, code, stdout, stderr) { + t.ifError(err, 'repo command ran without error') t.equal(code, 0, 'exit ok') var res = fs.readFileSync(outFile, 'ascii') s.close() - t.equal(res, "https://github.com/substack/node-optimist\n") + t.equal(res, 'https://github.com/substack/node-optimist\n') rimraf.sync(outFile) t.end() }) }) }) -test("npm repo npm-test-peer-deps - no repo", function (t) { - mr({port : common.port}, function (er, s) { +test('npm repo npm-test-peer-deps - no repo', function (t) { + mr({ port: common.port }, function (er, s) { common.npm([ 'repo', 'npm-test-peer-deps', '--registry=' + common.registry, '--loglevel=silent', '--browser=' + __dirname + '/_script.sh' ], opts, function (err, code, stdout, stderr) { + t.ifError(err, 'repo command ran without error') t.equal(code, 1, 'exit not ok') s.close() t.end() @@ -78,62 +77,65 @@ test("npm repo npm-test-peer-deps - no repo", function (t) { }) }) -test("npm repo test-repo-url-http - non-github (http://)", function (t) { - mr({port : common.port}, function (er, s) { +test('npm repo test-repo-url-http - non-github (http://)', function (t) { + mr({ port: common.port }, function (er, s) { common.npm([ 'repo', 'test-repo-url-http', '--registry=' + common.registry, '--loglevel=silent', '--browser=' + __dirname + '/_script.sh' ], opts, function (err, code, stdout, stderr) { + t.ifError(err, 'repo command ran without error') t.equal(code, 0, 'exit ok') var res = fs.readFileSync(outFile, 'ascii') s.close() - t.equal(res, "http://gitlab.com/evanlucas/test-repo-url-http\n") + t.equal(res, 'http://gitlab.com/evanlucas/test-repo-url-http\n') rimraf.sync(outFile) t.end() }) }) }) -test("npm repo test-repo-url-https - non-github (https://)", function (t) { - mr({port : common.port}, function (er, s) { +test('npm repo test-repo-url-https - non-github (https://)', function (t) { + mr({ port: common.port }, function (er, s) { common.npm([ 'repo', 'test-repo-url-https', '--registry=' + common.registry, '--loglevel=silent', '--browser=' + __dirname + '/_script.sh' ], opts, function (err, code, stdout, stderr) { + t.ifError(err, 'repo command ran without error') t.equal(code, 0, 'exit ok') var res = fs.readFileSync(outFile, 'ascii') s.close() - t.equal(res, "https://gitlab.com/evanlucas/test-repo-url-https\n") + t.equal(res, 'https://gitlab.com/evanlucas/test-repo-url-https\n') rimraf.sync(outFile) t.end() }) }) }) -test("npm repo test-repo-url-ssh - non-github (ssh://)", function (t) { - mr({port : common.port}, function (er, s) { +test('npm repo test-repo-url-ssh - non-github (ssh://)', function (t) { + mr({ port: common.port }, function (er, s) { common.npm([ 'repo', 'test-repo-url-ssh', '--registry=' + common.registry, '--loglevel=silent', '--browser=' + __dirname + '/_script.sh' ], opts, function (err, code, stdout, stderr) { + t.ifError(err, 'repo command ran without error') t.equal(code, 0, 'exit ok') var res = fs.readFileSync(outFile, 'ascii') s.close() - t.equal(res, "https://gitlab.com/evanlucas/test-repo-url-ssh\n") + t.equal(res, 'https://gitlab.com/evanlucas/test-repo-url-ssh\n') rimraf.sync(outFile) t.end() }) }) }) -test("cleanup", function (t) { - fs.unlinkSync(__dirname + "/_script.sh") - t.pass("cleaned up") +test('cleanup', function (t) { + fs.unlinkSync(__dirname + '/_script.sh') + t.pass('cleaned up') t.end() }) diff --git a/test/tap/run-script.js b/test/tap/run-script.js index 8dfe574e1..9c1d5d1f5 100644 --- a/test/tap/run-script.js +++ b/test/tap/run-script.js @@ -54,15 +54,14 @@ var both = { } } - function testOutput (t, command, er, code, stdout, stderr) { var lines - if (er) - throw er + if (er) throw er - if (stderr) + if (stderr) { throw new Error('npm ' + command + ' stderr: ' + stderr.toString()) + } lines = stdout.trim().split('\n') stdout = lines.filter(function (line) { diff --git a/test/tap/semver-doc.js b/test/tap/semver-doc.js index 963cace10..31c75fffd 100644 --- a/test/tap/semver-doc.js +++ b/test/tap/semver-doc.js @@ -1,12 +1,12 @@ -var test = require("tap").test +var test = require('tap').test -test("semver doc is up to date", function (t) { - var path = require("path") - var moddoc = path.join(__dirname, "../../node_modules/semver/README.md") - var mydoc = path.join(__dirname, "../../doc/misc/semver.md") - var fs = require("fs") - var mod = fs.readFileSync(moddoc, "utf8").replace(/semver\(1\)/, "semver(7)") - var my = fs.readFileSync(mydoc, "utf8") +test('semver doc is up to date', function (t) { + var path = require('path') + var moddoc = path.join(__dirname, '../../node_modules/semver/README.md') + var mydoc = path.join(__dirname, '../../doc/misc/semver.md') + var fs = require('fs') + var mod = fs.readFileSync(moddoc, 'utf8').replace(/semver\(1\)/, 'semver(7)') + var my = fs.readFileSync(mydoc, 'utf8') t.equal(my, mod) t.end() }) diff --git a/test/tap/semver-tag.js b/test/tap/semver-tag.js index 03dcdf85b..b4feb7517 100644 --- a/test/tap/semver-tag.js +++ b/test/tap/semver-tag.js @@ -1,11 +1,11 @@ // should not allow tagging with a valid semver range -var common = require("../common-tap.js") -var test = require("tap").test +var common = require('../common-tap.js') +var test = require('tap').test -test("try to tag with semver range as tag name", function (t) { - var cmd = ["tag", "zzzz@1.2.3", "v2.x", "--registry=http://localhost"] +test('try to tag with semver range as tag name', function (t) { + var cmd = ['tag', 'zzzz@1.2.3', 'v2.x', '--registry=http://localhost'] common.npm(cmd, { - stdio: "pipe" + stdio: 'pipe' }, function (er, code, so, se) { if (er) throw er t.similar(se, /Tag name must not be a valid SemVer range: v2.x\n/) diff --git a/test/tap/shrinkwrap-local-dependency.js b/test/tap/shrinkwrap-local-dependency.js index ffbde6574..8d7c0712f 100644 --- a/test/tap/shrinkwrap-local-dependency.js +++ b/test/tap/shrinkwrap-local-dependency.js @@ -1,63 +1,62 @@ -var test = require("tap").test -var path = require("path") -var fs = require("fs") -var osenv = require("osenv") -var rimraf = require("rimraf") -var mkdirp = require("mkdirp") -var common = require("../common-tap.js") - -var PKG_DIR = path.resolve(__dirname, "shrinkwrap-local-dependency") -var CACHE_DIR = path.resolve(PKG_DIR, "cache") -var DEP_DIR = path.resolve(PKG_DIR, "dep") +var test = require('tap').test +var path = require('path') +var fs = require('fs') +var osenv = require('osenv') +var rimraf = require('rimraf') +var mkdirp = require('mkdirp') +var common = require('../common-tap.js') + +var PKG_DIR = path.resolve(__dirname, 'shrinkwrap-local-dependency') +var CACHE_DIR = path.resolve(PKG_DIR, 'cache') +var DEP_DIR = path.resolve(PKG_DIR, 'dep') var desired = { - "name": "npm-test-shrinkwrap-local-dependency", - "version": "0.0.0", - "dependencies": { - "npm-test-shrinkwrap-local-dependency-dep": { - "version": "0.0.0", - "from": "dep", - "resolved": "file:dep" + 'name': 'npm-test-shrinkwrap-local-dependency', + 'version': '0.0.0', + 'dependencies': { + 'npm-test-shrinkwrap-local-dependency-dep': { + 'version': '0.0.0', + 'from': 'dep', + 'resolved': 'file:dep' } } } var root = { - "author": "Thomas Torp", - "name": "npm-test-shrinkwrap-local-dependency", - "version": "0.0.0", - "dependencies": { - "npm-test-shrinkwrap-local-dependency-dep": "file:./dep" + 'author': 'Thomas Torp', + 'name': 'npm-test-shrinkwrap-local-dependency', + 'version': '0.0.0', + 'dependencies': { + 'npm-test-shrinkwrap-local-dependency-dep': 'file:./dep' } } var dependency = { - "author": "Thomas Torp", - "name": "npm-test-shrinkwrap-local-dependency-dep", - "version": "0.0.0" + 'author': 'Thomas Torp', + 'name': 'npm-test-shrinkwrap-local-dependency-dep', + 'version': '0.0.0' } - -test("shrinkwrap uses resolved with file: on local deps", function(t) { +test('shrinkwrap uses resolved with file: on local deps', function (t) { setup() common.npm( - ["--cache="+CACHE_DIR, "--loglevel=silent", "install", "."], + ['--cache=' + CACHE_DIR, '--loglevel=silent', 'install', '.'], {}, function (err, code) { - t.ifError(err, "npm install worked") - t.equal(code, 0, "npm exited normally") + t.ifError(err, 'npm install worked') + t.equal(code, 0, 'npm exited normally') common.npm( - ["--cache="+CACHE_DIR, "--loglevel=silent", "shrinkwrap"], + ['--cache=' + CACHE_DIR, '--loglevel=silent', 'shrinkwrap'], {}, function (err, code) { - t.ifError(err, "npm shrinkwrap worked") - t.equal(code, 0, "npm exited normally") + t.ifError(err, 'npm shrinkwrap worked') + t.equal(code, 0, 'npm exited normally') - fs.readFile("npm-shrinkwrap.json", { encoding : "utf8" }, function (err, data) { - t.ifError(err, "read file correctly") - t.deepEqual(JSON.parse(data), desired, "shrinkwrap looks correct") + fs.readFile('npm-shrinkwrap.json', { encoding: 'utf8' }, function (err, data) { + t.ifError(err, 'read file correctly') + t.deepEqual(JSON.parse(data), desired, 'shrinkwrap looks correct') t.end() }) @@ -67,22 +66,22 @@ test("shrinkwrap uses resolved with file: on local deps", function(t) { ) }) -test('"npm install" should install local packages from shrinkwrap', function (t) { +test("'npm install' should install local packages from shrinkwrap", function (t) { cleanNodeModules() common.npm( - ["--cache="+CACHE_DIR, "--loglevel=silent", "install", "."], + ['--cache=' + CACHE_DIR, '--loglevel=silent', 'install', '.'], {}, function (err, code) { - t.ifError(err, "install ran correctly") - t.notOk(code, "npm install exited with code 0") + t.ifError(err, 'install ran correctly') + t.notOk(code, 'npm install exited with code 0') var dependencyPackageJson = path.resolve( PKG_DIR, - "node_modules/npm-test-shrinkwrap-local-dependency-dep/package.json" + 'node_modules/npm-test-shrinkwrap-local-dependency-dep/package.json' ) t.ok( - JSON.parse(fs.readFileSync(dependencyPackageJson, "utf8")), - "package with local dependency installed from shrinkwrap" + JSON.parse(fs.readFileSync(dependencyPackageJson, 'utf8')), + 'package with local dependency installed from shrinkwrap' ) t.end() @@ -90,32 +89,32 @@ test('"npm install" should install local packages from shrinkwrap', function (t) ) }) -test("cleanup", function(t) { +test('cleanup', function (t) { cleanup() t.end() }) -function setup() { +function setup () { cleanup() mkdirp.sync(PKG_DIR) mkdirp.sync(CACHE_DIR) mkdirp.sync(DEP_DIR) fs.writeFileSync( - path.resolve(PKG_DIR, "package.json"), + path.resolve(PKG_DIR, 'package.json'), JSON.stringify(root, null, 2) ) fs.writeFileSync( - path.resolve(DEP_DIR, "package.json"), + path.resolve(DEP_DIR, 'package.json'), JSON.stringify(dependency, null, 2) ) process.chdir(PKG_DIR) } -function cleanNodeModules() { - rimraf.sync(path.resolve(PKG_DIR, "node_modules")) +function cleanNodeModules () { + rimraf.sync(path.resolve(PKG_DIR, 'node_modules')) } -function cleanup() { +function cleanup () { process.chdir(osenv.tmpdir()) cleanNodeModules() rimraf.sync(PKG_DIR) diff --git a/test/tap/shrinkwrap-scoped-auth.js b/test/tap/shrinkwrap-scoped-auth.js index 81b205d2e..8fe0d1e23 100644 --- a/test/tap/shrinkwrap-scoped-auth.js +++ b/test/tap/shrinkwrap-scoped-auth.js @@ -1,68 +1,66 @@ -var resolve = require("path").resolve -var writeFileSync = require("graceful-fs").writeFileSync - -var mkdirp = require("mkdirp") -var mr = require("npm-registry-mock") -var osenv = require("osenv") -var rimraf = require("rimraf") -var test = require("tap").test - -var common = require("../common-tap.js") -var toNerfDart = require("../../lib/config/nerf-dart.js") - -var pkg = resolve(__dirname, "shrinkwrap-scoped-auth") -var outfile = resolve(pkg, "_npmrc") -var modules = resolve(pkg, "node_modules") -var tarballPath = "/scoped-underscore/-/scoped-underscore-1.3.1.tgz" +var resolve = require('path').resolve +var writeFileSync = require('graceful-fs').writeFileSync + +var mkdirp = require('mkdirp') +var mr = require('npm-registry-mock') +var osenv = require('osenv') +var rimraf = require('rimraf') +var test = require('tap').test + +var common = require('../common-tap.js') +var toNerfDart = require('../../lib/config/nerf-dart.js') + +var pkg = resolve(__dirname, 'shrinkwrap-scoped-auth') +var outfile = resolve(pkg, '_npmrc') +var modules = resolve(pkg, 'node_modules') +var tarballPath = '/scoped-underscore/-/scoped-underscore-1.3.1.tgz' var tarballURL = common.registry + tarballPath -var tarball = resolve(__dirname, "../fixtures/scoped-underscore-1.3.1.tgz") +var tarball = resolve(__dirname, '../fixtures/scoped-underscore-1.3.1.tgz') var server -var EXEC_OPTS = { - cwd : pkg -} +var EXEC_OPTS = { cwd: pkg } function mocks (server) { - var auth = "Bearer 0xabad1dea" - server.get(tarballPath, { authorization : auth }).replyWithFile(200, tarball) + var auth = 'Bearer 0xabad1dea' + server.get(tarballPath, { authorization: auth }).replyWithFile(200, tarball) server.get(tarballPath).reply(401, { - error : "unauthorized", - reason : "You are not authorized to access this db." + error: 'unauthorized', + reason: 'You are not authorized to access this db.' }) } -test("setup", function (t) { - mr({ port : common.port, plugin : mocks }, function (err, s) { +test('setup', function (t) { + mr({ port: common.port, plugin: mocks }, function (er, s) { server = s - t.ok(s, "set up mock registry") + t.ok(s, 'set up mock registry') setup() t.end() }) }) -test("authed npm install with shrinkwrapped scoped package", function (t) { +test('authed npm install with shrinkwrapped scoped package', function (t) { common.npm( [ - "install", - "--loglevel", "silent", - "--json", - "--fetch-retries", 0, - "--userconfig", outfile + 'install', + '--loglevel', 'silent', + '--json', + '--fetch-retries', 0, + '--userconfig', outfile ], EXEC_OPTS, function (err, code, stdout, stderr) { console.error(stderr) - t.ifError(err, "test runner executed without error") - t.equal(code, 0, "npm install exited OK") - t.notOk(stderr, "no output on stderr") + t.ifError(err, 'test runner executed without error') + t.equal(code, 0, 'npm install exited OK') + t.notOk(stderr, 'no output on stderr') try { var results = JSON.parse(stdout) - } - catch (ex) { + } catch (ex) { console.error('#', ex) - t.ifError(ex, "stdout was valid JSON") + t.ifError(ex, 'stdout was valid JSON') } + if (results) { var installedversion = { 'version': '1.3.1', @@ -77,28 +75,28 @@ test("authed npm install with shrinkwrapped scoped package", function (t) { ) }) -test("cleanup", function (t) { +test('cleanup', function (t) { server.close() cleanup() t.end() }) -var contents = "@scoped:registry="+common.registry+"\n" + - toNerfDart(common.registry)+":_authToken=0xabad1dea\n" +var contents = '@scoped:registry=' + common.registry + '\n' + + toNerfDart(common.registry) + ':_authToken=0xabad1dea\n' var json = { - name : "test-package-install", - version : "1.0.0" + name: 'test-package-install', + version: '1.0.0' } var shrinkwrap = { - name : "test-package-install", - version : "1.0.0", - dependencies : { - "@scoped/underscore" : { - resolved : tarballURL, - from : ">=1.3.1 <2", - version : "1.3.1" + name: 'test-package-install', + version: '1.0.0', + dependencies: { + '@scoped/underscore': { + resolved: tarballURL, + from: '>=1.3.1 <2', + version: '1.3.1' } } } @@ -106,15 +104,15 @@ var shrinkwrap = { function setup () { cleanup() mkdirp.sync(modules) - writeFileSync(resolve(pkg, "package.json"), JSON.stringify(json, null, 2)+"\n") + writeFileSync(resolve(pkg, 'package.json'), JSON.stringify(json, null, 2) + '\n') writeFileSync(outfile, contents) writeFileSync( - resolve(pkg, "npm-shrinkwrap.json"), - JSON.stringify(shrinkwrap, null, 2)+"\n" + resolve(pkg, 'npm-shrinkwrap.json'), + JSON.stringify(shrinkwrap, null, 2) + '\n' ) } -function cleanup() { +function cleanup () { process.chdir(osenv.tmpdir()) rimraf.sync(pkg) } diff --git a/test/tap/sorted-package-json.js b/test/tap/sorted-package-json.js index 6853cf302..9b2e93592 100644 --- a/test/tap/sorted-package-json.js +++ b/test/tap/sorted-package-json.js @@ -1,21 +1,20 @@ -var test = require("tap").test - , path = require("path") - , rimraf = require("rimraf") - , mkdirp = require("mkdirp") - , spawn = require("child_process").spawn - , npm = require.resolve("../../bin/npm-cli.js") - , node = process.execPath - , pkg = path.resolve(__dirname, "sorted-package-json") - , tmp = path.join(pkg, "tmp") - , cache = path.join(pkg, "cache") - , fs = require("fs") - , common = require("../common-tap.js") - , mr = require("npm-registry-mock") - , osenv = require("osenv") +var test = require('tap').test +var path = require('path') +var rimraf = require('rimraf') +var mkdirp = require('mkdirp') +var spawn = require('child_process').spawn +var npm = require.resolve('../../bin/npm-cli.js') +var node = process.execPath +var pkg = path.resolve(__dirname, 'sorted-package-json') +var tmp = path.join(pkg, 'tmp') +var cache = path.join(pkg, 'cache') +var fs = require('fs') +var common = require('../common-tap.js') +var mr = require('npm-registry-mock') +var osenv = require('osenv') - -test("sorting dependencies", function (t) { - var packageJson = path.resolve(pkg, "package.json") +test('sorting dependencies', function (t) { + var packageJson = path.resolve(pkg, 'package.json') cleanup() mkdirp.sync(cache) @@ -24,27 +23,27 @@ test("sorting dependencies", function (t) { var before = JSON.parse(fs.readFileSync(packageJson).toString()) - mr({port : common.port}, function (er, s) { + mr({ port: common.port }, function (er, s) { // underscore is already in the package.json, // but --save will trigger a rewrite with sort - var child = spawn(node, [npm, "install", "--save", "underscore@1.3.3"], { + var child = spawn(node, [npm, 'install', '--save', 'underscore@1.3.3'], { cwd: pkg, env: { - "npm_config_registry": common.registry, - "npm_config_cache": cache, - "npm_config_tmp": tmp, - "npm_config_prefix": pkg, - "npm_config_global": "false", + 'npm_config_registry': common.registry, + 'npm_config_cache': cache, + 'npm_config_tmp': tmp, + 'npm_config_prefix': pkg, + 'npm_config_global': 'false', HOME: process.env.HOME, Path: process.env.PATH, PATH: process.env.PATH } }) - child.on("close", function (code) { - t.equal(code, 0, "npm install exited with code") + child.on('close', function (code) { + t.equal(code, 0, 'npm install exited with code') var result = fs.readFileSync(packageJson).toString() - , resultAsJson = JSON.parse(result) + var resultAsJson = JSON.parse(result) s.close() @@ -61,33 +60,33 @@ test("sorting dependencies", function (t) { }) }) -test("cleanup", function (t) { +test('cleanup', function (t) { cleanup() - t.pass("cleaned up") + t.pass('cleaned up') t.end() }) -function setup() { +function setup () { mkdirp.sync(pkg) - fs.writeFileSync(path.resolve(pkg, "package.json"), JSON.stringify({ - "name": "sorted-package-json", - "version": "0.0.0", - "description": "", - "main": "index.js", - "scripts": { - "test": "echo \"Error: no test specified\" && exit 1" + fs.writeFileSync(path.resolve(pkg, 'package.json'), JSON.stringify({ + 'name': 'sorted-package-json', + 'version': '0.0.0', + 'description': '', + 'main': 'index.js', + 'scripts': { + 'test': 'echo \'Error: no test specified\' && exit 1' }, - "author": "Rocko Artischocko", - "license": "ISC", - "dependencies": { - "underscore": "^1.3.3", - "request": "^0.9.0" + 'author': 'Rocko Artischocko', + 'license': 'ISC', + 'dependencies': { + 'underscore': '^1.3.3', + 'request': '^0.9.0' } - }, null, 2), "utf8") + }, null, 2), 'utf8') } -function cleanup() { +function cleanup () { process.chdir(osenv.tmpdir()) rimraf.sync(cache) rimraf.sync(pkg) diff --git a/test/tap/spawn-enoent-help.js b/test/tap/spawn-enoent-help.js index 70fb078fa..716f6ebd1 100644 --- a/test/tap/spawn-enoent-help.js +++ b/test/tap/spawn-enoent-help.js @@ -1,25 +1,25 @@ -var path = require("path") -var test = require("tap").test -var rimraf = require("rimraf") -var mkdirp = require("mkdirp") -var common = require("../common-tap.js") +var path = require('path') +var test = require('tap').test +var rimraf = require('rimraf') +var mkdirp = require('mkdirp') +var common = require('../common-tap.js') -var pkg = path.resolve(__dirname, "spawn-enoent-help") +var pkg = path.resolve(__dirname, 'spawn-enoent-help') -test("setup", function (t) { +test('setup', function (t) { rimraf.sync(pkg) mkdirp.sync(pkg) t.end() }) -test("enoent help", function (t) { - common.npm(["help", "config"], { +test('enoent help', function (t) { + common.npm(['help', 'config'], { cwd: pkg, env: { - PATH: "", - Path: "", - "npm_config_loglevel": "warn", - "npm_config_viewer": "woman" + PATH: '', + Path: '', + 'npm_config_loglevel': 'warn', + 'npm_config_viewer': 'woman' } }, function (er, code, sout, serr) { t.similar(serr, /Check if the file 'emacsclient' is present./) @@ -28,7 +28,7 @@ test("enoent help", function (t) { }) }) -test("clean", function (t) { +test('clean', function (t) { rimraf.sync(pkg) t.end() }) diff --git a/test/tap/spawn-enoent.js b/test/tap/spawn-enoent.js index 29b70f6f8..320e477e0 100644 --- a/test/tap/spawn-enoent.js +++ b/test/tap/spawn-enoent.js @@ -1,32 +1,31 @@ -var path = require("path") -var test = require("tap").test -var fs = require("fs") -var rimraf = require("rimraf") -var mkdirp = require("mkdirp") -var common = require("../common-tap.js") +var path = require('path') +var test = require('tap').test +var fs = require('fs') +var rimraf = require('rimraf') +var mkdirp = require('mkdirp') +var common = require('../common-tap.js') -var pkg = path.resolve(__dirname, "spawn-enoent") +var pkg = path.resolve(__dirname, 'spawn-enoent') var pj = JSON.stringify({ - name:"x", - version: "1.2.3", - scripts: { start: "wharble-garble-blorst" } -}, null, 2) + "\n" + name: 'x', + version: '1.2.3', + scripts: { start: 'wharble-garble-blorst' } +}, null, 2) + '\n' - -test("setup", function (t) { +test('setup', function (t) { rimraf.sync(pkg) mkdirp.sync(pkg) - fs.writeFileSync(pkg + "/package.json", pj) + fs.writeFileSync(pkg + '/package.json', pj) t.end() }) -test("enoent script", function (t) { - common.npm(["start"], { +test('enoent script', function (t) { + common.npm(['start'], { cwd: pkg, env: { PATH: process.env.PATH, Path: process.env.Path, - "npm_config_loglevel": "warn" + 'npm_config_loglevel': 'warn' } }, function (er, code, sout, serr) { t.similar(serr, /npm ERR! Failed at the x@1\.2\.3 start script 'wharble-garble-blorst'\./) @@ -34,7 +33,7 @@ test("enoent script", function (t) { }) }) -test("clean", function (t) { +test('clean', function (t) { rimraf.sync(pkg) t.end() }) diff --git a/test/tap/tag-version-prefix.js b/test/tap/tag-version-prefix.js index efd2d14d4..e137c1771 100644 --- a/test/tap/tag-version-prefix.js +++ b/test/tap/tag-version-prefix.js @@ -19,70 +19,72 @@ var json = { name: 'blah', version: '0.1.2' } var configContents = 'sign-git-tag=false\nmessage=":bookmark: %s"\n' test('npm version <semver> with message config', function (t) { - setup() - - npm.load({ prefix: pkg, userconfig: npmrc }, function () { - var git = require('../../lib/utils/git.js') - - common.makeGitRepo({ path: pkg }, function (er) { - t.ifErr(er, 'git bootstrap ran without error') - - common.npm([ - 'config', - 'set', - 'tag-version-prefix', - 'q' - ], { cwd: pkg, env: { PATH: process.env.PATH } }, + setup() + + npm.load({ prefix: pkg, userconfig: npmrc }, function () { + var git = require('../../lib/utils/git.js') + + common.makeGitRepo({ path: pkg }, function (er) { + t.ifErr(er, 'git bootstrap ran without error') + + common.npm( + [ + 'config', + 'set', + 'tag-version-prefix', + 'q' + ], + { cwd: pkg, env: { PATH: process.env.PATH } }, + function (err, code, stdout, stderr) { + t.ifError(err, 'npm config ran without issue') + t.notOk(code, 'exited with a non-error code') + t.notOk(stderr, 'no error output') + + common.npm( + [ + 'version', + 'patch', + '--loglevel', 'silent' + // package config is picked up from env + ], + { cwd: pkg, env: { PATH: process.env.PATH } }, function (err, code, stdout, stderr) { - t.ifError(err, 'npm config ran without issue') - t.notOk(code, 'exited with a non-error code') - t.notOk(stderr, 'no error output') - - common.npm( - [ - 'version', - 'patch', - '--loglevel', 'silent' - // package config is picked up from env - ], - { cwd: pkg, env: { PATH: process.env.PATH } }, - function (err, code, stdout, stderr) { - t.ifError(err, 'npm version ran without issue') - t.notOk(code, 'exited with a non-error code') - t.notOk(stderr, 'no error output') - - git.whichAndExec( - ['tag'], - { cwd: pkg, env: process.env }, - function (er, tags, stderr) { - t.ok(tags.match(/q0\.1\.3/g), 'tag was created by version' + tags) - t.end() - } - ) - } - ) - }) + t.ifError(err, 'npm version ran without issue') + t.notOk(code, 'exited with a non-error code') + t.notOk(stderr, 'no error output') + + git.whichAndExec( + ['tag'], + { cwd: pkg, env: process.env }, + function (er, tags, stderr) { + t.ok(tags.match(/q0\.1\.3/g), 'tag was created by version' + tags) + t.end() + } + ) + } + ) }) }) + }) }) test('cleanup', function (t) { - cleanup() - t.end() + cleanup() + t.end() }) function cleanup () { - // windows fix for locked files - process.chdir(osenv.tmpdir()) + // windows fix for locked files + process.chdir(osenv.tmpdir()) - rimraf.sync(pkg) + rimraf.sync(pkg) } function setup () { - cleanup() - mkdirp.sync(cache) - process.chdir(pkg) + cleanup() + mkdirp.sync(cache) + process.chdir(pkg) - fs.writeFileSync(packagePath, JSON.stringify(json), 'utf8') - fs.writeFileSync(npmrc, configContents, 'ascii') + fs.writeFileSync(packagePath, JSON.stringify(json), 'utf8') + fs.writeFileSync(npmrc, configContents, 'ascii') } diff --git a/test/tap/test-run-ls.js b/test/tap/test-run-ls.js index 252c6e8f9..ea495879f 100644 --- a/test/tap/test-run-ls.js +++ b/test/tap/test-run-ls.js @@ -1,30 +1,30 @@ -var common = require("../common-tap.js") -var test = require("tap").test -var path = require("path") -var cwd = path.resolve(__dirname, "..", "..") -var testscript = require("../../package.json").scripts.test -var tsregexp = testscript.replace(/([\[\.\*\]])/g, "\\$1") +var common = require('../common-tap.js') +var test = require('tap').test +var path = require('path') +var cwd = path.resolve(__dirname, '..', '..') +var testscript = require('../../package.json').scripts.test +var tsregexp = testscript.replace(/([\[\.\*\]])/g, '\\$1') -test("default", function (t) { - common.npm(["run"], { cwd: cwd }, function (er, code, so) { +test('default', function (t) { + common.npm(['run'], { cwd: cwd }, function (er, code, so) { if (er) throw er t.notOk(code) - t.similar(so, new RegExp("\\n test\\n " + tsregexp + "\\n")) + t.similar(so, new RegExp('\\n test\\n ' + tsregexp + '\\n')) t.end() }) }) -test("parseable", function (t) { - common.npm(["run", "-p"], { cwd: cwd }, function (er, code, so) { +test('parseable', function (t) { + common.npm(['run', '-p'], { cwd: cwd }, function (er, code, so) { if (er) throw er t.notOk(code) - t.similar(so, new RegExp("\\ntest:" + tsregexp + "\\n")) + t.similar(so, new RegExp('\\ntest:' + tsregexp + '\\n')) t.end() }) }) -test("parseable", function (t) { - common.npm(["run", "--json"], { cwd: cwd }, function (er, code, so) { +test('parseable', function (t) { + common.npm(['run', '--json'], { cwd: cwd }, function (er, code, so) { if (er) throw er t.notOk(code) t.equal(JSON.parse(so).test, testscript) diff --git a/test/tap/update-examples.js b/test/tap/update-examples.js index f662e23d5..ae67e4a91 100644 --- a/test/tap/update-examples.js +++ b/test/tap/update-examples.js @@ -141,7 +141,7 @@ test('setup', function (t) { process.chdir(osenv.tmpdir()) mkdirp.sync(PKG_DIR) process.chdir(PKG_DIR) - t.pass('made '+PKG_DIR) + t.pass('made ' + PKG_DIR) resetPackage({}) diff --git a/test/tap/version-git-not-clean.js b/test/tap/version-git-not-clean.js index 1deae49f9..d770a86e6 100644 --- a/test/tap/version-git-not-clean.js +++ b/test/tap/version-git-not-clean.js @@ -1,60 +1,59 @@ -var common = require("../common-tap.js") -var test = require("tap").test -var npm = require("../../") -var osenv = require("osenv") -var path = require("path") -var fs = require("fs") -var rimraf = require("rimraf") -var mkdirp = require("mkdirp") -var which = require("which") -var spawn = require("child_process").spawn +var common = require('../common-tap.js') +var test = require('tap').test +var npm = require('../../') +var osenv = require('osenv') +var path = require('path') +var fs = require('fs') +var rimraf = require('rimraf') +var mkdirp = require('mkdirp') +var which = require('which') +var spawn = require('child_process').spawn -var pkg = path.resolve(__dirname, "version-git-not-clean") -var cache = path.resolve(pkg, "cache") +var pkg = path.resolve(__dirname, 'version-git-not-clean') +var cache = path.resolve(pkg, 'cache') -test("npm version <semver> with working directory not clean", function (t) { +test('npm version <semver> with working directory not clean', function (t) { setup() npm.load({ cache: cache, registry: common.registry, prefix: pkg }, function () { - which("git", function (err, git) { - t.ifError(err, "git found") + which('git', function (err, git) { + t.ifError(err, 'git found') - function gitInit(_cb) { - var child = spawn(git, ["init"]) - var out = "" - child.stdout.on("data", function (d) { + function gitInit (_cb) { + var child = spawn(git, ['init']) + var out = '' + child.stdout.on('data', function (d) { out += d.toString() }) - child.on("exit", function () { + child.on('exit', function () { return _cb(out) }) } - function addPackageJSON(_cb) { - var data = JSON.stringify({ name: "blah", version: "0.1.2" }) - fs.writeFile("package.json", data, function() { - var child = spawn(git, ["add", "package.json"]) - child.on("exit", function () { - var child2 = spawn(git, ["commit", "package.json", "-m", "init"]) - var out = "" - child2.stdout.on("data", function (d) { + function addPackageJSON (_cb) { + var data = JSON.stringify({ name: 'blah', version: '0.1.2' }) + fs.writeFile('package.json', data, function () { + var child = spawn(git, ['add', 'package.json']) + child.on('exit', function () { + var child2 = spawn(git, ['commit', 'package.json', '-m', 'init']) + var out = '' + child2.stdout.on('data', function (d) { out += d.toString() }) - child2.on("exit", function () { + child2.on('exit', function () { return _cb(out) }) }) }) } - gitInit(function() { - addPackageJSON(function() { - var data = JSON.stringify({ name: "blah", version: "0.1.3" }) - fs.writeFile("package.json", data, function() { - npm.commands.version(["patch"], function (err) { + gitInit(function () { + addPackageJSON(function () { + var data = JSON.stringify({ name: 'blah', version: '0.1.3' }) + fs.writeFile('package.json', data, function () { + npm.commands.version(['patch'], function (err) { if (!err) { - t.fail("should fail on non-clean working directory") - } - else { + t.fail('should fail on non-clean working directory') + } else { t.ok(err.message.match(/Git working directory not clean./)) t.ok(err.message.match(/M package.json/)) } @@ -67,7 +66,7 @@ test("npm version <semver> with working directory not clean", function (t) { }) }) -test("cleanup", function (t) { +test('cleanup', function (t) { // windows fix for locked files process.chdir(osenv.tmpdir()) @@ -75,7 +74,7 @@ test("cleanup", function (t) { t.end() }) -function setup() { +function setup () { mkdirp.sync(pkg) mkdirp.sync(cache) process.chdir(pkg) diff --git a/test/tap/version-no-git.js b/test/tap/version-no-git.js index 0acd0ab6a..0a859c7af 100644 --- a/test/tap/version-no-git.js +++ b/test/tap/version-no-git.js @@ -1,54 +1,54 @@ -var common = require("../common-tap.js") -var test = require("tap").test -var npm = require("../../") -var osenv = require("osenv") -var path = require("path") -var fs = require("fs") -var mkdirp = require("mkdirp") -var rimraf = require("rimraf") -var requireInject = require("require-inject") +var common = require('../common-tap.js') +var test = require('tap').test +var npm = require('../../') +var osenv = require('osenv') +var path = require('path') +var fs = require('fs') +var mkdirp = require('mkdirp') +var rimraf = require('rimraf') +var requireInject = require('require-inject') -var pkg = path.resolve(__dirname, "version-no-git") -var cache = path.resolve(pkg, "cache") -var gitDir = path.resolve(pkg, ".git") +var pkg = path.resolve(__dirname, 'version-no-git') +var cache = path.resolve(pkg, 'cache') +var gitDir = path.resolve(pkg, '.git') -test("npm version <semver> in a git repo without the git binary", function(t) { +test('npm version <semver> in a git repo without the git binary', function (t) { setup() - npm.load({cache: cache, registry: common.registry}, function() { - var version = requireInject("../../lib/version", { - which: function(cmd, cb) { - process.nextTick(function() { + npm.load({cache: cache, registry: common.registry}, function () { + var version = requireInject('../../lib/version', { + which: function (cmd, cb) { + process.nextTick(function () { cb(new Error('ENOGIT!')) }) } }) - version(["patch"], function(err) { - if (! t.error(err)) return t.end() - var p = path.resolve(pkg, "package") + version(['patch'], function (err) { + if (!t.error(err)) return t.end() + var p = path.resolve(pkg, 'package') var testPkg = require(p) - t.equal("0.0.1", testPkg.version, "\"" + testPkg.version+"\" === \"0.0.1\"") + t.equal('0.0.1', testPkg.version, '\'' + testPkg.version + '\' === \'0.0.1\'') t.end() }) }) }) -test("cleanup", function(t) { +test('cleanup', function (t) { process.chdir(osenv.tmpdir()) rimraf.sync(pkg) t.end() }) -function setup() { +function setup () { mkdirp.sync(pkg) mkdirp.sync(cache) mkdirp.sync(gitDir) - fs.writeFileSync(path.resolve(pkg, "package.json"), JSON.stringify({ - author: "Terin Stock", - name: "version-no-git-test", - version: "0.0.0", + fs.writeFileSync(path.resolve(pkg, 'package.json'), JSON.stringify({ + author: 'Terin Stock', + name: 'version-no-git-test', + version: '0.0.0', description: "Test for npm version if git binary doesn't exist" - }), "utf8") + }), 'utf8') process.chdir(pkg) } diff --git a/test/tap/version-no-package.js b/test/tap/version-no-package.js index 539f53feb..755f99317 100644 --- a/test/tap/version-no-package.js +++ b/test/tap/version-no-package.js @@ -1,45 +1,45 @@ -var common = require("../common-tap.js") -var test = require("tap").test -var osenv = require("osenv") -var path = require("path") -var mkdirp = require("mkdirp") -var rimraf = require("rimraf") +var common = require('../common-tap.js') +var test = require('tap').test +var osenv = require('osenv') +var path = require('path') +var mkdirp = require('mkdirp') +var rimraf = require('rimraf') -var pkg = path.resolve(__dirname, "version-no-package") +var pkg = path.resolve(__dirname, 'version-no-package') -test("setup", function (t) { +test('setup', function (t) { setup() t.end() }) -test("npm version in a prefix with no package.json", function(t) { +test('npm version in a prefix with no package.json', function (t) { setup() common.npm( - ["version", "--json", "--prefix", pkg], - { cwd : pkg }, + ['version', '--json', '--prefix', pkg], + { cwd: pkg }, function (er, code, stdout, stderr) { t.ifError(er, "npm version doesn't care that there's no package.json") - t.notOk(code, "npm version ran without barfing") - t.ok(stdout, "got version output") - t.notOk(stderr, "no error output") + t.notOk(code, 'npm version ran without barfing') + t.ok(stdout, 'got version output') + t.notOk(stderr, 'no error output') t.doesNotThrow(function () { var metadata = JSON.parse(stdout) - t.equal(metadata.node, process.versions.node, "node versions match") + t.equal(metadata.node, process.versions.node, 'node versions match') t.end() - }, "able to reconstitute version object from stdout") + }, 'able to reconstitute version object from stdout') } ) }) -test("cleanup", function(t) { +test('cleanup', function (t) { process.chdir(osenv.tmpdir()) rimraf.sync(pkg) t.end() }) -function setup() { +function setup () { mkdirp.sync(pkg) process.chdir(pkg) } diff --git a/test/tap/version-no-tags.js b/test/tap/version-no-tags.js index cb6f195f8..ed2bed32c 100644 --- a/test/tap/version-no-tags.js +++ b/test/tap/version-no-tags.js @@ -1,47 +1,47 @@ -var common = require("../common-tap.js") -var test = require("tap").test -var npm = require("../../") -var osenv = require("osenv") -var path = require("path") -var fs = require("fs") -var rimraf = require("rimraf") -var mkdirp = require("mkdirp") -var which = require("which") -var spawn = require("child_process").spawn +var common = require('../common-tap.js') +var test = require('tap').test +var npm = require('../../') +var osenv = require('osenv') +var path = require('path') +var fs = require('fs') +var rimraf = require('rimraf') +var mkdirp = require('mkdirp') +var which = require('which') +var spawn = require('child_process').spawn -var pkg = path.resolve(__dirname, "version-no-tags") -var cache = path.resolve(pkg, "cache") +var pkg = path.resolve(__dirname, 'version-no-tags') +var cache = path.resolve(pkg, 'cache') -test("npm version <semver> without git tag", function (t) { +test('npm version <semver> without git tag', function (t) { setup() npm.load({ cache: cache, registry: common.registry}, function () { - which("git", function (err, git) { - t.ifError(err, "git found on system") - function tagExists(tag, _cb) { - var child1 = spawn(git, ["tag", "-l", tag]) - var out = "" - child1.stdout.on("data", function (d) { + which('git', function (err, git) { + t.ifError(err, 'git found on system') + function tagExists (tag, _cb) { + var child1 = spawn(git, ['tag', '-l', tag]) + var out = '' + child1.stdout.on('data', function (d) { out += d.toString() }) - child1.on("exit", function () { + child1.on('exit', function () { return _cb(null, Boolean(~out.indexOf(tag))) }) } - var child2 = spawn(git, ["init"]) + var child2 = spawn(git, ['init']) child2.stdout.pipe(process.stdout) - child2.on("exit", function () { - npm.config.set("git-tag-version", false) - npm.commands.version(["patch"], function (err) { - if (err) return t.fail("Error perform version patch") - var p = path.resolve(pkg, "package") + child2.on('exit', function () { + npm.config.set('git-tag-version', false) + npm.commands.version(['patch'], function (err) { + if (err) return t.fail('Error perform version patch') + var p = path.resolve(pkg, 'package') var testPkg = require(p) - if (testPkg.version !== "0.0.1") t.fail(testPkg.version+" !== \"0.0.1\"") - t.equal("0.0.1", testPkg.version) - tagExists("v0.0.1", function (err, exists) { - t.ifError(err, "tag found to exist") - t.equal(exists, false, "git tag DOES exist") - t.pass("git tag does not exist") + if (testPkg.version !== '0.0.1') t.fail(testPkg.version + ' !== \'0.0.1\'') + t.equal('0.0.1', testPkg.version) + tagExists('v0.0.1', function (err, exists) { + t.ifError(err, 'tag found to exist') + t.equal(exists, false, 'git tag DOES exist') + t.pass('git tag does not exist') t.end() }) }) @@ -50,7 +50,7 @@ test("npm version <semver> without git tag", function (t) { }) }) -test("cleanup", function (t) { +test('cleanup', function (t) { // windows fix for locked files process.chdir(osenv.tmpdir()) @@ -58,14 +58,14 @@ test("cleanup", function (t) { t.end() }) -function setup() { +function setup () { mkdirp.sync(pkg) mkdirp.sync(cache) - fs.writeFileSync(path.resolve(pkg, "package.json"), JSON.stringify({ - author: "Evan Lucas", - name: "version-no-tags-test", - version: "0.0.0", - description: "Test for git-tag-version flag" - }), "utf8") + fs.writeFileSync(path.resolve(pkg, 'package.json'), JSON.stringify({ + author: 'Evan Lucas', + name: 'version-no-tags-test', + version: '0.0.0', + description: 'Test for git-tag-version flag' + }), 'utf8') process.chdir(pkg) } diff --git a/test/tap/view.js b/test/tap/view.js index 68583ba25..84a0a69d3 100644 --- a/test/tap/view.js +++ b/test/tap/view.js @@ -1,97 +1,97 @@ -var common = require("../common-tap.js") -var test = require("tap").test -var osenv = require("osenv") -var path = require("path") -var fs = require("fs") -var rimraf = require("rimraf") -var mkdirp = require("mkdirp") +var common = require('../common-tap.js') +var test = require('tap').test +var osenv = require('osenv') +var path = require('path') +var fs = require('fs') +var rimraf = require('rimraf') +var mkdirp = require('mkdirp') var tmp = osenv.tmpdir() -var t1dir = path.resolve(tmp, "view-local-no-pkg") -var t2dir = path.resolve(tmp, "view-local-notmine") -var t3dir = path.resolve(tmp, "view-local-mine") -var mr = require("npm-registry-mock") +var t1dir = path.resolve(tmp, 'view-local-no-pkg') +var t2dir = path.resolve(tmp, 'view-local-notmine') +var t3dir = path.resolve(tmp, 'view-local-mine') +var mr = require('npm-registry-mock') -test("setup", function (t) { +test('setup', function (t) { mkdirp.sync(t1dir) mkdirp.sync(t2dir) mkdirp.sync(t3dir) - fs.writeFileSync(t2dir + "/package.json", JSON.stringify({ - author: "Evan Lucas" - , name: "test-repo-url-https" - , version: "0.0.1" - }), "utf8") + fs.writeFileSync(t2dir + '/package.json', JSON.stringify({ + author: 'Evan Lucas', + name: 'test-repo-url-https', + version: '0.0.1' + }), 'utf8') - fs.writeFileSync(t3dir + "/package.json", JSON.stringify({ - author: "Evan Lucas" - , name: "biscuits" - , version: "0.0.1" - }), "utf8") + fs.writeFileSync(t3dir + '/package.json', JSON.stringify({ + author: 'Evan Lucas', + name: 'biscuits', + version: '0.0.1' + }), 'utf8') - t.pass("created fixtures") + t.pass('created fixtures') t.end() }) function plugin (server) { server - .get("/biscuits") + .get('/biscuits') .many() - .reply(404, {"error": "version not found"}) + .reply(404, {'error': 'version not found'}) } -test("npm view . in global mode", function (t) { +test('npm view . in global mode', function (t) { process.chdir(t1dir) common.npm([ - "view" - , "." - , "--registry=" + common.registry - , "--global" + 'view', + '.', + '--registry=' + common.registry, + '--global' ], { cwd: t1dir }, function (err, code, stdout, stderr) { - t.ifError(err, "view command finished successfully") - t.equal(code, 1, "exit not ok") + t.ifError(err, 'view command finished successfully') + t.equal(code, 1, 'exit not ok') t.similar(stderr, /Cannot use view command in global mode./m) t.end() }) }) -test("npm view --global", function(t) { +test('npm view --global', function (t) { process.chdir(t1dir) common.npm([ - "view" - , "--registry=" + common.registry - , "--global" - ], { cwd: t1dir }, function(err, code, stdout, stderr) { - t.ifError(err, "view command finished successfully") - t.equal(code, 1, "exit not ok") + 'view', + '--registry=' + common.registry, + '--global' + ], { cwd: t1dir }, function (err, code, stdout, stderr) { + t.ifError(err, 'view command finished successfully') + t.equal(code, 1, 'exit not ok') t.similar(stderr, /Cannot use view command in global mode./m) t.end() }) }) -test("npm view . with no package.json", function(t) { +test('npm view . with no package.json', function (t) { process.chdir(t1dir) common.npm([ - "view" - , "." - , "--registry=" + common.registry + 'view', + '.', + '--registry=' + common.registry ], { cwd: t1dir }, function (err, code, stdout, stderr) { - t.ifError(err, "view command finished successfully") - t.equal(code, 1, "exit not ok") + t.ifError(err, 'view command finished successfully') + t.equal(code, 1, 'exit not ok') t.similar(stderr, /Invalid package.json/m) t.end() }) }) -test("npm view . with no published package", function (t) { +test('npm view . with no published package', function (t) { process.chdir(t3dir) - mr({port : common.port, plugin : plugin}, function (er, s) { + mr({ port: common.port, plugin: plugin}, function (er, s) { common.npm([ - "view" - , "." - , "--registry=" + common.registry + 'view', + '.', + '--registry=' + common.registry ], { cwd: t3dir }, function (err, code, stdout, stderr) { - t.ifError(err, "view command finished successfully") - t.equal(code, 1, "exit not ok") + t.ifError(err, 'view command finished successfully') + t.equal(code, 1, 'exit not ok') t.similar(stderr, /version not found/m) s.close() t.end() @@ -99,16 +99,16 @@ test("npm view . with no published package", function (t) { }) }) -test("npm view .", function (t) { +test('npm view .', function (t) { process.chdir(t2dir) - mr({port : common.port, plugin : plugin}, function (er, s) { + mr({ port: common.port, plugin: plugin }, function (er, s) { common.npm([ - "view" - , "." - , "--registry=" + common.registry + 'view', + '.', + '--registry=' + common.registry ], { cwd: t2dir }, function (err, code, stdout) { - t.ifError(err, "view command finished successfully") - t.equal(code, 0, "exit ok") + t.ifError(err, 'view command finished successfully') + t.equal(code, 0, 'exit ok') var re = new RegExp("name: 'test-repo-url-https'") t.similar(stdout, re) s.close() @@ -117,161 +117,160 @@ test("npm view .", function (t) { }) }) -test("npm view . select fields", function (t) { +test('npm view . select fields', function (t) { process.chdir(t2dir) - mr({port : common.port, plugin : plugin}, function (er, s) { + mr({ port: common.port, plugin: plugin }, function (er, s) { common.npm([ - "view" - , "." - , "main" - , "--registry=" + common.registry + 'view', + '.', + 'main', + '--registry=' + common.registry ], { cwd: t2dir }, function (err, code, stdout) { - t.ifError(err, "view command finished successfully") - t.equal(code, 0, "exit ok") - t.equal(stdout.trim(), "index.js", "should print `index.js`") + t.ifError(err, 'view command finished successfully') + t.equal(code, 0, 'exit ok') + t.equal(stdout.trim(), 'index.js', 'should print `index.js`') s.close() t.end() }) }) }) -test("npm view .@<version>", function (t) { +test('npm view .@<version>', function (t) { process.chdir(t2dir) - mr({port : common.port, plugin : plugin}, function (er, s) { + mr({ port: common.port, plugin: plugin }, function (er, s) { common.npm([ - "view" - , ".@0.0.0" - , "version" - , "--registry=" + common.registry + 'view', + '.@0.0.0', + 'version', + '--registry=' + common.registry ], { cwd: t2dir }, function (err, code, stdout) { - t.ifError(err, "view command finished successfully") - t.equal(code, 0, "exit ok") - t.equal(stdout.trim(), "0.0.0", "should print `0.0.0`") + t.ifError(err, 'view command finished successfully') + t.equal(code, 0, 'exit ok') + t.equal(stdout.trim(), '0.0.0', 'should print `0.0.0`') s.close() t.end() }) }) }) -test("npm view .@<version> --json", function (t) { +test('npm view .@<version> --json', function (t) { process.chdir(t2dir) - mr({port : common.port, plugin : plugin}, function (er, s) { + mr({ port: common.port, plugin: plugin }, function (er, s) { common.npm([ - "view" - , ".@0.0.0" - , "version" - , "--json" - , "--registry=" + common.registry + 'view', + '.@0.0.0', + 'version', + '--json', + '--registry=' + common.registry ], { cwd: t2dir }, function (err, code, stdout) { - t.ifError(err, "view command finished successfully") - t.equal(code, 0, "exit ok") - t.equal(stdout.trim(), "\"0.0.0\"", "should print `\"0.0.0\"`") + t.ifError(err, 'view command finished successfully') + t.equal(code, 0, 'exit ok') + t.equal(stdout.trim(), '"0.0.0"', 'should print `"0.0.0"`') s.close() t.end() }) }) }) -test("npm view <package name>", function (t) { - mr({port : common.port, plugin : plugin}, function (er, s) { +test('npm view <package name>', function (t) { + mr({ port: common.port, plugin: plugin }, function (er, s) { common.npm([ - "view" - , "underscore" - , "--registry=" + common.registry + 'view', + 'underscore', + '--registry=' + common.registry ], { cwd: t2dir }, function (err, code, stdout) { - t.ifError(err, "view command finished successfully") - t.equal(code, 0, "exit ok") + t.ifError(err, 'view command finished successfully') + t.equal(code, 0, 'exit ok') var re = new RegExp("name: 'underscore'") - t.similar(stdout, re, "should have name `underscore`") + t.similar(stdout, re, 'should have name `underscore`') s.close() t.end() }) }) }) -test("npm view <package name> --global", function(t) { - mr({port : common.port, plugin : plugin}, function (er, s) { +test('npm view <package name> --global', function (t) { + mr({ port: common.port, plugin: plugin }, function (er, s) { common.npm([ - "view" - , "underscore" - , "--global" - , "--registry=" + common.registry - ], { cwd: t2dir }, function(err, code, stdout) { - t.ifError(err, "view command finished successfully") - t.equal(code, 0, "exit ok") + 'view', + 'underscore', + '--global', + '--registry=' + common.registry + ], { cwd: t2dir }, function (err, code, stdout) { + t.ifError(err, 'view command finished successfully') + t.equal(code, 0, 'exit ok') var re = new RegExp("name: 'underscore'") - t.similar(stdout, re, "should have name `underscore`") + t.similar(stdout, re, 'should have name `underscore`') s.close() t.end() }) }) }) -test("npm view <package name> --json", function(t) { +test('npm view <package name> --json', function (t) { t.plan(3) - mr({port : common.port, plugin : plugin}, function (er, s) { + mr({ port: common.port, plugin: plugin }, function (er, s) { common.npm([ - "view" - , "underscore" - , "--json" - , "--registry=" + common.registry + 'view', + 'underscore', + '--json', + '--registry=' + common.registry ], { cwd: t2dir }, function (err, code, stdout) { - t.ifError(err, "view command finished successfully") - t.equal(code, 0, "exit ok") + t.ifError(err, 'view command finished successfully') + t.equal(code, 0, 'exit ok') s.close() try { var out = JSON.parse(stdout.trim()) t.similar(out, { - maintainers: ["jashkenas <jashkenas@gmail.com>"] - }, "should have the same maintainer") - } - catch (er) { - t.fail("Unable to parse JSON") + maintainers: ['jashkenas <jashkenas@gmail.com>'] + }, 'should have the same maintainer') + } catch (er) { + t.fail('Unable to parse JSON') } }) }) }) -test("npm view <package name> <field>", function (t) { - mr({port : common.port, plugin : plugin}, function (er, s) { +test('npm view <package name> <field>', function (t) { + mr({ port: common.port, plugin: plugin }, function (er, s) { common.npm([ - "view" - , "underscore" - , "homepage" - , "--registry=" + common.registry + 'view', + 'underscore', + 'homepage', + '--registry=' + common.registry ], { cwd: t2dir }, function (err, code, stdout) { - t.ifError(err, "view command finished successfully") - t.equal(code, 0, "exit ok") - t.equal(stdout.trim(), "http://underscorejs.org", - "homepage should equal `http://underscorejs.org`") + t.ifError(err, 'view command finished successfully') + t.equal(code, 0, 'exit ok') + t.equal(stdout.trim(), 'http://underscorejs.org', + 'homepage should equal `http://underscorejs.org`') s.close() t.end() }) }) }) -test("npm view with invalid package name", function (t) { - var invalidName = "InvalidPackage" - obj = {} - obj["/" + invalidName] = [404, {"error": "not found"}] +test('npm view with invalid package name', function (t) { + var invalidName = 'InvalidPackage' + var obj = {} + obj['/' + invalidName] = [404, {'error': 'not found'}] - mr({port : common.port, mocks: {"get": obj}}, function (er, s) { + mr({ port: common.port, mocks: { 'get': obj } }, function (er, s) { common.npm([ - "view" - , invalidName - , "--registry=" + common.registry + 'view', + invalidName, + '--registry=' + common.registry ], {}, function (err, code, stdout, stderr) { - t.ifError(err, "view command finished successfully") - t.equal(code, 1, "exit not ok") + t.ifError(err, 'view command finished successfully') + t.equal(code, 1, 'exit not ok') - t.similar(stderr, new RegExp("is not in the npm registry"), - "Package should NOT be found") + t.similar(stderr, new RegExp('is not in the npm registry'), + 'Package should NOT be found') - t.dissimilar(stderr, new RegExp("use the name yourself!"), - "Suggestion should not be there") + t.dissimilar(stderr, new RegExp('use the name yourself!'), + 'Suggestion should not be there') - t.similar(stderr, new RegExp("name can no longer contain capital letters"), - "Suggestion about Capital letter should be there") + t.similar(stderr, new RegExp('name can no longer contain capital letters'), + 'Suggestion about Capital letter should be there') s.close() t.end() @@ -279,27 +278,26 @@ test("npm view with invalid package name", function (t) { }) }) - -test("npm view with valid but non existent package name", function (t) { - mr({port : common.port, mocks: { - "get": { - "/valid-but-non-existent-package" : [404, {"error": "not found"}] +test('npm view with valid but non existent package name', function (t) { + mr({ port: common.port, mocks: { + 'get': { + '/valid-but-non-existent-package': [404, {'error': 'not found'}] } }}, function (er, s) { common.npm([ - "view" - , "valid-but-non-existent-package" - , "--registry=" + common.registry + 'view', + 'valid-but-non-existent-package', + '--registry=' + common.registry ], {}, function (err, code, stdout, stderr) { - t.ifError(err, "view command finished successfully") - t.equal(code, 1, "exit not ok") + t.ifError(err, 'view command finished successfully') + t.equal(code, 1, 'exit not ok') t.similar(stderr, new RegExp("'valid-but-non-existent-package' is not in the npm registry\."), - "Package should NOT be found") + 'Package should NOT be found') - t.similar(stderr, new RegExp("use the name yourself!"), - "Suggestion should be there") + t.similar(stderr, new RegExp('use the name yourself!'), + 'Suggestion should be there') s.close() t.end() @@ -307,11 +305,11 @@ test("npm view with valid but non existent package name", function (t) { }) }) -test("cleanup", function (t) { +test('cleanup', function (t) { process.chdir(osenv.tmpdir()) rimraf.sync(t1dir) rimraf.sync(t2dir) rimraf.sync(t3dir) - t.pass("cleaned up") + t.pass('cleaned up') t.end() }) diff --git a/test/tap/whoami.js b/test/tap/whoami.js index 558d0db9a..268e0f94f 100644 --- a/test/tap/whoami.js +++ b/test/tap/whoami.js @@ -1,55 +1,55 @@ -var common = require("../common-tap.js") +var common = require('../common-tap.js') -var fs = require("fs") -var path = require("path") -var createServer = require("http").createServer +var fs = require('fs') +var path = require('path') +var createServer = require('http').createServer -var test = require("tap").test -var rimraf = require("rimraf") +var test = require('tap').test +var rimraf = require('rimraf') var opts = { cwd: __dirname } -var FIXTURE_PATH = path.resolve(__dirname, "fixture_npmrc") +var FIXTURE_PATH = path.resolve(__dirname, 'fixture_npmrc') -test("npm whoami with basic auth", function (t) { - var s = "//registry.lvh.me/:username = wombat\n" + - "//registry.lvh.me/:_password = YmFkIHBhc3N3b3Jk\n" + - "//registry.lvh.me/:email = lindsay@wdu.org.au\n" - fs.writeFileSync(FIXTURE_PATH, s, "ascii") - fs.chmodSync(FIXTURE_PATH, "0444") +test('npm whoami with basic auth', function (t) { + var s = '//registry.lvh.me/:username = wombat\n' + + '//registry.lvh.me/:_password = YmFkIHBhc3N3b3Jk\n' + + '//registry.lvh.me/:email = lindsay@wdu.org.au\n' + fs.writeFileSync(FIXTURE_PATH, s, 'ascii') + fs.chmodSync(FIXTURE_PATH, '0444') common.npm( [ - "whoami", - "--userconfig=" + FIXTURE_PATH, - "--registry=http://registry.lvh.me/" + 'whoami', + '--userconfig=' + FIXTURE_PATH, + '--registry=http://registry.lvh.me/' ], opts, function (err, code, stdout, stderr) { t.ifError(err) - t.equal(stderr, "", "got nothing on stderr") - t.equal(code, 0, "exit ok") - t.equal(stdout, "wombat\n", "got username") + t.equal(stderr, '', 'got nothing on stderr') + t.equal(code, 0, 'exit ok') + t.equal(stdout, 'wombat\n', 'got username') rimraf.sync(FIXTURE_PATH) t.end() } ) }) -test("npm whoami with bearer auth", {timeout : 2 * 1000}, function (t) { - var s = "//localhost:" + common.port + - "/:_authToken = wombat-developers-union\n" - fs.writeFileSync(FIXTURE_PATH, s, "ascii") - fs.chmodSync(FIXTURE_PATH, "0444") +test('npm whoami with bearer auth', { timeout: 2 * 1000 }, function (t) { + var s = '//localhost:' + common.port + + '/:_authToken = wombat-developers-union\n' + fs.writeFileSync(FIXTURE_PATH, s, 'ascii') + fs.chmodSync(FIXTURE_PATH, '0444') - function verify(req, res) { - t.equal(req.method, "GET") - t.equal(req.url, "/-/whoami") + function verify (req, res) { + t.equal(req.method, 'GET') + t.equal(req.url, '/-/whoami') - res.setHeader("content-type", "application/json") + res.setHeader('content-type', 'application/json') res.writeHeader(200) - res.end(JSON.stringify({username : "wombat"}), "utf8") + res.end(JSON.stringify({ username: 'wombat' }), 'utf8') } var server = createServer(verify) @@ -57,17 +57,17 @@ test("npm whoami with bearer auth", {timeout : 2 * 1000}, function (t) { server.listen(common.port, function () { common.npm( [ - "whoami", - "--userconfig=" + FIXTURE_PATH, - "--registry=http://localhost:" + common.port + "/" + 'whoami', + '--userconfig=' + FIXTURE_PATH, + '--registry=http://localhost:' + common.port + '/' ], opts, function (err, code, stdout, stderr) { t.ifError(err) - t.equal(stderr, "", "got nothing on stderr") - t.equal(code, 0, "exit ok") - t.equal(stdout, "wombat\n", "got username") + t.equal(stderr, '', 'got nothing on stderr') + t.equal(code, 0, 'exit ok') + t.equal(stdout, 'wombat\n', 'got username') rimraf.sync(FIXTURE_PATH) server.close() t.end() diff --git a/test/tap/zz-cleanup.js b/test/tap/zz-cleanup.js index c491cbf07..e1020aa3b 100644 --- a/test/tap/zz-cleanup.js +++ b/test/tap/zz-cleanup.js @@ -1,8 +1,8 @@ -var common = require("../common-tap") -var test = require("tap").test -var rimraf = require("rimraf") +var common = require('../common-tap') +var test = require('tap').test +var rimraf = require('rimraf') -test("cleanup", function (t) { +test('cleanup', function (t) { rimraf.sync(common.npm_config_cache) t.end() }) |