diff options
author | Gar <gar+gh@danger.computer> | 2021-03-01 06:00:58 +0300 |
---|---|---|
committer | Gar <gar+gh@danger.computer> | 2021-03-09 22:10:06 +0300 |
commit | 85a8694dd9b4a924a474ba75261914511a216868 (patch) | |
tree | 1102b6d0df598a59bd85998a2f05f155ba6b1800 /lib | |
parent | 7ff152d94d2dbeaacbfc9824d8b1bb6ff96bf0f2 (diff) |
fix(npm.output): make output go through npm.output
All output that anything wants to make now goes through
`npm.output()`. This is an incremental change getting us
closer to where we want to be with testing.
PR-URL: https://github.com/npm/cli/pull/2795
Credit: @wraithgar
Close: #2795
Reviewed-by: @ruyadorno, @isaacs
Diffstat (limited to 'lib')
44 files changed, 279 insertions, 318 deletions
diff --git a/lib/access.js b/lib/access.js index e11934af4..3bc211190 100644 --- a/lib/access.js +++ b/lib/access.js @@ -3,7 +3,6 @@ const path = require('path') const libaccess = require('libnpmaccess') const readPackageJson = require('read-package-json-fast') -const output = require('./utils/output.js') const otplease = require('./utils/otplease.js') const usageUtil = require('./utils/usage.js') const getIdentity = require('./utils/get-identity.js') @@ -157,7 +156,7 @@ class Access { const pkgs = await libaccess.lsPackages(owner, opts) // TODO - print these out nicely (breaking change) - output(JSON.stringify(pkgs, null, 2)) + this.npm.output(JSON.stringify(pkgs, null, 2)) } get ['ls-collaborators'] () { @@ -169,7 +168,7 @@ class Access { const collabs = await libaccess.lsCollaborators(pkgName, usr, opts) // TODO - print these out nicely (breaking change) - output(JSON.stringify(collabs, null, 2)) + this.npm.output(JSON.stringify(collabs, null, 2)) } async edit () { diff --git a/lib/adduser.js b/lib/adduser.js index dac0f5a46..45d602fd2 100644 --- a/lib/adduser.js +++ b/lib/adduser.js @@ -1,5 +1,4 @@ const log = require('npmlog') -const output = require('./utils/output.js') const usageUtil = require('./utils/usage.js') const replaceInfo = require('./utils/replace-info.js') const authTypes = { @@ -49,7 +48,7 @@ class AddUser { scope, }) - output(message) + this.npm.output(message) } getRegistry ({ scope, registry }) { diff --git a/lib/audit.js b/lib/audit.js index dfa01cb27..b8c85605d 100644 --- a/lib/audit.js +++ b/lib/audit.js @@ -1,6 +1,5 @@ const Arborist = require('@npmcli/arborist') const auditReport = require('npm-audit-report') -const output = require('./utils/output.js') const reifyFinish = require('./utils/reify-finish.js') const auditError = require('./utils/audit-error.js') const usageUtil = require('./utils/usage.js') @@ -57,7 +56,7 @@ class Audit { reporter, }) process.exitCode = process.exitCode || result.exitCode - output(result.report) + this.npm.output(result.report) } } } diff --git a/lib/bin.js b/lib/bin.js index 11490c41c..f540cc57c 100644 --- a/lib/bin.js +++ b/lib/bin.js @@ -1,4 +1,3 @@ -const output = require('./utils/output.js') const envPath = require('./utils/path.js') const usageUtil = require('./utils/usage.js') @@ -18,7 +17,7 @@ class Bin { async bin (args) { const b = this.npm.bin - output(b) + this.npm.output(b) if (this.npm.flatOptions.global && !envPath.includes(b)) console.error('(not in PATH env variable)') } diff --git a/lib/cache.js b/lib/cache.js index 846955976..3ca99fd25 100644 --- a/lib/cache.js +++ b/lib/cache.js @@ -1,7 +1,6 @@ const cacache = require('cacache') const { promisify } = require('util') const log = require('npmlog') -const output = require('./utils/output.js') const pacote = require('pacote') const path = require('path') const rimraf = promisify(require('rimraf')) @@ -116,13 +115,13 @@ with --force.`) ? `~${cache.substr(process.env.HOME.length)}` : cache const stats = await cacache.verify(cache) - output(`Cache verified and compressed (${prefix})`) - output(`Content verified: ${stats.verifiedContent} (${stats.keptSize} bytes)`) - stats.badContentCount && output(`Corrupted content removed: ${stats.badContentCount}`) - stats.reclaimedCount && output(`Content garbage-collected: ${stats.reclaimedCount} (${stats.reclaimedSize} bytes)`) - stats.missingContent && output(`Missing content: ${stats.missingContent}`) - output(`Index entries: ${stats.totalEntries}`) - output(`Finished in ${stats.runTime.total / 1000}s`) + this.npm.output(`Cache verified and compressed (${prefix})`) + this.npm.output(`Content verified: ${stats.verifiedContent} (${stats.keptSize} bytes)`) + stats.badContentCount && this.npm.output(`Corrupted content removed: ${stats.badContentCount}`) + stats.reclaimedCount && this.npm.output(`Content garbage-collected: ${stats.reclaimedCount} (${stats.reclaimedSize} bytes)`) + stats.missingContent && this.npm.output(`Missing content: ${stats.missingContent}`) + this.npm.output(`Index entries: ${stats.totalEntries}`) + this.npm.output(`Finished in ${stats.runTime.total / 1000}s`) } } diff --git a/lib/completion.js b/lib/completion.js index 4c37e6ef3..5baf17665 100644 --- a/lib/completion.js +++ b/lib/completion.js @@ -39,7 +39,6 @@ const configNames = Object.keys(types) const shorthandNames = Object.keys(shorthands) const allConfs = configNames.concat(shorthandNames) const isWindowsShell = require('./utils/is-windows-shell.js') -const output = require('./utils/output.js') const fileExists = require('./utils/file-exists.js') const usageUtil = require('./utils/usage.js') @@ -131,14 +130,14 @@ class Completion { if (partialWords.slice(0, -1).indexOf('--') === -1) { if (word.charAt(0) === '-') - return wrap(opts, configCompl(opts)) + return this.wrap(opts, configCompl(opts)) 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 - return wrap(opts, configValueCompl(opts)) + return this.wrap(opts, configValueCompl(opts)) } } @@ -152,7 +151,7 @@ class Completion { // check if there's a command already. const cmd = parsed.argv.remain[1] if (!cmd) - return wrap(opts, cmdCompl(opts)) + return this.wrap(opts, cmdCompl(opts)) Object.keys(parsed).forEach(k => this.npm.config.set(k, parsed[k])) @@ -162,9 +161,29 @@ class Completion { const impl = this.npm.commands[cmd] if (impl && impl.completion) { const comps = await impl.completion(opts) - return wrap(opts, comps) + return this.wrap(opts, comps) } } + + // The command should respond with an array. Loop over that, + // wrapping quotes around any that have spaces, and writing + // them to stdout. + // 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' + wrap (opts, compls) { + if (!Array.isArray(compls)) + compls = compls ? [compls] : [] + + compls = compls.map(c => + Array.isArray(c) ? c.map(escape).join(' ') : escape(c)) + + if (opts.partialWord) + compls = compls.filter(c => c.startsWith(opts.partialWord)) + + if (compls.length > 0) + this.npm.output(compls.join('\n')) + } } const dumpScript = async () => { @@ -214,26 +233,6 @@ const unescape = w => w.charAt(0) === '\'' ? w.replace(/^'|'$/g, '') const escape = w => !/\s+/.test(w) ? w : '\'' + w + '\'' -// The command should respond with an array. Loop over that, -// wrapping quotes around any that have spaces, and writing -// them to stdout. -// 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' -const wrap = (opts, compls) => { - if (!Array.isArray(compls)) - compls = compls ? [compls] : [] - - compls = compls.map(c => - Array.isArray(c) ? c.map(escape).join(' ') : escape(c)) - - if (opts.partialWord) - compls = compls.filter(c => c.startsWith(opts.partialWord)) - - if (compls.length > 0) - output(compls.join('\n')) -} - // the current word has a dash. Return the config names, // with the same number of dashes as the current word has. const configCompl = opts => { diff --git a/lib/config.js b/lib/config.js index 2805db9b8..7009f4601 100644 --- a/lib/config.js +++ b/lib/config.js @@ -1,6 +1,5 @@ const { defaults, types } = require('./utils/config.js') const usageUtil = require('./utils/usage.js') -const output = require('./utils/output.js') const mkdirp = require('mkdirp-infer-owner') const { dirname } = require('path') @@ -142,7 +141,7 @@ class Config { const pref = keys.length > 1 ? `${key}=` : '' out.push(pref + this.npm.config.get(key)) } - output(out.join('\n')) + this.npm.output(out.join('\n')) } async del (keys) { @@ -241,7 +240,7 @@ ${defData} ) } - output(msg.join('\n').trim()) + this.npm.output(msg.join('\n').trim()) } async listJson () { @@ -252,7 +251,7 @@ ${defData} publicConf[key] = this.npm.config.get(key) } - output(JSON.stringify(publicConf, null, 2)) + this.npm.output(JSON.stringify(publicConf, null, 2)) } usageError () { diff --git a/lib/diff.js b/lib/diff.js index 859e6f76f..ed36a3067 100644 --- a/lib/diff.js +++ b/lib/diff.js @@ -9,7 +9,6 @@ const pacote = require('pacote') const pickManifest = require('npm-pick-manifest') const usageUtil = require('./utils/usage.js') -const output = require('./utils/output.js') const readLocalPkg = require('./utils/read-local-package.js') class Diff { @@ -55,7 +54,7 @@ class Diff { diffFiles: args, where: this.where, }) - return output(res) + return this.npm.output(res) } async retrieveSpecs ([a, b]) { diff --git a/lib/dist-tag.js b/lib/dist-tag.js index 171a88c52..4b7e26020 100644 --- a/lib/dist-tag.js +++ b/lib/dist-tag.js @@ -3,7 +3,6 @@ const npa = require('npm-package-arg') const regFetch = require('npm-registry-fetch') const semver = require('semver') -const output = require('./utils/output.js') const otplease = require('./utils/otplease.js') const readLocalPkgName = require('./utils/read-local-package.js') const usageUtil = require('./utils/usage.js') @@ -91,7 +90,7 @@ class DistTag { spec, } await otplease(reqOpts, reqOpts => regFetch(url, reqOpts)) - output(`+${t}: ${spec.name}@${version}`) + this.npm.output(`+${t}: ${spec.name}@${version}`) } async remove (spec, tag, opts) { @@ -116,7 +115,7 @@ class DistTag { spec, } await otplease(reqOpts, reqOpts => regFetch(url, reqOpts)) - output(`-${tag}: ${spec.name}@${version}`) + this.npm.output(`-${tag}: ${spec.name}@${version}`) } async list (spec, opts) { @@ -133,7 +132,7 @@ class DistTag { const tags = await this.fetchTags(spec, opts) const msg = Object.keys(tags).map(k => `${k}: ${tags[k]}`).sort().join('\n') - output(msg) + this.npm.output(msg) return tags } catch (err) { log.error('dist-tag ls', "Couldn't get dist-tag data for", spec) diff --git a/lib/doctor.js b/lib/doctor.js index 81860004e..63619d0cf 100644 --- a/lib/doctor.js +++ b/lib/doctor.js @@ -10,7 +10,6 @@ const semver = require('semver') const { promisify } = require('util') const ansiTrim = require('./utils/ansi-trim.js') const isWindows = require('./utils/is-windows.js') -const output = require('./utils/output.js') const ping = require('./utils/ping.js') const usageUtil = require('./utils/usage.js') const { defaults: { registry: defaultRegistry } } = require('./utils/config.js') @@ -111,7 +110,7 @@ class Doctor { const silent = this.npm.log.levels[this.npm.log.level] > this.npm.log.levels.error if (!silent) { - output(table(outTable, tableOpts)) + this.npm.output(table(outTable, tableOpts)) if (!allOk) console.error('') } diff --git a/lib/exec.js b/lib/exec.js index d1db49128..69c3cfe75 100644 --- a/lib/exec.js +++ b/lib/exec.js @@ -1,4 +1,3 @@ -const output = require('./utils/output.js') const usageUtil = require('./utils/usage.js') const { promisify } = require('util') const read = promisify(require('read')) @@ -224,7 +223,7 @@ class Exec { if (process.stdin.isTTY) { if (ciDetect()) return this.npm.log.warn('exec', 'Interactive mode disabled in CI environment') - output(`\nEntering npm script environment\nType 'exit' or ^D when finished\n`) + this.npm.output(`\nEntering npm script environment\nType 'exit' or ^D when finished\n`) } } return await runScript({ diff --git a/lib/explain.js b/lib/explain.js index 01541040e..f46d3b507 100644 --- a/lib/explain.js +++ b/lib/explain.js @@ -1,7 +1,6 @@ const usageUtil = require('./utils/usage.js') const { explainNode } = require('./utils/explain-dep.js') const completion = require('./utils/completion/installed-deep.js') -const output = require('./utils/output.js') const Arborist = require('@npmcli/arborist') const npa = require('npm-package-arg') const semver = require('semver') @@ -59,9 +58,9 @@ class Explain { } if (this.npm.flatOptions.json) - output(JSON.stringify(expls, null, 2)) + this.npm.output(JSON.stringify(expls, null, 2)) else { - output(expls.map(expl => { + this.npm.output(expls.map(expl => { return explainNode(expl, Infinity, this.npm.color) }).join('\n\n')) } diff --git a/lib/explore.js b/lib/explore.js index fdfe6e1bc..e09e86740 100644 --- a/lib/explore.js +++ b/lib/explore.js @@ -5,7 +5,6 @@ const rpj = require('read-package-json-fast') const runScript = require('@npmcli/run-script') const { join, resolve, relative } = require('path') const completion = require('./utils/completion/installed-shallow.js') -const output = require('./utils/output.js') const usageUtil = require('./utils/usage.js') class Explore { @@ -54,7 +53,7 @@ class Explore { } if (!args.length) - output(`\nExploring ${path}\nType 'exit' or ^D when finished\n`) + this.npm.output(`\nExploring ${path}\nType 'exit' or ^D when finished\n`) this.npm.log.disableProgress() try { return await runScript({ diff --git a/lib/fund.js b/lib/fund.js index 1e9724266..826c3170e 100644 --- a/lib/fund.js +++ b/lib/fund.js @@ -12,7 +12,6 @@ const { } = require('libnpmfund') const completion = require('./utils/completion/installed-deep.js') -const output = require('./utils/output.js') const openUrl = require('./utils/open-url.js') const usageUtil = require('./utils/usage.js') @@ -85,7 +84,7 @@ class Fund { ? this.printJSON : this.printHuman - output( + this.npm.output( print( getFundingInfo(tree), opts @@ -206,9 +205,9 @@ class Fund { validSources.forEach(({ type, url }, i) => { const typePrefix = type ? `${type} funding` : 'Funding' const msg = `${typePrefix} available at the following URL` - output(`${i + 1}: ${msg}: ${url}`) + this.npm.output(`${i + 1}: ${msg}: ${url}`) }) - output('Run `npm fund [<@scope>/]<pkg> --which=1`, for example, to open the first funding URL listed in that package') + this.npm.output('Run `npm fund [<@scope>/]<pkg> --which=1`, for example, to open the first funding URL listed in that package') } else { const noFundingError = new Error(`No valid funding method available for: ${spec}`) noFundingError.code = 'ENOFUND' diff --git a/lib/help-search.js b/lib/help-search.js index ed2bc23b9..9648e3b14 100644 --- a/lib/help-search.js +++ b/lib/help-search.js @@ -1,7 +1,6 @@ const fs = require('fs') const path = require('path') const color = require('ansicolors') -const output = require('./utils/output.js') const usageUtil = require('./utils/usage.js') const npmUsage = require('./utils/npm-usage.js') const { promisify } = require('util') @@ -44,8 +43,8 @@ class HelpSearch { if (!formatted.trim()) npmUsage(this.npm, false) else { - output(formatted) - output(didYouMean(args[0], cmdList)) + this.npm.output(formatted) + this.npm.output(didYouMean(args[0], cmdList)) } } diff --git a/lib/help.js b/lib/help.js index d7897326f..ef7e3bfd0 100644 --- a/lib/help.js +++ b/lib/help.js @@ -4,7 +4,6 @@ const path = require('path') const log = require('npmlog') const openUrl = require('./utils/open-url.js') const glob = require('glob') -const output = require('./utils/output.js') const usage = require('./utils/usage.js') @@ -70,7 +69,7 @@ class Help { this.npm.commands[section].usage) { this.npm.config.set('loglevel', 'silent') log.level = 'silent' - output(this.npm.commands[section].usage) + this.npm.output(this.npm.commands[section].usage) return } diff --git a/lib/hook.js b/lib/hook.js index 312f542d7..a6f04d653 100644 --- a/lib/hook.js +++ b/lib/hook.js @@ -1,5 +1,4 @@ const hookApi = require('libnpmhook') -const output = require('./utils/output.js') const otplease = require('./utils/otplease.js') const relativeDate = require('tiny-relative-date') const Table = require('cli-table3') @@ -44,12 +43,12 @@ class Hook { async add (pkg, uri, secret, opts) { const hook = await hookApi.add(pkg, uri, secret, opts) if (opts.json) - output(JSON.stringify(hook, null, 2)) + this.npm.output(JSON.stringify(hook, null, 2)) else if (opts.parseable) { - output(Object.keys(hook).join('\t')) - output(Object.keys(hook).map(k => hook[k]).join('\t')) + this.npm.output(Object.keys(hook).join('\t')) + this.npm.output(Object.keys(hook).map(k => hook[k]).join('\t')) } else if (!opts.silent && opts.loglevel !== 'silent') { - output(`+ ${this.hookName(hook)} ${ + this.npm.output(`+ ${this.hookName(hook)} ${ opts.unicode ? ' ➜ ' : ' -> ' } ${hook.endpoint}`) } @@ -58,19 +57,19 @@ class Hook { async ls (pkg, opts) { const hooks = await hookApi.ls({ ...opts, package: pkg }) if (opts.json) - output(JSON.stringify(hooks, null, 2)) + this.npm.output(JSON.stringify(hooks, null, 2)) else if (opts.parseable) { - output(Object.keys(hooks[0]).join('\t')) + this.npm.output(Object.keys(hooks[0]).join('\t')) hooks.forEach(hook => { - output(Object.keys(hook).map(k => hook[k]).join('\t')) + this.npm.output(Object.keys(hook).map(k => hook[k]).join('\t')) }) } else if (!hooks.length) - output("You don't have any hooks configured yet.") + this.npm.output("You don't have any hooks configured yet.") else if (!opts.silent && opts.loglevel !== 'silent') { if (hooks.length === 1) - output('You have one hook configured.') + this.npm.output('You have one hook configured.') else - output(`You have ${hooks.length} hooks configured.`) + this.npm.output(`You have ${hooks.length} hooks configured.`) const table = new Table({ head: ['id', 'target', 'endpoint'] }) hooks.forEach((hook) => { @@ -90,19 +89,19 @@ class Hook { } else table.push([{ colSpan: 2, content: 'never triggered' }]) }) - output(table.toString()) + this.npm.output(table.toString()) } } async rm (id, opts) { const hook = await hookApi.rm(id, opts) if (opts.json) - output(JSON.stringify(hook, null, 2)) + this.npm.output(JSON.stringify(hook, null, 2)) else if (opts.parseable) { - output(Object.keys(hook).join('\t')) - output(Object.keys(hook).map(k => hook[k]).join('\t')) + this.npm.output(Object.keys(hook).join('\t')) + this.npm.output(Object.keys(hook).map(k => hook[k]).join('\t')) } else if (!opts.silent && opts.loglevel !== 'silent') { - output(`- ${this.hookName(hook)} ${ + this.npm.output(`- ${this.hookName(hook)} ${ opts.unicode ? ' ✘ ' : ' X ' } ${hook.endpoint}`) } @@ -111,12 +110,12 @@ class Hook { async update (id, uri, secret, opts) { const hook = await hookApi.update(id, uri, secret, opts) if (opts.json) - output(JSON.stringify(hook, null, 2)) + this.npm.output(JSON.stringify(hook, null, 2)) else if (opts.parseable) { - output(Object.keys(hook).join('\t')) - output(Object.keys(hook).map(k => hook[k]).join('\t')) + this.npm.output(Object.keys(hook).join('\t')) + this.npm.output(Object.keys(hook).map(k => hook[k]).join('\t')) } else if (!opts.silent && opts.loglevel !== 'silent') { - output(`+ ${this.hookName(hook)} ${ + this.npm.output(`+ ${this.hookName(hook)} ${ opts.unicode ? ' ➜ ' : ' -> ' } ${hook.endpoint}`) } diff --git a/lib/init.js b/lib/init.js index af97a9614..3f9abbcdd 100644 --- a/lib/init.js +++ b/lib/init.js @@ -2,7 +2,6 @@ const initJson = require('init-package-json') const npa = require('npm-package-arg') const usageUtil = require('./utils/usage.js') -const output = require('./utils/output.js') class Init { constructor (npm) { @@ -61,7 +60,7 @@ class Init { this.npm.log.disableProgress() const initFile = this.npm.config.get('init-module') if (!this.npm.flatOptions.yes && !this.npm.flatOptions.force) { - output([ + this.npm.output([ 'This utility will walk you through creating a package.json file.', 'It only covers the most common items, and tries to guess sensible defaults.', '', @@ -9,7 +9,6 @@ const npa = require('npm-package-arg') const usageUtil = require('./utils/usage.js') const completion = require('./utils/completion/installed-deep.js') -const output = require('./utils/output.js') const _depth = Symbol('depth') const _dedupe = Symbol('dedupe') @@ -147,7 +146,7 @@ class LS { const [rootError] = tree.errors.filter(e => e.code === 'EJSONPARSE' && e.path === resolve(path, 'package.json')) - output( + this.npm.output( json ? jsonOutput({ path, problems, result, rootError, seenItems }) : parseable diff --git a/lib/npm.js b/lib/npm.js index 1f8c785e7..0534e6306 100644 --- a/lib/npm.js +++ b/lib/npm.js @@ -282,6 +282,13 @@ const npm = module.exports = new class extends EventEmitter { } return resolve(this.config.get('tmp'), this[_tmpFolder]) } + + // output to stdout in a progress bar compatible way + output (...msg) { + this.log.clearProgress() + console.log(...msg) + this.log.showProgress() + } }() // now load everything required by the class methods diff --git a/lib/org.js b/lib/org.js index 054e1833d..2a08941a8 100644 --- a/lib/org.js +++ b/lib/org.js @@ -1,6 +1,5 @@ const liborg = require('libnpmorg') const usageUtil = require('./utils/usage.js') -const output = require('./utils/output.js') const otplease = require('./utils/otplease.js') const Table = require('cli-table3') @@ -72,17 +71,17 @@ class Org { return liborg.set(org, user, role, opts).then(memDeets => { if (opts.json) - output(JSON.stringify(memDeets, null, 2)) + this.npm.output(JSON.stringify(memDeets, null, 2)) else if (opts.parseable) { - output(['org', 'orgsize', 'user', 'role'].join('\t')) - output([ + this.npm.output(['org', 'orgsize', 'user', 'role'].join('\t')) + this.npm.output([ memDeets.org.name, memDeets.org.size, memDeets.user, memDeets.role, ].join('\t')) } else if (!opts.silent && opts.loglevel !== 'silent') - output(`Added ${memDeets.user} as ${memDeets.role} to ${memDeets.org.name}. You now have ${memDeets.org.size} member${memDeets.org.size === 1 ? '' : 's'} in this org.`) + this.npm.output(`Added ${memDeets.user} as ${memDeets.role} to ${memDeets.org.name}. You now have ${memDeets.org.size} member${memDeets.org.size === 1 ? '' : 's'} in this org.`) return memDeets }) @@ -102,17 +101,17 @@ class Org { org = org.replace(/^[~@]?/, '') const userCount = Object.keys(roster).length if (opts.json) { - output(JSON.stringify({ + this.npm.output(JSON.stringify({ user, org, userCount, deleted: true, })) } else if (opts.parseable) { - output(['user', 'org', 'userCount', 'deleted'].join('\t')) - output([user, org, userCount, true].join('\t')) + this.npm.output(['user', 'org', 'userCount', 'deleted'].join('\t')) + this.npm.output([user, org, userCount, true].join('\t')) } else if (!opts.silent && opts.loglevel !== 'silent') - output(`Successfully removed ${user} from ${org}. You now have ${userCount} member${userCount === 1 ? '' : 's'} in this org.`) + this.npm.output(`Successfully removed ${user} from ${org}. You now have ${userCount} member${userCount === 1 ? '' : 's'} in this org.`) }) } @@ -129,18 +128,18 @@ class Org { roster = newRoster } if (opts.json) - output(JSON.stringify(roster, null, 2)) + this.npm.output(JSON.stringify(roster, null, 2)) else if (opts.parseable) { - output(['user', 'role'].join('\t')) + this.npm.output(['user', 'role'].join('\t')) Object.keys(roster).forEach(user => { - output([user, roster[user]].join('\t')) + this.npm.output([user, roster[user]].join('\t')) }) } else if (!opts.silent && opts.loglevel !== 'silent') { const table = new Table({ head: ['user', 'role'] }) Object.keys(roster).sort().forEach(user => { table.push([user, roster[user]]) }) - output(table.toString()) + this.npm.output(table.toString()) } }) } diff --git a/lib/outdated.js b/lib/outdated.js index fc6967faf..be5820870 100644 --- a/lib/outdated.js +++ b/lib/outdated.js @@ -9,7 +9,6 @@ const pickManifest = require('npm-pick-manifest') const Arborist = require('@npmcli/arborist') -const output = require('./utils/output.js') const usageUtil = require('./utils/usage.js') const ansiTrim = require('./utils/ansi-trim.js') @@ -75,9 +74,9 @@ class Outdated { // display results if (this.opts.json) - output(this.makeJSON(outdated)) + this.npm.output(this.makeJSON(outdated)) else if (this.opts.parseable) - output(this.makeParseable(outdated)) + this.npm.output(this.makeParseable(outdated)) else { const outList = outdated.map(x => this.makePretty(x)) const outHead = ['Package', @@ -99,7 +98,7 @@ class Outdated { align: ['l', 'r', 'r', 'r', 'l'], stringLength: s => ansiTrim(s).length, } - output(table(outTable, tableOpts)) + this.npm.output(table(outTable, tableOpts)) } } diff --git a/lib/owner.js b/lib/owner.js index 6cb990488..cd387e94d 100644 --- a/lib/owner.js +++ b/lib/owner.js @@ -3,7 +3,6 @@ const npa = require('npm-package-arg') const npmFetch = require('npm-registry-fetch') const pacote = require('pacote') -const output = require('./utils/output.js') const otplease = require('./utils/otplease.js') const readLocalPkg = require('./utils/read-local-package.js') const usageUtil = require('./utils/usage.js') @@ -89,9 +88,9 @@ class Owner { const packumentOpts = { ...opts, fullMetadata: true } const { maintainers } = await pacote.packument(spec, packumentOpts) if (!maintainers || !maintainers.length) - output('no admin found') + this.npm.output('no admin found') else - output(maintainers.map(o => `${o.name} <${o.email}>`).join('\n')) + this.npm.output(maintainers.map(o => `${o.name} <${o.email}>`).join('\n')) return maintainers } catch (err) { @@ -114,7 +113,8 @@ class Owner { log.verbose('owner add', '%s to %s', user, pkg) const spec = npa(pkg) - return putOwners(spec, user, opts, validateAddOwner) + return this.putOwners(spec, user, opts, + (newOwner, owners) => this.validateAddOwner(newOwner, owners)) } async rm (user, pkg, opts) { @@ -131,109 +131,111 @@ class Owner { log.verbose('owner rm', '%s from %s', user, pkg) const spec = npa(pkg) - return putOwners(spec, user, opts, validateRmOwner) + return this.putOwners(spec, user, opts, + (rmOwner, owners) => this.validateRmOwner(rmOwner, owners)) } -} -module.exports = Owner -const validateAddOwner = (newOwner, owners) => { - owners = owners || [] - for (const o of owners) { - if (o.name === newOwner.name) { - log.info( - 'owner add', - 'Already a package owner: ' + o.name + ' <' + o.email + '>' - ) - return false - } - } - return [ - ...owners, - newOwner, - ] -} - -const validateRmOwner = (rmOwner, owners) => { - let found = false - const m = owners.filter(function (o) { - var match = (o.name === rmOwner.name) - found = found || match - return !match - }) - - if (!found) { - log.info('owner rm', 'Not a package owner: ' + rmOwner.name) - return false - } + async putOwners (spec, user, opts, validation) { + const uri = `/-/user/org.couchdb.user:${encodeURIComponent(user)}` + let u = '' - if (!m.length) { - throw Object.assign( - new Error( - 'Cannot remove all owners of a package. Add someone else first.' - ), - { code: 'EOWNERRM' } - ) - } + try { + u = await npmFetch.json(uri, opts) + } catch (err) { + log.error('owner mutate', `Error getting user data for ${user}`) + throw err + } - return m -} + if (user && (!u || !u.name || u.error)) { + throw Object.assign( + new Error( + "Couldn't get user data for " + user + ': ' + JSON.stringify(u) + ), + { code: 'EOWNERUSER' } + ) + } -const putOwners = async (spec, user, opts, validation) => { - const uri = `/-/user/org.couchdb.user:${encodeURIComponent(user)}` - let u = '' + // normalize user data + u = { name: u.name, email: u.email } - try { - u = await npmFetch.json(uri, opts) - } catch (err) { - log.error('owner mutate', `Error getting user data for ${user}`) - throw err - } + const data = await pacote.packument(spec, { ...opts, fullMetadata: true }) - if (user && (!u || !u.name || u.error)) { - throw Object.assign( - new Error( - "Couldn't get user data for " + user + ': ' + JSON.stringify(u) - ), - { code: 'EOWNERUSER' } - ) - } + // save the number of maintainers before validation for comparison + const before = data.maintainers ? data.maintainers.length : 0 - // normalize user data - u = { name: u.name, email: u.email } + const m = validation(u, data.maintainers) + if (!m) + return // invalid owners - const data = await pacote.packument(spec, { ...opts, fullMetadata: true }) + const body = { + _id: data._id, + _rev: data._rev, + maintainers: m, + } + const dataPath = `/${spec.escapedName}/-rev/${encodeURIComponent(data._rev)}` + const res = await otplease(opts, opts => { + return npmFetch.json(dataPath, { + ...opts, + method: 'PUT', + body, + spec, + }) + }) - // save the number of maintainers before validation for comparison - const before = data.maintainers ? data.maintainers.length : 0 + if (!res.error) { + if (m.length < before) + this.npm.output(`- ${user} (${spec.name})`) + else + this.npm.output(`+ ${user} (${spec.name})`) + } else { + throw Object.assign( + new Error('Failed to update package: ' + JSON.stringify(res)), + { code: 'EOWNERMUTATE' } + ) + } + return res + } + + validateAddOwner (newOwner, owners) { + owners = owners || [] + for (const o of owners) { + if (o.name === newOwner.name) { + log.info( + 'owner add', + 'Already a package owner: ' + o.name + ' <' + o.email + '>' + ) + return false + } + } + return [ + ...owners, + newOwner, + ] + } + + validateRmOwner (rmOwner, owners) { + let found = false + const m = owners.filter(function (o) { + var match = (o.name === rmOwner.name) + found = found || match + return !match + }) + + if (!found) { + log.info('owner rm', 'Not a package owner: ' + rmOwner.name) + return false + } - const m = validation(u, data.maintainers) - if (!m) - return // invalid owners + if (!m.length) { + throw Object.assign( + new Error( + 'Cannot remove all owners of a package. Add someone else first.' + ), + { code: 'EOWNERRM' } + ) + } - const body = { - _id: data._id, - _rev: data._rev, - maintainers: m, - } - const dataPath = `/${spec.escapedName}/-rev/${encodeURIComponent(data._rev)}` - const res = await otplease(opts, opts => - npmFetch.json(dataPath, { - ...opts, - method: 'PUT', - body, - spec, - })) - - if (!res.error) { - if (m.length < before) - output(`- ${user} (${spec.name})`) - else - output(`+ ${user} (${spec.name})`) - } else { - throw Object.assign( - new Error('Failed to update package: ' + JSON.stringify(res)), - { code: 'EOWNERMUTATE' } - ) + return m } - return res } +module.exports = Owner diff --git a/lib/pack.js b/lib/pack.js index cf1e77f48..7ffe3138e 100644 --- a/lib/pack.js +++ b/lib/pack.js @@ -7,7 +7,6 @@ const npa = require('npm-package-arg') const { getContents, logTar } = require('./utils/tar.js') const writeFile = util.promisify(require('fs').writeFile) -const output = require('./utils/output.js') const usageUtil = require('./utils/usage.js') @@ -49,7 +48,7 @@ class Pack { for (const tar of tarballs) { logTar(tar, { log, unicode }) - output(tar.filename.replace(/^@/, '').replace(/\//, '-')) + this.npm.output(tar.filename.replace(/^@/, '').replace(/\//, '-')) } } } diff --git a/lib/ping.js b/lib/ping.js index e43f0640f..3643fe3b6 100644 --- a/lib/ping.js +++ b/lib/ping.js @@ -1,5 +1,4 @@ const log = require('npmlog') -const output = require('./utils/output.js') const usageUtil = require('./utils/usage.js') const pingUtil = require('./utils/ping.js') @@ -24,7 +23,7 @@ class Ping { const time = Date.now() - start log.notice('PONG', `${time / 1000}ms`) if (this.npm.flatOptions.json) { - output(JSON.stringify({ + this.npm.output(JSON.stringify({ registry: this.npm.flatOptions.registry, time, details, diff --git a/lib/prefix.js b/lib/prefix.js index e46f9c4cd..8ec5ab9ef 100644 --- a/lib/prefix.js +++ b/lib/prefix.js @@ -1,4 +1,3 @@ -const output = require('./utils/output.js') const usageUtil = require('./utils/usage.js') class Prefix { @@ -16,7 +15,7 @@ class Prefix { } async prefix (args) { - return output(this.npm.prefix) + return this.npm.output(this.npm.prefix) } } module.exports = Prefix diff --git a/lib/profile.js b/lib/profile.js index dab99092b..a0a860601 100644 --- a/lib/profile.js +++ b/lib/profile.js @@ -7,7 +7,6 @@ const qrcodeTerminal = require('qrcode-terminal') const Table = require('cli-table3') const otplease = require('./utils/otplease.js') -const output = require('./utils/output.js') const pulseTillDone = require('./utils/pulse-till-done.js') const readUserInfo = require('./utils/read-user-info.js') const usageUtil = require('./utils/usage.js') @@ -116,7 +115,7 @@ class Profile { delete info.cidr_whitelist if (conf.json) { - output(JSON.stringify(info, null, 2)) + this.npm.output(JSON.stringify(info, null, 2)) return } @@ -145,21 +144,21 @@ class Profile { .filter((arg) => arg.trim() !== '') .map((arg) => cleaned[arg]) .join('\t') - output(values) + this.npm.output(values) } else { if (conf.parseable) { for (const key of Object.keys(info)) { if (key === 'tfa') - output(`${key}\t${cleaned[tfa]}`) + this.npm.output(`${key}\t${cleaned[tfa]}`) else - output(`${key}\t${info[key]}`) + this.npm.output(`${key}\t${info[key]}`) } } else { const table = new Table() for (const key of Object.keys(cleaned)) table.push({ [ansistyles.bright(key)]: cleaned[key] }) - output(table.toString()) + this.npm.output(table.toString()) } } } @@ -215,13 +214,13 @@ class Profile { const result = await otplease(conf, conf => npmProfile.set(newUser, conf)) if (conf.json) - output(JSON.stringify({ [prop]: result[prop] }, null, 2)) + this.npm.output(JSON.stringify({ [prop]: result[prop] }, null, 2)) else if (conf.parseable) - output(prop + '\t' + result[prop]) + this.npm.output(prop + '\t' + result[prop]) else if (result[prop] != null) - output('Set', prop, 'to', result[prop]) + this.npm.output('Set', prop, 'to', result[prop]) else - output('Set', prop) + this.npm.output('Set', prop) } async enable2fa (args) { @@ -327,7 +326,7 @@ class Profile { ) if (challenge.tfa === null) { - output('Two factor authentication mode changed to: ' + mode) + this.npm.output('Two factor authentication mode changed to: ' + mode) return } @@ -344,7 +343,7 @@ class Profile { const secret = otpauth.searchParams.get('secret') const code = await qrcode(challenge.tfa) - output( + this.npm.output( 'Scan into your authenticator app:\n' + code + '\n Or enter code:', secret ) @@ -355,17 +354,17 @@ class Profile { const result = await npmProfile.set({ tfa: [interactiveOTP] }, conf) - output( + this.npm.output( '2FA successfully enabled. Below are your recovery codes, ' + 'please print these out.' ) - output( + this.npm.output( 'You will need these to recover access to your account ' + 'if you lose your authentication device.' ) for (const tfaCode of result.tfa) - output('\t' + tfaCode) + this.npm.output('\t' + tfaCode) } async disable2fa (args) { @@ -373,7 +372,7 @@ class Profile { const info = await pulseTillDone.withPromise(npmProfile.get(conf)) if (!info.tfa || info.tfa.pending) { - output('Two factor authentication not enabled.') + this.npm.output('Two factor authentication not enabled.') return } @@ -391,11 +390,11 @@ class Profile { }, conf)) if (conf.json) - output(JSON.stringify({ tfa: false }, null, 2)) + this.npm.output(JSON.stringify({ tfa: false }, null, 2)) else if (conf.parseable) - output('tfa\tfalse') + this.npm.output('tfa\tfalse') else - output('Two factor authentication disabled.') + this.npm.output('Two factor authentication disabled.') } } module.exports = Profile diff --git a/lib/publish.js b/lib/publish.js index c8e82c44c..b0bf92213 100644 --- a/lib/publish.js +++ b/lib/publish.js @@ -9,7 +9,6 @@ const npa = require('npm-package-arg') const npmFetch = require('npm-registry-fetch') const { flatten } = require('./utils/flat-options.js') -const output = require('./utils/output.js') const otplease = require('./utils/otplease.js') const usageUtil = require('./utils/usage.js') const { getContents, logTar } = require('./utils/tar.js') @@ -115,9 +114,9 @@ class Publish { const silent = log.level === 'silent' if (!silent && json) - output(JSON.stringify(pkgContents, null, 2)) + this.npm.output(JSON.stringify(pkgContents, null, 2)) else if (!silent) - output(`+ ${pkgContents.id}`) + this.npm.output(`+ ${pkgContents.id}`) return pkgContents } diff --git a/lib/rebuild.js b/lib/rebuild.js index 1091b0158..ffbdebc21 100644 --- a/lib/rebuild.js +++ b/lib/rebuild.js @@ -3,7 +3,6 @@ const Arborist = require('@npmcli/arborist') const npa = require('npm-package-arg') const semver = require('semver') const usageUtil = require('./utils/usage.js') -const output = require('./utils/output.js') const completion = require('./utils/completion/installed-deep.js') class Rebuild { @@ -52,7 +51,7 @@ class Rebuild { } else await arb.rebuild() - output('rebuilt dependencies successfully') + this.npm.output('rebuilt dependencies successfully') } isNode (specs, node) { diff --git a/lib/root.js b/lib/root.js index 8e5ac63d7..7c3fa2bbb 100644 --- a/lib/root.js +++ b/lib/root.js @@ -1,4 +1,3 @@ -const output = require('./utils/output.js') const usageUtil = require('./utils/usage.js') class Root { @@ -16,7 +15,7 @@ class Root { } async root () { - output(this.npm.dir) + this.npm.output(this.npm.dir) } } module.exports = Root diff --git a/lib/run-script.js b/lib/run-script.js index cdfd88f10..dc822668d 100644 --- a/lib/run-script.js +++ b/lib/run-script.js @@ -2,7 +2,6 @@ const runScript = require('@npmcli/run-script') const { isServerPackage } = runScript const readJson = require('read-package-json-fast') const { resolve } = require('path') -const output = require('./utils/output.js') const log = require('npmlog') const usageUtil = require('./utils/usage.js') const didYouMean = require('./utils/did-you-mean.js') @@ -117,13 +116,13 @@ class RunScript { return allScripts if (this.npm.flatOptions.json) { - output(JSON.stringify(scripts, null, 2)) + this.npm.output(JSON.stringify(scripts, null, 2)) return allScripts } if (this.npm.flatOptions.parseable) { for (const [script, cmd] of Object.entries(scripts)) - output(`${script}:${cmd}`) + this.npm.output(`${script}:${cmd}`) return allScripts } @@ -138,18 +137,18 @@ class RunScript { } if (cmds.length) - output(`Lifecycle scripts included in ${name}:`) + this.npm.output(`Lifecycle scripts included in ${name}:`) for (const script of cmds) - output(prefix + script + indent + scripts[script]) + this.npm.output(prefix + script + indent + scripts[script]) if (!cmds.length && runScripts.length) - output(`Scripts available in ${name} via \`npm run-script\`:`) + this.npm.output(`Scripts available in ${name} via \`npm run-script\`:`) else if (runScripts.length) - output('\navailable via `npm run-script`:') + this.npm.output('\navailable via `npm run-script`:') for (const script of runScripts) - output(prefix + script + indent + scripts[script]) + this.npm.output(prefix + script + indent + scripts[script]) return allScripts } diff --git a/lib/search.js b/lib/search.js index e0922b984..35e3eeb0e 100644 --- a/lib/search.js +++ b/lib/search.js @@ -5,7 +5,6 @@ const log = require('npmlog') const formatPackageStream = require('./search/format-package-stream.js') const packageFilter = require('./search/package-filter.js') -const output = require('./utils/output.js') const usageUtil = require('./utils/usage.js') function prepareIncludes (args) { @@ -83,12 +82,12 @@ class Search { p.on('data', chunk => { if (!anyOutput) anyOutput = true - output(chunk.toString('utf8')) + this.npm.output(chunk.toString('utf8')) }) await p.promise() if (!anyOutput && !opts.json && !opts.parseable) - output('No matches found for ' + (args.map(JSON.stringify).join(' '))) + this.npm.output('No matches found for ' + (args.map(JSON.stringify).join(' '))) log.silly('search', 'search completed') log.clearProgress() diff --git a/lib/star.js b/lib/star.js index b39d23b2c..073c93a89 100644 --- a/lib/star.js +++ b/lib/star.js @@ -2,7 +2,6 @@ const fetch = require('npm-registry-fetch') const log = require('npmlog') const npa = require('npm-package-arg') -const output = require('./utils/output.js') const usageUtil = require('./utils/usage.js') const getIdentity = require('./utils/get-identity') @@ -73,7 +72,7 @@ class Star { body, }) - output(show + ' ' + pkg.name) + this.npm.output(show + ' ' + pkg.name) log.verbose('star', data) return data } diff --git a/lib/stars.js b/lib/stars.js index fe280705b..e0a6a0003 100644 --- a/lib/stars.js +++ b/lib/stars.js @@ -1,7 +1,6 @@ const log = require('npmlog') const fetch = require('npm-registry-fetch') -const output = require('./utils/output.js') const getIdentity = require('./utils/get-identity.js') const usageUtil = require('./utils/usage.js') @@ -36,7 +35,7 @@ class Stars { log.warn('stars', 'user has not starred any packages') for (const row of rows) - output(row.value) + this.npm.output(row.value) } } module.exports = Stars diff --git a/lib/team.js b/lib/team.js index 4947739a0..3ba2c023d 100644 --- a/lib/team.js +++ b/lib/team.js @@ -1,7 +1,6 @@ const columns = require('cli-columns') const libteam = require('libnpmteam') -const output = require('./utils/output.js') const otplease = require('./utils/otplease.js') const usageUtil = require('./utils/usage.js') @@ -66,82 +65,82 @@ class Team { async create (entity, opts) { await libteam.create(entity, opts) if (opts.json) { - output(JSON.stringify({ + this.npm.output(JSON.stringify({ created: true, team: entity, })) } else if (opts.parseable) - output(`${entity}\tcreated`) + this.npm.output(`${entity}\tcreated`) else if (!opts.silent && opts.loglevel !== 'silent') - output(`+@${entity}`) + this.npm.output(`+@${entity}`) } async destroy (entity, opts) { await libteam.destroy(entity, opts) if (opts.json) { - output(JSON.stringify({ + this.npm.output(JSON.stringify({ deleted: true, team: entity, })) } else if (opts.parseable) - output(`${entity}\tdeleted`) + this.npm.output(`${entity}\tdeleted`) else if (!opts.silent && opts.loglevel !== 'silent') - output(`-@${entity}`) + this.npm.output(`-@${entity}`) } async add (entity, user, opts) { await libteam.add(user, entity, opts) if (opts.json) { - output(JSON.stringify({ + this.npm.output(JSON.stringify({ added: true, team: entity, user, })) } else if (opts.parseable) - output(`${user}\t${entity}\tadded`) + this.npm.output(`${user}\t${entity}\tadded`) else if (!opts.silent && opts.loglevel !== 'silent') - output(`${user} added to @${entity}`) + this.npm.output(`${user} added to @${entity}`) } async rm (entity, user, opts) { await libteam.rm(user, entity, opts) if (opts.json) { - output(JSON.stringify({ + this.npm.output(JSON.stringify({ removed: true, team: entity, user, })) } else if (opts.parseable) - output(`${user}\t${entity}\tremoved`) + this.npm.output(`${user}\t${entity}\tremoved`) else if (!opts.silent && opts.loglevel !== 'silent') - output(`${user} removed from @${entity}`) + this.npm.output(`${user} removed from @${entity}`) } async listUsers (entity, opts) { const users = (await libteam.lsUsers(entity, opts)).sort() if (opts.json) - output(JSON.stringify(users, null, 2)) + this.npm.output(JSON.stringify(users, null, 2)) else if (opts.parseable) - output(users.join('\n')) + this.npm.output(users.join('\n')) else if (!opts.silent && opts.loglevel !== 'silent') { const plural = users.length === 1 ? '' : 's' const more = users.length === 0 ? '' : ':\n' - output(`\n@${entity} has ${users.length} user${plural}${more}`) - output(columns(users, { padding: 1 })) + this.npm.output(`\n@${entity} has ${users.length} user${plural}${more}`) + this.npm.output(columns(users, { padding: 1 })) } } async listTeams (entity, opts) { const teams = (await libteam.lsTeams(entity, opts)).sort() if (opts.json) - output(JSON.stringify(teams, null, 2)) + this.npm.output(JSON.stringify(teams, null, 2)) else if (opts.parseable) - output(teams.join('\n')) + this.npm.output(teams.join('\n')) else if (!opts.silent && opts.loglevel !== 'silent') { const plural = teams.length === 1 ? '' : 's' const more = teams.length === 0 ? '' : ':\n' - output(`\n@${entity} has ${teams.length} team${plural}${more}`) - output(columns(teams.map(t => `@${t}`), { padding: 1 })) + this.npm.output(`\n@${entity} has ${teams.length} team${plural}${more}`) + this.npm.output(columns(teams.map(t => `@${t}`), { padding: 1 })) } } } diff --git a/lib/token.js b/lib/token.js index ad6d5c6fc..ad634c0b0 100644 --- a/lib/token.js +++ b/lib/token.js @@ -5,7 +5,6 @@ const log = require('npmlog') const profile = require('npm-profile') const otplease = require('./utils/otplease.js') -const output = require('./utils/output.js') const pulseTillDone = require('./utils/pulse-till-done.js') const readUserInfo = require('./utils/read-user-info.js') const usageUtil = require('./utils/usage.js') @@ -64,12 +63,12 @@ class Token { log.info('token', 'getting list') const tokens = await pulseTillDone.withPromise(profile.listTokens(conf)) if (conf.json) { - output(JSON.stringify(tokens, null, 2)) + this.npm.output(JSON.stringify(tokens, null, 2)) return } else if (conf.parseable) { - output(['key', 'token', 'created', 'readonly', 'CIDR whitelist'].join('\t')) + this.npm.output(['key', 'token', 'created', 'readonly', 'CIDR whitelist'].join('\t')) tokens.forEach((token) => { - output([ + this.npm.output([ token.key, token.token, token.created, @@ -95,7 +94,7 @@ class Token { token.cidr_whitelist ? token.cidr_whitelist.join(', ') : '', ]) }) - output(table.toString()) + this.npm.output(table.toString()) } async rm (args) { @@ -127,11 +126,11 @@ class Token { }) })) if (conf.json) - output(JSON.stringify(toRemove)) + this.npm.output(JSON.stringify(toRemove)) else if (conf.parseable) - output(toRemove.join('\t')) + this.npm.output(toRemove.join('\t')) else - output('Removed ' + toRemove.length + ' token' + (toRemove.length !== 1 ? 's' : '')) + this.npm.output('Removed ' + toRemove.length + ' token' + (toRemove.length !== 1 ? 's' : '')) } async create (args) { @@ -149,14 +148,14 @@ class Token { delete result.key delete result.updated if (conf.json) - output(JSON.stringify(result)) + this.npm.output(JSON.stringify(result)) else if (conf.parseable) - Object.keys(result).forEach((k) => output(k + '\t' + result[k])) + Object.keys(result).forEach((k) => this.npm.output(k + '\t' + result[k])) else { const table = new Table() for (const k of Object.keys(result)) table.push({ [ansistyles.bright(k)]: String(result[k]) }) - output(table.toString()) + this.npm.output(table.toString()) } }) } diff --git a/lib/unpublish.js b/lib/unpublish.js index 34751da4a..acba6ea52 100644 --- a/lib/unpublish.js +++ b/lib/unpublish.js @@ -8,7 +8,6 @@ const libunpub = require('libnpmpublish').unpublish const readJson = util.promisify(require('read-package-json')) const usageUtil = require('./utils/usage.js') -const output = require('./utils/output.js') const otplease = require('./utils/otplease.js') const getIdentity = require('./utils/get-identity.js') @@ -107,7 +106,7 @@ class Unpublish { } if (!silent && loglevel !== 'silent') - output(`- ${pkgName}${pkgVersion}`) + this.npm.output(`- ${pkgName}${pkgVersion}`) } } module.exports = Unpublish diff --git a/lib/utils/audit-error.js b/lib/utils/audit-error.js index ae0749ff6..c58c1d16e 100644 --- a/lib/utils/audit-error.js +++ b/lib/utils/audit-error.js @@ -3,7 +3,6 @@ // prints a JSON version of the error if it's --json // returns 'true' if there was an error, false otherwise -const output = require('./output.js') const auditError = (npm, report) => { if (!report || !report.error) return false @@ -18,7 +17,7 @@ const auditError = (npm, report) => { const { body: errBody } = error const body = Buffer.isBuffer(errBody) ? errBody.toString() : errBody if (npm.flatOptions.json) { - output(JSON.stringify({ + npm.output(JSON.stringify({ message: error.message, method: error.method, uri: error.uri, @@ -27,7 +26,7 @@ const auditError = (npm, report) => { body, }, null, 2)) } else - output(body) + npm.output(body) throw 'audit endpoint returned an error' } diff --git a/lib/utils/npm-usage.js b/lib/utils/npm-usage.js index 220f8037f..b77bca7be 100644 --- a/lib/utils/npm-usage.js +++ b/lib/utils/npm-usage.js @@ -1,6 +1,5 @@ const didYouMean = require('./did-you-mean.js') const { dirname } = require('path') -const output = require('./output.js') const { cmdList } = require('./cmd-list') module.exports = (npm, valid = true) => { @@ -8,7 +7,7 @@ module.exports = (npm, valid = true) => { const usesBrowser = npm.config.get('viewer') === 'browser' ? ' (in a browser)' : '' npm.log.level = 'silent' - output(` + npm.output(` Usage: npm <command> npm install install all the dependencies in your project @@ -34,7 +33,7 @@ npm@${npm.version} ${dirname(dirname(__dirname))} `) if (npm.argv.length >= 1) - output(didYouMean(npm.argv[0], cmdList)) + npm.output(didYouMean(npm.argv[0], cmdList)) if (!valid) process.exitCode = 1 diff --git a/lib/utils/open-url.js b/lib/utils/open-url.js index 1fe456bd0..41fac33ec 100644 --- a/lib/utils/open-url.js +++ b/lib/utils/open-url.js @@ -1,4 +1,3 @@ -const output = require('./output.js') const opener = require('opener') const { URL } = require('url') @@ -16,7 +15,7 @@ const open = async (npm, url, errMsg) => { }, null, 2) : `${errMsg}:\n ${url}\n` - output(alternateMsg) + npm.output(alternateMsg) } if (browser === false) { diff --git a/lib/utils/output.js b/lib/utils/output.js deleted file mode 100644 index 2d1549859..000000000 --- a/lib/utils/output.js +++ /dev/null @@ -1,7 +0,0 @@ -const log = require('npmlog') -// output to stdout in a progress bar compatible way -module.exports = (...msg) => { - log.clearProgress() - console.log(...msg) - log.showProgress() -} diff --git a/lib/utils/reify-output.js b/lib/utils/reify-output.js index 216f0e902..ddad32121 100644 --- a/lib/utils/reify-output.js +++ b/lib/utils/reify-output.js @@ -10,7 +10,6 @@ // run `npm audit fix` to fix them, or `npm audit` for details const log = require('npmlog') -const output = require('./output.js') const { depth } = require('treeverse') const ms = require('ms') const auditReport = require('npm-audit-report') @@ -72,10 +71,10 @@ const reifyOutput = (npm, arb) => { summary.audit = npm.command === 'audit' ? auditReport : auditReport.toJSON().metadata } - output(JSON.stringify(summary, 0, 2)) + npm.output(JSON.stringify(summary, 0, 2)) } else { packagesChangedMessage(npm, summary) - packagesFundingMessage(summary) + packagesFundingMessage(npm, summary) printAuditReport(npm, auditReport) } } @@ -98,7 +97,7 @@ const printAuditReport = (npm, report) => { auditLevel, }) process.exitCode = process.exitCode || res.exitCode - output('\n' + res.report) + npm.output('\n' + res.report) } const packagesChangedMessage = (npm, { added, removed, changed, audited }) => { @@ -136,18 +135,18 @@ const packagesChangedMessage = (npm, { added, removed, changed, audited }) => { msg.push(`audited ${audited} package${audited === 1 ? '' : 's'}`) msg.push(` in ${ms(Date.now() - npm.started)}`) - output(msg.join('')) + npm.output(msg.join('')) } -const packagesFundingMessage = ({ funding }) => { +const packagesFundingMessage = (npm, { funding }) => { if (!funding) return - output('') + npm.output('') const pkg = funding === 1 ? 'package' : 'packages' const is = funding === 1 ? 'is' : 'are' - output(`${funding} ${pkg} ${is} looking for funding`) - output(' run `npm fund` for details') + npm.output(`${funding} ${pkg} ${is} looking for funding`) + npm.output(' run `npm fund` for details') } module.exports = reifyOutput diff --git a/lib/version.js b/lib/version.js index 1ba834f5d..a7c0c1955 100644 --- a/lib/version.js +++ b/lib/version.js @@ -1,5 +1,4 @@ const libversion = require('libnpmversion') -const output = require('./utils/output.js') const usageUtil = require('./utils/usage.js') class Version { @@ -56,7 +55,7 @@ class Version { ...this.npm.flatOptions, path: this.npm.prefix, }) - return output(`${prefix}${version}`) + return this.npm.output(`${prefix}${version}`) } async list () { @@ -78,9 +77,9 @@ class Version { results[key] = version if (this.npm.flatOptions.json) - output(JSON.stringify(results, null, 2)) + this.npm.output(JSON.stringify(results, null, 2)) else - output(results) + this.npm.output(results) } } module.exports = Version diff --git a/lib/whoami.js b/lib/whoami.js index 39184ed9c..7ce877104 100644 --- a/lib/whoami.js +++ b/lib/whoami.js @@ -1,4 +1,3 @@ -const output = require('./utils/output.js') const getIdentity = require('./utils/get-identity.js') const usageUtil = require('./utils/usage.js') @@ -23,7 +22,7 @@ class Whoami { async whoami (args) { const opts = this.npm.flatOptions const username = await getIdentity(this.npm, opts) - output(opts.json ? JSON.stringify(username) : username) + this.npm.output(opts.json ? JSON.stringify(username) : username) } } module.exports = Whoami |