Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(pkg): support empty bracket and negative indexes syntax #3536

Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions docs/content/commands/npm-pkg.md
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,13 @@ Returned values are always in **json** format.
npm pkg set contributors[0].name='Foo' contributors[0].email='foo@bar.ca'
```

You may also append items to the end of an array using the special
empty bracket notation:

```bash
npm pkg get contributors[].name='Bar' contributors[].email='bar@bar.ca'
ruyadorno marked this conversation as resolved.
Show resolved Hide resolved
```

It's also possible to parse values as json prior to saving them to your
`package.json` file, for example in order to set a `"private": true`
property:
Expand Down
10 changes: 10 additions & 0 deletions lib/utils/queryable.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ const cleanLeadingDot = str =>
const parseKeys = (key) => {
const sqBracketItems = new Set()
const parseSqBrackets = (str) => {
str = str.replace('[]', '[-0]')
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

what if i have an object with a literal key of "-0"?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

hmm that's a good point, it's not only -0 but any negative index really (which are also being added support to here) - now I'm not so sure about it given that we didn't explore that idea much further during the RFC process

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It seems just like using a string placeholder won’t work, because any string could be an object key - ie, it’s an implementation question, not a semantics question.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For an array, negative indexes could indeed be supported - but you’d have to traverse down to know that’s what it was.

const index = sqBracketsMatcher(str)

// once we find square brackets, we recursively parse all these
Expand Down Expand Up @@ -124,8 +125,17 @@ const setter = ({ data, key, value, force }) => {
const maybeIndex = Number(_key)
if (!Number.isNaN(maybeIndex)) {
_key = maybeIndex

// creates new array in case it's missing
if (!Object.keys(_data).length)
_data = []

// in case it's using a negative index, than calculates the
// length of the array minus that negative index, it's also used
// as a handy shortcut to empty-bracket-appending syntax since
// it converts missing indexes like this: arr[] -> arr[-0]
if (_key < 0 || Object.is(_key, -0))
_key = (_data.length) + _key
}

// retrieves the next data object to recursively iterate on,
Expand Down
32 changes: 32 additions & 0 deletions test/lib/pkg.js
Original file line number Diff line number Diff line change
Expand Up @@ -291,6 +291,38 @@ t.test('set single field', t => {
})
})

t.test('push to array syntax', t => {
const json = {
name: 'foo',
version: '1.1.1',
keywords: [
'foo',
],
}
npm.localPrefix = t.testdir({
'package.json': JSON.stringify(json),
})

pkg.exec(['set', 'keywords[]=bar', 'keywords[]=baz'], err => {
if (err)
throw err

t.strictSame(
readPackageJson(),
{
...json,
keywords: [
'foo',
'bar',
'baz',
],
},
'should append to arrays using empty bracket syntax'
)
t.end()
})
})

t.test('set multiple fields', t => {
const json = {
name: 'foo',
Expand Down
55 changes: 55 additions & 0 deletions test/lib/utils/queryable.js
Original file line number Diff line number Diff line change
Expand Up @@ -602,6 +602,61 @@ t.test('set arrays', async t => {
{ code: 'EOVERRIDEVALUE' },
'should throw an override error'
)

qqq.set('arr[]', 'c')
t.strictSame(
qqq.toJSON(),
{
arr: [
'a',
'b',
'c',
],
},
'should be able to append to array using empty bracket notation'
)

qqq.set('arr[-2]', 'B')
t.strictSame(
qqq.toJSON(),
{
arr: [
'a',
'B',
'c',
],
},
'should be able to use negative indexes'
)

qqq.set('arr[-1]', 'C')
t.strictSame(
qqq.toJSON(),
{
arr: [
'a',
'B',
'C',
],
},
'should be able to use negative indexes'
)

qqq.set('arr[].foo', 'foo')
t.strictSame(
qqq.toJSON(),
{
arr: [
'a',
'B',
'C',
{
foo: 'foo',
},
],
},
'should be able to append objects to array using empty bracket notation'
)
})

t.test('delete values', async t => {
Expand Down