From b01c81c4cda7bf9cc7ccc8302908f8079c2a01be Mon Sep 17 00:00:00 2001 From: achingbrain Date: Wed, 11 Mar 2020 13:29:56 +0000 Subject: [PATCH] fix: error when command is unknown Since yargs v14, using `.parse(command)` with an unknown command causes an [error to be thrown](https://github.com/yargs/yargs/issues/1419) instead of the help text being printed. One solution is to use `.argv` instead of `.parse(command)` but we use the `.parse(command)` variant to enable testing as the passed command is evaluated rather than `process.argv`, which is what happens when you call `.argv`. Instead if we detect a error caused by an unknown command, use the parser to show help instead of version of yargs that had `.parse(command)` called on it. --- packages/ipfs/src/cli/index.js | 7 +++++++ packages/ipfs/test/cli/daemon.js | 9 +++++++++ 2 files changed, 16 insertions(+) diff --git a/packages/ipfs/src/cli/index.js b/packages/ipfs/src/cli/index.js index 708eda1d0f..cc5421515e 100644 --- a/packages/ipfs/src/cli/index.js +++ b/packages/ipfs/src/cli/index.js @@ -18,6 +18,13 @@ module.exports = (command, ctxMiddleware) => { .fail((msg, err, yargs) => { // Handle yargs errors if (msg) { + // if the error was caused by an unknown command, the use of `.parse(command)` + // below causes printing help to fail: https://github.com/yargs/yargs/issues/1419#issuecomment-527234789 + // so pass the unadulterated parser in as `yargs` in order to print help successfully + if (msg.includes('Unknown argument')) { + yargs = parser + } + return reject(errCode(new Error(msg), 'ERR_YARGS', { yargs })) } diff --git a/packages/ipfs/test/cli/daemon.js b/packages/ipfs/test/cli/daemon.js index fb6720f748..6ff510b179 100644 --- a/packages/ipfs/test/cli/daemon.js +++ b/packages/ipfs/test/cli/daemon.js @@ -256,4 +256,13 @@ describe('daemon', () => { } }) }) + + it('should print help when command is unknown', async function () { + this.timeout(100 * 1000) + + const err = await ipfs.fail('derp') + + expect(err.stderr).to.include('Commands:') + expect(err.stderr).to.include('Unknown argument: derp') + }) })