Skip to content

Commit 09b58e4

Browse files
authored
fix: make all color output use an npm instance of chalk (#6284)
1 parent a57a97b commit 09b58e4

25 files changed

+381
-413
lines changed

lib/commands/explain.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -78,7 +78,7 @@ class Explain extends ArboristWorkspaceCmd {
7878
this.npm.output(JSON.stringify(expls, null, 2))
7979
} else {
8080
this.npm.output(expls.map(expl => {
81-
return explainNode(expl, Infinity, this.npm.color)
81+
return explainNode(expl, Infinity, this.npm.chalk)
8282
}).join('\n\n'))
8383
}
8484
}

lib/commands/fund.js

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
const archy = require('archy')
22
const Arborist = require('@npmcli/arborist')
3-
const chalk = require('chalk')
43
const pacote = require('pacote')
54
const semver = require('semver')
65
const npa = require('npm-package-arg')
@@ -96,7 +95,6 @@ class Fund extends ArboristWorkspaceCmd {
9695
}
9796

9897
printHuman (fundingInfo) {
99-
const color = this.npm.color
10098
const unicode = this.npm.config.get('unicode')
10199
const seenUrls = new Map()
102100

@@ -117,7 +115,7 @@ class Fund extends ArboristWorkspaceCmd {
117115

118116
if (url) {
119117
item.label = tree({
120-
label: color ? chalk.bgBlack.white(url) : url,
118+
label: this.npm.chalk.bgBlack.white(url),
121119
nodes: [pkgRef],
122120
}).trim()
123121

@@ -154,7 +152,7 @@ class Fund extends ArboristWorkspaceCmd {
154152
})
155153

156154
const res = tree(result)
157-
return color ? chalk.reset(res) : res
155+
return this.npm.chalk.reset(res)
158156
}
159157

160158
async openFundingUrl ({ path, tree, spec, fundingSourceNumber }) {

lib/commands/help-search.js

Lines changed: 1 addition & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
const { readFile } = require('fs/promises')
22
const path = require('path')
3-
const chalk = require('chalk')
43
const glob = require('glob')
54
const BaseCommand = require('../base-command.js')
65

@@ -163,18 +162,14 @@ class HelpSearch extends BaseCommand {
163162
return
164163
}
165164

166-
if (!this.npm.color) {
167-
out.push(line + '\n')
168-
return
169-
}
170165
const hilitLine = []
171166
for (const arg of args) {
172167
const finder = line.toLowerCase().split(arg.toLowerCase())
173168
let p = 0
174169
for (const f of finder) {
175170
hilitLine.push(line.slice(p, p + f.length))
176171
const word = line.slice(p + f.length, p + f.length + arg.length)
177-
const hilit = chalk.bgBlack.red(word)
172+
const hilit = this.npm.chalk.bgBlack.red(word)
178173
hilitLine.push(hilit)
179174
p += f.length + arg.length
180175
}

lib/commands/ls.js

Lines changed: 13 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@ const relativePrefix = `.${sep}`
33
const { EOL } = require('os')
44

55
const archy = require('archy')
6-
const chalk = require('chalk')
76
const Arborist = require('@npmcli/arborist')
87
const { breadth } = require('treeverse')
98
const npa = require('npm-package-arg')
@@ -50,7 +49,7 @@ class LS extends ArboristWorkspaceCmd {
5049

5150
async exec (args) {
5251
const all = this.npm.config.get('all')
53-
const color = this.npm.color
52+
const chalk = this.npm.chalk
5453
const depth = this.npm.config.get('depth')
5554
const global = this.npm.global
5655
const json = this.npm.config.get('json')
@@ -157,7 +156,7 @@ class LS extends ArboristWorkspaceCmd {
157156
? getJsonOutputItem(node, { global, long })
158157
: parseable
159158
? null
160-
: getHumanOutputItem(node, { args, color, global, long })
159+
: getHumanOutputItem(node, { args, chalk, global, long })
161160

162161
// loop through list of node problems to add them to global list
163162
if (node[_include]) {
@@ -180,7 +179,7 @@ class LS extends ArboristWorkspaceCmd {
180179
this.npm.outputBuffer(
181180
json ? jsonOutput({ path, problems, result, rootError, seenItems }) :
182181
parseable ? parseableOutput({ seenNodes, global, long }) :
183-
humanOutput({ color, result, seenItems, unicode })
182+
humanOutput({ chalk, result, seenItems, unicode })
184183
)
185184

186185
// if filtering items, should exit with error code on no results
@@ -278,9 +277,9 @@ const augmentItemWithIncludeMetadata = (node, item) => {
278277
return item
279278
}
280279

281-
const getHumanOutputItem = (node, { args, color, global, long }) => {
280+
const getHumanOutputItem = (node, { args, chalk, global, long }) => {
282281
const { pkgid, path } = node
283-
const workspacePkgId = color ? chalk.green(pkgid) : pkgid
282+
const workspacePkgId = chalk.green(pkgid)
284283
let printable = node.isWorkspace ? workspacePkgId : pkgid
285284

286285
// special formatting for top-level package name
@@ -293,8 +292,7 @@ const getHumanOutputItem = (node, { args, color, global, long }) => {
293292
}
294293
}
295294

296-
const highlightDepName =
297-
color && args.length && node[_filteredBy]
295+
const highlightDepName = args.length && node[_filteredBy]
298296
const missingColor = isOptional(node)
299297
? chalk.yellow.bgBlack
300298
: chalk.red.bgBlack
@@ -308,28 +306,28 @@ const getHumanOutputItem = (node, { args, color, global, long }) => {
308306
const label =
309307
(
310308
node[_missing]
311-
? (color ? missingColor(missingMsg) : missingMsg) + ' '
309+
? missingColor(missingMsg) + ' '
312310
: ''
313311
) +
314312
`${highlightDepName ? chalk.yellow.bgBlack(printable) : printable}` +
315313
(
316314
node[_dedupe]
317-
? ' ' + (color ? chalk.gray('deduped') : 'deduped')
315+
? ' ' + chalk.gray('deduped')
318316
: ''
319317
) +
320318
(
321319
invalid
322-
? ' ' + (color ? chalk.red.bgBlack(invalid) : invalid)
320+
? ' ' + chalk.red.bgBlack(invalid)
323321
: ''
324322
) +
325323
(
326324
isExtraneous(node, { global })
327-
? ' ' + (color ? chalk.green.bgBlack('extraneous') : 'extraneous')
325+
? ' ' + chalk.green.bgBlack('extraneous')
328326
: ''
329327
) +
330328
(
331329
node.overridden
332-
? ' ' + (color ? chalk.gray('overridden') : 'overridden')
330+
? ' ' + chalk.gray('overridden')
333331
: ''
334332
) +
335333
(isGitNode(node) ? ` (${node.resolved})` : '') +
@@ -504,7 +502,7 @@ const augmentNodesWithMetadata = ({
504502

505503
const sortAlphabetically = ({ pkgid: a }, { pkgid: b }) => localeCompare(a, b)
506504

507-
const humanOutput = ({ color, result, seenItems, unicode }) => {
505+
const humanOutput = ({ chalk, result, seenItems, unicode }) => {
508506
// we need to traverse the entire tree in order to determine which items
509507
// should be included (since a nested transitive included dep will make it
510508
// so that all its ancestors should be displayed)
@@ -520,7 +518,7 @@ const humanOutput = ({ color, result, seenItems, unicode }) => {
520518
}
521519

522520
const archyOutput = archy(result, '', { unicode })
523-
return color ? chalk.reset(archyOutput) : archyOutput
521+
return chalk.reset(archyOutput)
524522
}
525523

526524
const jsonOutput = ({ path, problems, result, rootError, seenItems }) => {

lib/commands/outdated.js

Lines changed: 6 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@ const os = require('os')
22
const { resolve } = require('path')
33
const pacote = require('pacote')
44
const table = require('text-table')
5-
const chalk = require('chalk')
65
const npa = require('npm-package-arg')
76
const pickManifest = require('npm-pick-manifest')
87
const localeCompare = require('@isaacs/string-locale-compare')('en')
@@ -104,9 +103,7 @@ class Outdated extends ArboristWorkspaceCmd {
104103
}
105104
const outTable = [outHead].concat(outList)
106105

107-
if (this.npm.color) {
108-
outTable[0] = outTable[0].map(heading => chalk.underline(heading))
109-
}
106+
outTable[0] = outTable[0].map(heading => this.npm.chalk.underline(heading))
110107

111108
const tableOpts = {
112109
align: ['l', 'r', 'r', 'r', 'l'],
@@ -281,8 +278,8 @@ class Outdated extends ArboristWorkspaceCmd {
281278
? node.pkgid
282279
: node.name
283280

284-
return this.npm.color && humanOutput
285-
? chalk.green(workspaceName)
281+
return humanOutput
282+
? this.npm.chalk.green(workspaceName)
286283
: workspaceName
287284
}
288285

@@ -306,11 +303,9 @@ class Outdated extends ArboristWorkspaceCmd {
306303
columns[7] = homepage
307304
}
308305

309-
if (this.npm.color) {
310-
columns[0] = chalk[current === wanted ? 'yellow' : 'red'](columns[0]) // current
311-
columns[2] = chalk.green(columns[2]) // wanted
312-
columns[3] = chalk.magenta(columns[3]) // latest
313-
}
306+
columns[0] = this.npm.chalk[current === wanted ? 'yellow' : 'red'](columns[0]) // current
307+
columns[2] = this.npm.chalk.green(columns[2]) // wanted
308+
columns[3] = this.npm.chalk.magenta(columns[3]) // latest
314309

315310
return columns
316311
}

lib/commands/profile.js

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
const inspect = require('util').inspect
22
const { URL } = require('url')
3-
const chalk = require('chalk')
43
const log = require('../utils/log-shim.js')
54
const npmProfile = require('npm-profile')
65
const qrcodeTerminal = require('qrcode-terminal')
@@ -161,7 +160,7 @@ class Profile extends BaseCommand {
161160
} else {
162161
const table = new Table()
163162
for (const key of Object.keys(cleaned)) {
164-
table.push({ [chalk.bold(key)]: cleaned[key] })
163+
table.push({ [this.npm.chalk.bold(key)]: cleaned[key] })
165164
}
166165

167166
this.npm.output(table.toString())

lib/commands/run-script.js

Lines changed: 1 addition & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
const { resolve } = require('path')
2-
const chalk = require('chalk')
32
const runScript = require('@npmcli/run-script')
43
const { isServerPackage } = runScript
54
const rpj = require('read-package-json-fast')
@@ -18,14 +17,6 @@ const cmdList = [
1817
'version',
1918
].reduce((l, p) => l.concat(['pre' + p, p, 'post' + p]), [])
2019

21-
const nocolor = {
22-
reset: s => s,
23-
bold: s => s,
24-
dim: s => s,
25-
blue: s => s,
26-
green: s => s,
27-
}
28-
2920
const BaseCommand = require('../base-command.js')
3021
class RunScript extends BaseCommand {
3122
static description = 'Run arbitrary package scripts'
@@ -138,7 +129,6 @@ class RunScript extends BaseCommand {
138129
path = path || this.npm.localPrefix
139130
const { scripts, name, _id } = await rpj(`${path}/package.json`)
140131
const pkgid = _id || name
141-
const color = this.npm.color
142132

143133
if (!scripts) {
144134
return []
@@ -170,7 +160,7 @@ class RunScript extends BaseCommand {
170160
const list = cmdList.includes(script) ? cmds : runScripts
171161
list.push(script)
172162
}
173-
const colorize = color ? chalk : nocolor
163+
const colorize = this.npm.chalk
174164

175165
if (cmds.length) {
176166
this.npm.output(

lib/commands/token.js

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
const Table = require('cli-table3')
2-
const chalk = require('chalk')
32
const { v4: isCidrV4, v6: isCidrV6 } = require('is-cidr')
43
const log = require('../utils/log-shim.js')
54
const profile = require('npm-profile')
@@ -152,7 +151,7 @@ class Token extends BaseCommand {
152151
} else {
153152
const table = new Table()
154153
for (const k of Object.keys(result)) {
155-
table.push({ [chalk.bold(k)]: String(result[k]) })
154+
table.push({ [this.npm.chalk.bold(k)]: String(result[k]) })
156155
}
157156
this.npm.output(table.toString())
158157
}

lib/commands/view.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
const chalk = require('chalk')
21
const columns = require('cli-columns')
32
const fs = require('fs')
43
const jsonParse = require('json-parse-even-better-errors')
@@ -315,6 +314,7 @@ class View extends BaseCommand {
315314
prettyView (packu, manifest) {
316315
// More modern, pretty printing of default view
317316
const unicode = this.npm.config.get('unicode')
317+
const chalk = this.npm.chalk
318318
const tags = []
319319

320320
Object.keys(packu['dist-tags']).forEach((t) => {

lib/npm.js

Lines changed: 19 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,8 @@ class Npm extends EventEmitter {
3737
#title = 'npm'
3838
#argvClean = []
3939
#chalk = null
40+
#logChalk = null
41+
#noColorChalk = new chalk.Instance({ level: 0 })
4042
#npmRoot = null
4143
#warnedNonDashArg = false
4244

@@ -261,6 +263,7 @@ class Npm extends EventEmitter {
261263
this.#display.load({
262264
// Use logColor since that is based on stderr
263265
color: this.logColor,
266+
chalk: this.logChalk,
264267
progress: this.flatOptions.progress,
265268
silent: this.silent,
266269
timing: this.config.get('timing'),
@@ -330,17 +333,28 @@ class Npm extends EventEmitter {
330333
return this.flatOptions.logColor
331334
}
332335

336+
get noColorChalk () {
337+
return this.#noColorChalk
338+
}
339+
333340
get chalk () {
334341
if (!this.#chalk) {
335-
let level = chalk.level
336-
if (!this.color) {
337-
level = 0
338-
}
339-
this.#chalk = new chalk.Instance({ level })
342+
this.#chalk = new chalk.Instance({
343+
level: this.color ? chalk.level : 0,
344+
})
340345
}
341346
return this.#chalk
342347
}
343348

349+
get logChalk () {
350+
if (!this.#logChalk) {
351+
this.#logChalk = new chalk.Instance({
352+
level: this.logColor ? chalk.stderr.level : 0,
353+
})
354+
}
355+
return this.#logChalk
356+
}
357+
344358
get global () {
345359
return this.config.get('global') || this.config.get('location') === 'global'
346360
}

0 commit comments

Comments
 (0)