Skip to content

Commit

Permalink
fix: move run-script banners to stderr when in json mode
Browse files Browse the repository at this point in the history
Fixes #7354
  • Loading branch information
lukekarrys committed Apr 29, 2024
1 parent d9cf7fc commit e6317ad
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 10 deletions.
2 changes: 1 addition & 1 deletion docs/bin/build.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ const run = require('../lib/build.js')
const { paths } = require('../lib/index')

run(paths)
.then((res) => console.log(`Wrote ${res.length} files`))
.then((res) => console.error(`Wrote ${res.length} files`))
.catch((err) => {
process.exitCode = 1
console.error(err)
Expand Down
24 changes: 15 additions & 9 deletions lib/utils/display.js
Original file line number Diff line number Diff line change
Expand Up @@ -267,16 +267,22 @@ class Display {
if (this.#outputState.buffering) {
this.#outputState.buffer.push([level, meta, ...args])
} else {
// HACK: if it looks like the banner and we are in a state where we hide the
// banner then dont write any output. This hack can be replaced with proc-log.META
const isBanner = args.length === 1 &&
typeof args[0] === 'string' &&
args[0].startsWith('\n> ') &&
args[0].endsWith('\n')
const hideBanner = this.#silent || ['exec', 'explore'].includes(this.#command)
if (!(isBanner && hideBanner)) {
this.#writeOutput(level, meta, ...args)
// HACK: Check if the argument looks like a run-script banner. This can be
// replaced with proc-log.META in @npmcli/run-script
if (typeof args[0] === 'string' && args[0].startsWith('\n> ') && args[0].endsWith('\n')) {
if (this.#silent || ['exec', 'explore'].includes(this.#command)) {
// Silent mode and some specific commands always hide run script banners
break
} else if (this.#json) {
// In json mode, change output to stderr since we dont want to break json
// parsing on stdout if the user is piping to jq or something.
// XXX: in a future (breaking?) change it might make sense for run-script to
// always output these banners with proc-log.output.error if we think they
// align closer with "logging" instead of "output"
level = output.KEYS.error
}
}
this.#writeOutput(level, meta, ...args)
}
break
}
Expand Down
12 changes: 12 additions & 0 deletions smoke-tests/test/pack-json-output.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@

const t = require('tap')
const setup = require('./fixtures/setup.js')

t.test('pack --json returns only json on stdout', async t => {
const { npmLocal } = await setup(t)

const { stderr, stdout } = await npmLocal('pack', '--json')

t.match(stderr, /> npm@.* prepack\n/, 'stderr has banner')
t.ok(JSON.parse(stdout), 'stdout can be parsed as json')
})

0 comments on commit e6317ad

Please sign in to comment.