Skip to content

Commit

Permalink
Allow toString to be used for help menu
Browse files Browse the repository at this point in the history
  • Loading branch information
carsonreinke committed Jul 21, 2020
1 parent 6cad30a commit ab7864a
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 1 deletion.
18 changes: 17 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -1392,6 +1392,22 @@ class Command extends EventEmitter {
return width;
};

/**
* Convert value to a string for help
*
* @param {object} value
* @return {string}
*/

_stringify(value) {
// Use the `toString` method for objects that don't use the default
if (typeof value === 'object' && Object.getPrototypeOf(value).toString !== Object.prototype.toString) {
return value.toString();
}

return JSON.stringify(value);
}

/**
* Return help for options.
*
Expand All @@ -1410,7 +1426,7 @@ class Command extends EventEmitter {
// Explicit options (including version)
const help = this.options.map((option) => {
const fullDesc = option.description +
((!option.negate && option.defaultValue !== undefined) ? ' (default: ' + JSON.stringify(option.defaultValue) + ')' : '');
((!option.negate && option.defaultValue !== undefined) ? ' (default: ' + this._stringify(option.defaultValue) + ')' : '');
return padOptionDetails(option.flags, fullDesc);
});

Expand Down
17 changes: 17 additions & 0 deletions tests/command.help.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -130,3 +130,20 @@ test('when both help flags masked then not displayed in helpInformation', () =>
const helpInformation = program.helpInformation();
expect(helpInformation).not.toMatch('display help');
});

test('when default value is object with toString and displays in helpInformation', () => {
const program = new commander.Command();
program
.option('--host <host>', 'select host', new URL('http://example.com/'));
const helpInformation = program.helpInformation();
expect(helpInformation).toContain('http://example.com/');
});

test('when default value is object and displays in helpInformation', () => {
const program = new commander.Command();
program
.option('--host <host>', 'select host', { host: 'example.com' });
const helpInformation = program.helpInformation();
expect(helpInformation).not.toContain('[object Object]');
expect(helpInformation).toContain('{"host":"example.com"}');
});

0 comments on commit ab7864a

Please sign in to comment.