Skip to content

Commit

Permalink
fix(set-script): add completion
Browse files Browse the repository at this point in the history
PR-URL: #2925
Credit: @Yash-Singh1
Close: #2925
Reviewed-by: @ruyadorno
  • Loading branch information
Yash-Singh1 authored and wraithgar committed Mar 24, 2021
1 parent 877b4ed commit c76f04a
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 0 deletions.
11 changes: 11 additions & 0 deletions lib/set-script.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ const log = require('npmlog')
const fs = require('fs')
const parseJSON = require('json-parse-even-better-errors')
const rpj = require('read-package-json-fast')
const { resolve } = require('path')

const BaseCommand = require('./base-command.js')
class SetScript extends BaseCommand {
Expand All @@ -20,6 +21,16 @@ class SetScript extends BaseCommand {
return ['[<script>] [<command>]']
}

async completion (opts) {
const argv = opts.conf.argv.remain
if (argv.length === 2) {
// find the script name
const json = resolve(this.npm.localPrefix, 'package.json')
const { scripts = {} } = await rpj(json).catch(er => ({}))
return Object.keys(scripts)
}
}

exec (args, cb) {
this.set(args).then(() => cb()).catch(cb)
}
Expand Down
37 changes: 37 additions & 0 deletions test/lib/set-script.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,43 @@ const test = require('tap')
const requireInject = require('require-inject')
const parseJSON = require('json-parse-even-better-errors')

test.test('completion', t => {
const SetScript = requireInject('../../lib/set-script.js')
const emptyDir = t.testdir()
t.test('already have a script name', async t => {
const setScript = new SetScript({localPrefix: emptyDir})
const res = await setScript.completion({conf: {argv: {remain: ['npm', 'run', 'x']}}})
t.equal(res, undefined)
t.end()
})
t.test('no package.json', async t => {
const setScript = new SetScript({localPrefix: emptyDir})
const res = await setScript.completion({conf: {argv: {remain: ['npm', 'run']}}})
t.strictSame(res, [])
t.end()
})
t.test('has package.json, no scripts', async t => {
const localPrefix = t.testdir({
'package.json': JSON.stringify({}),
})
const setScript = new SetScript({localPrefix})
const res = await setScript.completion({conf: {argv: {remain: ['npm', 'run']}}})
t.strictSame(res, [])
t.end()
})
t.test('has package.json, with scripts', async t => {
const localPrefix = t.testdir({
'package.json': JSON.stringify({
scripts: { hello: 'echo hello', world: 'echo world' },
}),
})
const setScript = new SetScript({localPrefix})
const res = await setScript.completion({conf: {argv: {remain: ['npm', 'run']}}})
t.strictSame(res, ['hello', 'world'])
t.end()
})
t.end()
})
test.test('fails on invalid arguments', (t) => {
const SetScript = requireInject('../../lib/set-script.js', {
npmlog: {},
Expand Down

0 comments on commit c76f04a

Please sign in to comment.