From 780afc50e3a345feb1871a28e33fa48235bc3bd5 Mon Sep 17 00:00:00 2001 From: Sander Aalbers <31731300+Sanderovich@users.noreply.github.com> Date: Fri, 18 Oct 2024 16:40:34 +0200 Subject: [PATCH] fix(pkg): display if any of multiple attributes exist (#7855) See #7854 for the why and more details. I changed the unwrap logic so that it only runs when the result contains one entry and the amount of arguments is one. Otherwise, when multiple arguments are provided the unwrap results in an undefined. Additionally, I think it makes sense to skip the unwrap logic when the result contains one entry and pkg has multiple arguments because you would expect an object. In the existing comment above the if-statement, it is mentioned the CLI should not unwrap at all. I chose not to do this because it is not clear to me if this is a final decision and has a large impact. However, if it is the desired direction, I am happy to do the work. ## References Fixes #7854 --- lib/commands/pkg.js | 6 +++--- test/lib/commands/pkg.js | 20 ++++++++++++++++++++ 2 files changed, 23 insertions(+), 3 deletions(-) diff --git a/lib/commands/pkg.js b/lib/commands/pkg.js index a011fc10be107..5a236f6e62270 100644 --- a/lib/commands/pkg.js +++ b/lib/commands/pkg.js @@ -63,12 +63,12 @@ class Pkg extends BaseCommand { if (args.length) { result = new Queryable(result).query(args) - // in case there's only a single result from the query - // just prints that one element to stdout + // in case there's only a single argument and a single result from the query + // just prints that one element to stdout. // TODO(BREAKING_CHANGE): much like other places where we unwrap single // item arrays this should go away. it makes the behavior unknown for users // who don't already know the shape of the data. - if (Object.keys(result).length === 1) { + if (Object.keys(result).length === 1 && args.length === 1) { result = result[args] } } diff --git a/test/lib/commands/pkg.js b/test/lib/commands/pkg.js index 2306fe10db025..f4d0278b04d9b 100644 --- a/test/lib/commands/pkg.js +++ b/test/lib/commands/pkg.js @@ -108,6 +108,26 @@ t.test('get multiple arg', async t => { ) }) +t.test('get multiple arg with only one arg existing', async t => { + const { pkg, OUTPUT } = await mockNpm(t, { + prefixDir: { + 'package.json': JSON.stringify({ + name: 'foo', + }), + }, + }) + + await pkg('get', 'name', 'version', 'dependencies') + + t.strictSame( + JSON.parse(OUTPUT()), + { + name: 'foo', + }, + 'should print retrieved package.json field' + ) +}) + t.test('get multiple arg with empty value', async t => { const { pkg, OUTPUT } = await mockNpm(t, { prefixDir: {