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 /lib | |
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
Diffstat (limited to 'lib')
97 files changed, 3716 insertions, 3521 deletions
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 ' ' }}) |