configure output (#1387)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* Add output configuration and use for version and errors * Tests passing using write/writeErr * Suppress test output on stderr using spyon * Accurately set help columns for stdout/stderr * Remove bogus file * Tidy comments * Only using single argument to write, simplify declaration to match * Add tests for configureOutput write and writeError * Add tests for configureOutput getColumns and getErrorColumns * Add error case too * Use configureOutput instead of jest.spyon for some tests * Add configureOutput to chain tests * Add set/get test for configureOutput * Rename routines with symmetrical out/err * Add outputError simple code * Add tests for outputError * Add JSDoc * Tweak wording * First cut at TypeScript * Add TypeScript sanity check for configureOutput * Add example for configureOutput * Add configureOutput to README * Make example in README a little clearer
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
19 files+499 added−125 removed
- tests:+342 added−103 removed
- other:+157 added−22 removed
Provenance
- Commit
ed7f13e- Tree
2062e9e- Author
John Gee <john@ruru.gen.nz>- Committer
GitHub <noreply@github.com>- Parent
2f7aa33
19 files changed+499 added−125 removed
added:examples/configure-output.js+31 added
12345678910111213141516171819202122232425262728293031// const commander = require('commander'); // (normal include)const commander = require('../'); // include commander in git clone of commander repo
const program = new commander.Command();
function errorColor(str) { // Add ANSI escape codes to display text in red. return `\x1b[31m${str}\x1b[0m`;}
program .configureOutput({ // Visibly override write routines as example! writeOut: (str) => process.stdout.write(`[OUT] ${str}`), writeErr: (str) => process.stdout.write(`[ERR] ${str}`), // Output errors in red. outputError: (str, write) => write(errorColor(str)) });
program .version('1.2.3') .option('-c, --compress') .command('sub-command');
program.parse();
// Try the following:// node configure-output.js --version// node configure-output.js --unknown// node configure-output.js --help// node configure-output.jsmodified:tests/args.variadic.test.js-15 removed
1234567891011121314151617181920678962 unmodified linesconst commander = require('../');
// Testing variadic arguments. Testing all the action arguments, but could test just variadicArg.
describe('variadic argument', () => { // Optional. Use internal knowledge to suppress output to keep test output clean. let consoleErrorSpy;
beforeAll(() => { consoleErrorSpy = jest.spyOn(console, 'error').mockImplementation(() => { }); });
afterEach(() => { consoleErrorSpy.mockClear(); });
afterAll(() => { consoleErrorSpy.mockRestore(); });
test('when no extra arguments specified for program then variadic arg is empty array', () => { const actionMock = jest.fn(); const program = new commander.Command(); program62 unmodified linesmodified:tests/command.action.test.js+1 added-3 removed
44 unmodified lines45 expect(actionMock).toHaveBeenCalledWith('my-file', program);46 });47 48 test('when .action on program with required argument and argument not supplied then action not called', () => {49- // Optional. Use internal knowledge to suppress output to keep test output clean.50- const consoleErrorSpy = jest.spyOn(console, 'error').mockImplementation(() => { });49 const actionMock = jest.fn();50 const program = new commander.Command();51 program52 .exitOverride()53+ .configureOutput({ writeErr: () => {} })54 .arguments('<file>')55 .action(actionMock);56 expect(() => {57 program.parse(['node', 'test']);58 }).toThrow();59 expect(actionMock).not.toHaveBeenCalled();61- consoleErrorSpy.mockRestore();60 });61 62 // Changes made in #729 to call program action handler63 test('when .action on program and no arguments then action called', () => {72 unmodified linesmodified:tests/command.allowUnknownOption.test.js+4 added-4 removed
2 unmodified lines345677891010111213141415161718181920212272 unmodified lines2 unmodified lines// Not testing output, just testing whether an error is detected.
describe('allowUnknownOption', () => { // Optional. Use internal knowledge to suppress output to keep test output clean. let consoleErrorSpy; let writeErrorSpy;
beforeAll(() => { consoleErrorSpy = jest.spyOn(console, 'error').mockImplementation(() => { }); writeErrorSpy = jest.spyOn(process.stderr, 'write').mockImplementation(() => { }); });
afterEach(() => { consoleErrorSpy.mockClear(); writeErrorSpy.mockClear(); });
afterAll(() => { consoleErrorSpy.mockRestore(); writeErrorSpy.mockRestore(); });
test('when specify unknown program option then error', () => { const program = new commander.Command();72 unmodified linesmodified:tests/command.chain.test.js+6 added
133 unmodified lines134 const program = new Command();135 const result = program.configureHelp({ });136 expect(result).toBe(program);137 });138+139+ test('when call .configureOutput() then returns this', () => {140+ const program = new Command();141+ const result = program.configureOutput({ });142+ expect(result).toBe(program);143+ });144 });added:tests/command.configureOutput.test.js+275 added
1+const commander = require('../');2+3+test('when default writeErr() then error on stderr', () => {4+ const writeSpy = jest.spyOn(process.stderr, 'write').mockImplementation(() => { });5+ const program = new commander.Command();6+ program.exitOverride();7+8+ try {9+ program.parse(['--unknown'], { from: 'user' });10+ } catch (err) {11+ }12+13+ expect(writeSpy).toHaveBeenCalledTimes(1);14+ writeSpy.mockRestore();15+});16+17+test('when custom writeErr() then error on custom output', () => {18+ const writeSpy = jest.spyOn(process.stderr, 'write').mockImplementation(() => { });19+ const customWrite = jest.fn();20+ const program = new commander.Command();21+ program22+ .exitOverride()23+ .configureOutput({ writeErr: customWrite });24+25+ try {26+ program.parse(['--unknown'], { from: 'user' });27+ } catch (err) {28+ }29+30+ expect(writeSpy).toHaveBeenCalledTimes(0);31+ expect(customWrite).toHaveBeenCalledTimes(1);32+ writeSpy.mockRestore();33+});34+35+test('when default write() then version on stdout', () => {36+ const writeSpy = jest.spyOn(process.stdout, 'write').mockImplementation(() => { });37+ const program = new commander.Command();38+ program39+ .exitOverride()40+ .version('1.2.3');41+42+ expect(() => {43+ program.parse(['--version'], { from: 'user' });44+ }).toThrow();45+46+ expect(writeSpy).toHaveBeenCalledTimes(1);47+ writeSpy.mockRestore();48+});49+50+test('when custom write() then version on custom output', () => {51+ const writeSpy = jest.spyOn(process.stdout, 'write').mockImplementation(() => { });52+ const customWrite = jest.fn();53+ const program = new commander.Command();54+ program55+ .exitOverride()56+ .version('1.2.3')57+ .configureOutput({ writeOut: customWrite });58+59+ expect(() => {60+ program.parse(['--version'], { from: 'user' });61+ }).toThrow();62+63+ expect(writeSpy).toHaveBeenCalledTimes(0);64+ expect(customWrite).toHaveBeenCalledTimes(1);65+ writeSpy.mockRestore();66+});67+68+test('when default write() then help on stdout', () => {69+ const writeSpy = jest.spyOn(process.stdout, 'write').mockImplementation(() => { });70+ const program = new commander.Command();71+ program.outputHelp();72+73+ expect(writeSpy).toHaveBeenCalledTimes(1);74+ writeSpy.mockRestore();75+});76+77+test('when custom write() then help error on custom output', () => {78+ const writeSpy = jest.spyOn(process.stdout, 'write').mockImplementation(() => { });79+ const customWrite = jest.fn();80+ const program = new commander.Command();81+ program.configureOutput({ writeOut: customWrite });82+ program.outputHelp();83+84+ expect(writeSpy).toHaveBeenCalledTimes(0);85+ expect(customWrite).toHaveBeenCalledTimes(1);86+ writeSpy.mockRestore();87+});88+89+test('when default writeErr then help error on stderr', () => {90+ const writeSpy = jest.spyOn(process.stderr, 'write').mockImplementation(() => { });91+ const program = new commander.Command();92+ program.outputHelp({ error: true });93+94+ expect(writeSpy).toHaveBeenCalledTimes(1);95+ writeSpy.mockRestore();96+});97+98+test('when custom writeErr then help error on custom output', () => {99+ const writeSpy = jest.spyOn(process.stderr, 'write').mockImplementation(() => { });100+ const customWrite = jest.fn();101+ const program = new commander.Command();102+ program.configureOutput({ writeErr: customWrite });103+ program.outputHelp({ error: true });104+105+ expect(writeSpy).toHaveBeenCalledTimes(0);106+ expect(customWrite).toHaveBeenCalledTimes(1);107+ writeSpy.mockRestore();108+});109+110+test('when default getOutColumns then help columns from stdout', () => {111+ const expectedColumns = 123;112+ const holdIsTTY = process.stdout.isTTY;113+ const holdColumns = process.stdout.columns;114+ let helpColumns;115+116+ process.stderr.isTTY = true;117+ process.stdout.columns = expectedColumns;118+ process.stdout.isTTY = true;119+ const program = new commander.Command();120+ program121+ .configureHelp({122+ formatHelp: (cmd, helper) => {123+ helpColumns = helper.columns;124+ return '';125+ }126+ });127+ program.outputHelp();128+129+ expect(helpColumns).toBe(expectedColumns);130+ process.stdout.columns = holdColumns;131+ process.stdout.isTTY = holdIsTTY;132+});133+134+test('when custom getOutColumns then help columns custom', () => {135+ const expectedColumns = 123;136+ let helpColumns;137+138+ const program = new commander.Command();139+ program140+ .configureHelp({141+ formatHelp: (cmd, helper) => {142+ helpColumns = helper.columns;143+ return '';144+ }145+ }).configureOutput({146+ getOutColumns: () => expectedColumns147+ });148+ program.outputHelp();149+150+ expect(helpColumns).toBe(expectedColumns);151+});152+153+test('when default getErrColumns then help error columns from stderr', () => {154+ const expectedColumns = 123;155+ const holdIsTTY = process.stderr.isTTY;156+ const holdColumns = process.stderr.columns;157+ let helpColumns;158+159+ process.stderr.isTTY = true;160+ process.stderr.columns = expectedColumns;161+ const program = new commander.Command();162+ program163+ .configureHelp({164+ formatHelp: (cmd, helper) => {165+ helpColumns = helper.columns;166+ return '';167+ }168+ });169+ program.outputHelp({ error: true });170+171+ expect(helpColumns).toBe(expectedColumns);172+ process.stderr.isTTY = holdIsTTY;173+ process.stderr.columns = holdColumns;174+});175+176+test('when custom getErrColumns then help error columns custom', () => {177+ const expectedColumns = 123;178+ let helpColumns;179+180+ const program = new commander.Command();181+ program182+ .configureHelp({183+ formatHelp: (cmd, helper) => {184+ helpColumns = helper.columns;185+ return '';186+ }187+ }).configureOutput({188+ getErrColumns: () => expectedColumns189+ });190+ program.outputHelp({ error: true });191+192+ expect(helpColumns).toBe(expectedColumns);193+});194+195+test('when custom getOutColumns and configureHelp:columns then help columns from configureHelp', () => {196+ const expectedColumns = 123;197+ let helpColumns;198+199+ const program = new commander.Command();200+ program201+ .configureHelp({202+ formatHelp: (cmd, helper) => {203+ helpColumns = helper.columns;204+ return '';205+ },206+ columns: expectedColumns207+ }).configureOutput({208+ getOutColumns: () => 999209+ });210+ program.outputHelp();211+212+ expect(helpColumns).toBe(expectedColumns);213+});214+215+test('when custom getErrColumns and configureHelp:columns then help error columns from configureHelp', () => {216+ const expectedColumns = 123;217+ let helpColumns;218+219+ const program = new commander.Command();220+ program221+ .configureHelp({222+ formatHelp: (cmd, helper) => {223+ helpColumns = helper.columns;224+ return '';225+ },226+ columns: expectedColumns227+ }).configureOutput({228+ getErrColumns: () => 999229+ });230+ program.outputHelp({ error: true });231+232+ expect(helpColumns).toBe(expectedColumns);233+});234+235+test('when set configureOutput then get configureOutput', () => {236+ const outputOptions = {237+ writeOut: jest.fn(),238+ writeErr: jest.fn(),239+ getOutColumns: jest.fn(),240+ getErrColumns: jest.fn(),241+ outputError: jest.fn()242+ };243+ const program = new commander.Command();244+ program.configureOutput(outputOptions);245+ expect(program.configureOutput()).toEqual(outputOptions);246+});247+248+test('when custom outputErr and error then outputErr called', () => {249+ const outputError = jest.fn();250+ const program = new commander.Command();251+ program252+ .exitOverride()253+ .configureOutput({254+ outputError255+ });256+257+ expect(() => {258+ program.parse(['--unknownOption'], { from: 'user' });259+ }).toThrow();260+ expect(outputError).toHaveBeenCalledWith("error: unknown option '--unknownOption'\n", program._outputConfiguration.writeErr);261+});262+263+test('when custom outputErr and writeErr and error then outputErr passed writeErr', () => {264+ const writeErr = () => jest.fn();265+ const outputError = jest.fn();266+ const program = new commander.Command();267+ program268+ .exitOverride()269+ .configureOutput({ writeErr, outputError });270+271+ expect(() => {272+ program.parse(['--unknownOption'], { from: 'user' });273+ }).toThrow();274+ expect(outputError).toHaveBeenCalledWith("error: unknown option '--unknownOption'\n", writeErr);275+});modified:tests/command.exitOverride.test.js+10 added-12 removed
15 unmodified lines16 }17 18 describe('.exitOverride and error details', () => {19 // Use internal knowledge to suppress output to keep test output clean.20- let consoleErrorSpy;20+ let stderrSpy;21 22 beforeAll(() => {23- consoleErrorSpy = jest.spyOn(console, 'error').mockImplementation(() => { });23+ stderrSpy = jest.spyOn(process.stderr, 'write').mockImplementation(() => { });24 });25 26 afterEach(() => {27- consoleErrorSpy.mockClear();27+ stderrSpy.mockClear();28 });29 30 afterAll(() => {31- consoleErrorSpy.mockRestore();31+ stderrSpy.mockRestore();32 });33 34 test('when specify unknown program option then throw CommanderError', () => {35 const program = new commander.Command();6 unmodified lines42 } catch (err) {43 caughtErr = err;44 }45 46- expect(consoleErrorSpy).toHaveBeenCalled();46+ expect(stderrSpy).toHaveBeenCalled();47 expectCommanderError(caughtErr, 1, 'commander.unknownOption', "error: unknown option '-m'");48 });49 50 test('when specify unknown command then throw CommanderError', () => {9 unmodified lines60 } catch (err) {61 caughtErr = err;62 }63 64- expect(consoleErrorSpy).toHaveBeenCalled();64+ expect(stderrSpy).toHaveBeenCalled();65 expectCommanderError(caughtErr, 1, 'commander.unknownCommand', "error: unknown command 'oops'. See 'prog --help'.");66 });67 68 // Same error as above, but with custom handler.28 unmodified lines97 } catch (err) {98 caughtErr = err;99 }100 101- expect(consoleErrorSpy).toHaveBeenCalled();101+ expect(stderrSpy).toHaveBeenCalled();102 expectCommanderError(caughtErr, 1, 'commander.optionMissingArgument', `error: option '${optionFlags}' argument missing`);103 });104 105 test('when specify command without required argument then throw CommanderError', () => {9 unmodified lines115 } catch (err) {116 caughtErr = err;117 }118 119- expect(consoleErrorSpy).toHaveBeenCalled();119+ expect(stderrSpy).toHaveBeenCalled();120 expectCommanderError(caughtErr, 1, 'commander.missingArgument', "error: missing required argument 'arg-name'");121 });122 123 test('when specify --help then throw CommanderError', () => {13 unmodified lines137 writeSpy.mockRestore();138 });139 140 test('when executable subcommand and no command specified then throw CommanderError', () => {141- const writeSpy = jest.spyOn(process.stderr, 'write').mockImplementation(() => { });141 const program = new commander.Command();142 program143 .exitOverride()144 .command('compress', 'compress description');5 unmodified lines150 caughtErr = err;151 }152 153 expectCommanderError(caughtErr, 1, 'commander.help', '(outputHelp)');155- writeSpy.mockRestore();154 });155 156 test('when specify --version then throw CommanderError', () => {159- const writeSpy = jest.spyOn(process.stdout, 'write').mockImplementation(() => { });157+ const stdoutSpy = jest.spyOn(process.stdout, 'write').mockImplementation(() => { });158 const myVersion = '1.2.3';159 const program = new commander.Command();160 program161 .exitOverride()6 unmodified lines168 caughtErr = err;169 }170 171 expectCommanderError(caughtErr, 0, 'commander.version', myVersion);174- writeSpy.mockRestore();172+ stdoutSpy.mockRestore();173 });174 175 test('when executableSubcommand succeeds then call exitOverride', async() => {176 expect.hasAssertions();47 unmodified linesmodified:tests/command.helpCommand.test.js+4 added-4 removed
37 unmodified lines38 });39 40 describe('help command processed on correct command', () => {41 // Use internal knowledge to suppress output to keep test output clean.42- let consoleErrorSpy;42+ let writeErrorSpy;43 let writeSpy;44 45 beforeAll(() => {46- consoleErrorSpy = jest.spyOn(console, 'error').mockImplementation(() => { });46+ writeErrorSpy = jest.spyOn(process.stderr, 'write').mockImplementation(() => { });47 writeSpy = jest.spyOn(process.stdout, 'write').mockImplementation(() => { });48 });49 50 afterEach(() => {51- consoleErrorSpy.mockClear();51+ writeErrorSpy.mockClear();52 writeSpy.mockClear();53 });54 55 afterAll(() => {56- consoleErrorSpy.mockRestore();56+ writeErrorSpy.mockRestore();57 writeSpy.mockRestore();58 });59 60 test('when "program help" then program', () => {40 unmodified linesmodified:tests/command.helpOption.test.js+4 added-4 removed
1 const commander = require('../');2 3 describe('helpOption', () => {4 let writeSpy;5- let consoleErrorSpy;5+ let writeErrorSpy;6 7 beforeAll(() => {8 // Optional. Suppress expected output to keep test output clean.9 writeSpy = jest.spyOn(process.stdout, 'write').mockImplementation(() => { });10- consoleErrorSpy = jest.spyOn(console, 'error').mockImplementation(() => { });10+ writeErrorSpy = jest.spyOn(process.stderr, 'write').mockImplementation(() => { });11 });12 13 afterEach(() => {14 writeSpy.mockClear();15- consoleErrorSpy.mockClear();15+ writeErrorSpy.mockClear();16 });17 18 afterAll(() => {19 writeSpy.mockRestore();20- consoleErrorSpy.mockRestore();20+ writeErrorSpy.mockRestore();21 });22 23 test('when helpOption has custom flags then custom short flag invokes help', () => {24 const program = new commander.Command();93 unmodified linesmodified:tests/command.unknownCommand.test.js+4 added-4 removed
1 const commander = require('../');2 3 describe('unknownOption', () => {4 // Optional. Use internal knowledge to suppress output to keep test output clean.5- let consoleErrorSpy;5+ let writeErrorSpy;6 7 beforeAll(() => {8- consoleErrorSpy = jest.spyOn(console, 'error').mockImplementation(() => { });8+ writeErrorSpy = jest.spyOn(process.stderr, 'write').mockImplementation(() => { });9 });10 11 afterEach(() => {12- consoleErrorSpy.mockClear();12+ writeErrorSpy.mockClear();13 });14 15 afterAll(() => {16- consoleErrorSpy.mockRestore();16+ writeErrorSpy.mockRestore();17 });18 19 test('when unknown argument in simple program then no error', () => {20 const program = new commander.Command();44 unmodified linesmodified:tests/command.unknownOption.test.js+4 added-4 removed
2 unmodified lines3 // Checking for detection of unknown options, including regression tests for some past issues.4 5 describe('unknownOption', () => {6 // Optional. Use internal knowledge to suppress output to keep test output clean.7- let consoleErrorSpy;7+ let writeErrorSpy;8 9 beforeAll(() => {10- consoleErrorSpy = jest.spyOn(console, 'error').mockImplementation(() => { });10+ writeErrorSpy = jest.spyOn(process.stderr, 'write').mockImplementation(() => { });11 });12 13 afterEach(() => {14- consoleErrorSpy.mockClear();14+ writeErrorSpy.mockClear();15 });16 17 afterAll(() => {18- consoleErrorSpy.mockRestore();18+ writeErrorSpy.mockRestore();19 });20 21 test('when specify unknown option with subcommand and action handler then error', () => {22 const program = new commander.Command();63 unmodified linesdeleted:tests/help.columns.test.js-22 removed
1-const commander = require('../');2-3-// These are tests of the Help class, not of the Command help.4-// There is some overlap with the higher level Command tests (which predate Help).5-6-describe('columns', () => {7- test('when default then columns from stdout', () => {8- const hold = process.stdout.columns;9- process.stdout.columns = 123;10- const program = new commander.Command();11- const helper = program.createHelp();12- expect(helper.columns).toEqual(123);13- process.stdout.columns = hold;14- });15-16- test('when configure columns then value from user', () => {17- const program = new commander.Command();18- program.configureHelp({ columns: 321 });19- const helper = program.createHelp();20- expect(helper.columns).toEqual(321);21- });22-});modified:tests/options.mandatory.test.js+8 added-8 removed
101 unmodified lines102 });103 104 describe('required program option with mandatory value not specified', () => {105 // Optional. Use internal knowledge to suppress output to keep test output clean.106- let consoleErrorSpy;106+ let writeErrorSpy;107 108 beforeAll(() => {109- consoleErrorSpy = jest.spyOn(console, 'error').mockImplementation(() => { });109+ writeErrorSpy = jest.spyOn(process.stderr, 'write').mockImplementation(() => { });110 });111 112 afterEach(() => {113- consoleErrorSpy.mockClear();113+ writeErrorSpy.mockClear();114 });115 116 afterAll(() => {117- consoleErrorSpy.mockRestore();117+ writeErrorSpy.mockRestore();118 });119 120 test('when program has required option not specified then error', () => {121 const program = new commander.Command();62 unmodified lines184 });185 186 describe('required command option with mandatory value not specified', () => {187 // Optional. Use internal knowledge to suppress output to keep test output clean.188- let consoleErrorSpy;188+ let writeErrorSpy;189 190 beforeAll(() => {191- consoleErrorSpy = jest.spyOn(console, 'error').mockImplementation(() => { });191+ writeErrorSpy = jest.spyOn(process.stderr, 'write').mockImplementation(() => { });192 });193 194 afterEach(() => {195- consoleErrorSpy.mockClear();195+ writeErrorSpy.mockClear();196 });197 198 afterAll(() => {199- consoleErrorSpy.mockRestore();199+ writeErrorSpy.mockRestore();200 });201 202 test('when command has required value not specified then error', () => {203 const program = new commander.Command();77 unmodified linesmodified:tests/options.variadic.test.js+1 added-5 removed
1 const commander = require('../');2 3 describe('variadic option with required value', () => {4 test('when variadic with value missing then error', () => {5- // Optional. Use internal knowledge to suppress output to keep test output clean.6- const consoleErrorSpy = jest.spyOn(console, 'error').mockImplementation(() => { });7-5 const program = new commander.Command();6 program7 .exitOverride()8+ .configureOutput({ writeErr: jest.fn() })9 .option('-r,--required <value...>');10 11 expect(() => {12 program.parse(['--required'], { from: 'user' });13 }).toThrow();16-17- consoleErrorSpy.mockRestore();14 });15 16 test('when variadic with one value then set in array', () => {17 const program = new commander.Command();135 unmodified linesmodified:tests/options.version.test.js+21 added-18 removed
1 unmodified line2 3 // Test .version. Using exitOverride to check behaviour (instead of mocking process.exit).4 5 describe('.version', () => {6- // Optional. Suppress normal output to keep test output clean.7- let writeSpy;8-9- beforeAll(() => {10- writeSpy = jest.spyOn(process.stdout, 'write').mockImplementation(() => { });11- });12-13- afterEach(() => {14- writeSpy.mockClear();15- });16-17- afterAll(() => {18- writeSpy.mockRestore();19- });20-6 test('when no .version and specify --version then unknown option error', () => {7 const errorMessage = 'unknownOption';8 const program = new commander.Command();9 // Override unknownOption as convenient way to check fails as expected.14 unmodified lines24 });25 26 test('when specify default short flag then display version', () => {27 const myVersion = '1.2.3';28+ const writeMock = jest.fn();29 const program = new commander.Command();30 program31 .exitOverride()32+ .configureOutput({ writeOut: writeMock })33 .version(myVersion);34 35 expect(() => {36 program.parse(['node', 'test', '-V']);37 }).toThrow(myVersion);51-52- // Test output once as well, rest of tests just check the thrown message.53- expect(writeSpy).toHaveBeenCalledWith(`${myVersion}\n`);38+ expect(writeMock).toHaveBeenCalledWith(`${myVersion}\n`);39 });40 41 test('when specify default long flag then display version', () => {42 const myVersion = '1.2.3';43+ const writeMock = jest.fn();44 const program = new commander.Command();45 program46 .exitOverride()47+ .configureOutput({ writeOut: writeMock })48 .version(myVersion);49 50 expect(() => {51 program.parse(['node', 'test', '--version']);52 }).toThrow(myVersion);53+ expect(writeMock).toHaveBeenCalledWith(`${myVersion}\n`);54 });55 56 test('when default .version then helpInformation includes default version help', () => {57 const myVersion = '1.2.3';8 unmodified lines66 });67 68 test('when specify custom short flag then display version', () => {69 const myVersion = '1.2.3';70+ const writeMock = jest.fn();71 const program = new commander.Command();72 program73 .exitOverride()74+ .configureOutput({ writeOut: writeMock })75 .version(myVersion, '-r, --revision');76 77 expect(() => {78 program.parse(['node', 'test', '-r']);79 }).toThrow(myVersion);80+ expect(writeMock).toHaveBeenCalledWith(`${myVersion}\n`);81 });82 83 test('when specify just custom short flag then display version', () => {84 const myVersion = '1.2.3';85+ const writeMock = jest.fn();86 const program = new commander.Command();87 program88 .exitOverride()89+ .configureOutput({ writeOut: writeMock })90 .version(myVersion, '-r');91 92 expect(() => {93 program.parse(['node', 'test', '-r']);94 }).toThrow(myVersion);95+ expect(writeMock).toHaveBeenCalledWith(`${myVersion}\n`);96 });97 98 test('when specify custom long flag then display version', () => {99 const myVersion = '1.2.3';100+ const writeMock = jest.fn();101 const program = new commander.Command();102 program103 .exitOverride()104+ .configureOutput({ writeOut: writeMock })105 .version(myVersion, '-r, --revision');106 107 expect(() => {108 program.parse(['node', 'test', '--revision']);109 }).toThrow(myVersion);110+ expect(writeMock).toHaveBeenCalledWith(`${myVersion}\n`);111 });112 113 test('when specify just custom long flag then display version', () => {114 const myVersion = '1.2.3';115+ const writeMock = jest.fn();116 const program = new commander.Command();117 program118 .exitOverride()119+ .configureOutput({ writeOut: writeMock })120 .version(myVersion, '--revision');121 122 expect(() => {123 program.parse(['node', 'test', '--revision']);124 }).toThrow(myVersion);125+ expect(writeMock).toHaveBeenCalledWith(`${myVersion}\n`);126 });127 128 test('when custom .version then helpInformation includes custom version help', () => {129 const myVersion = '1.2.3';23 unmodified lines153 });154 155 test('when have .version+version and specify --version then version displayed', () => {156 const myVersion = '1.2.3';157+ const writeMock = jest.fn();158 const program = new commander.Command();159 program160 .exitOverride()161+ .configureOutput({ writeOut: writeMock })162 .version(myVersion)163 .command('version')164 .action(() => {});165 166 expect(() => {167 program.parse(['node', 'test', '--version']);168 }).toThrow(myVersion);169+ expect(writeMock).toHaveBeenCalledWith(`${myVersion}\n`);170 });171 172 test('when specify version then can get version', () => {173 const myVersion = '1.2.3';5 unmodified linesmodified:typings/commander-tests.ts+12 added
261 unmodified lines262 visibleCommands: (cmd: commander.Command) => [] // override method263 });264 const helpConfiguration: commander.HelpConfiguration = program.configureHelp();265 266+// configureOutput267+const configureOutputThis: commander.Command = program.configureOutput({ });268+const configureOutputConfig: commander.OutputConfiguration = program.configureOutput();269+270+program.configureOutput({271+ writeOut: (str: string) => { },272+ writeErr: (str: string) => { },273+ getOutColumns: () => 80,274+ getErrColumns: () => 80,275+ outputError: (str: string, write: (str: string) => void) => { }276+});277+278 // Help279 const helper = new commander.Help();280 const helperCommand = new commander.Command();281 const helperOption = new commander.Option('-a, --all');59 unmodified linesmodified:typings/index.d.ts+28 added-1 removed
75 unmodified lines76 type OptionConstructor = new (flags: string, description?: string) => Option;77 78 interface Help {79 /** output columns, long lines are wrapped to fit */80- columns: number;80+ columns?: number;81 sortSubcommands: boolean;82 sortOptions: boolean;83 84 /** Get the command term to show in the list of subcommands. */48 unmodified lines133 interface AddHelpTextContext { // passed to text function used with .addHelpText()134 error: boolean;135 command: Command;136 }137+ interface OutputConfiguration {138+ writeOut?(str: string): void;139+ writeErr?(str: string): void;140+ getOutColumns?(): number;141+ getErrColumns?(): number;142+ outputError?(str: string, write: (str: string) => void): void;143 144+ }145+146 type AddHelpTextPosition = 'beforeAll' | 'before' | 'after' | 'afterAll';147 148 interface Command {149 [key: string]: any; // options as properties107 unmodified lines257 /** Get configuration */258 configureHelp(): HelpConfiguration;259 260 /**261+ * The default output goes to stdout and stderr. You can customise this for special262+ * applications. You can also customise the display of errors by overriding outputError.263+ *264+ * The configuration properties are all functions:265+ *266+ * // functions to change where being written, stdout and stderr267+ * writeOut(str)268+ * writeErr(str)269+ * // matching functions to specify columns for wrapping help270+ * getOutColumns()271+ * getErrColumns()272+ * // functions based on what is being written out273+ * outputError(str, write) // used for displaying errors, and not used for displaying help274+ */275+ configureOutput(configuration: OutputConfiguration): this;276+ /** Get configuration */277+ configureOutput(): OutputConfiguration;278+279+ /**280 * Register callback `fn` for the command.281 *282 * @example283 * program306 unmodified linesmodified:index.js+62 added-19 removed
10 unmodified lines11 12 // Although this is a class, methods are static in style to allow override using subclass or just functions.13 class Help {14 constructor() {15- this.columns = process.stdout.columns || 80;15+ this.columns = undefined;16 this.sortSubcommands = false;17 this.sortOptions = false;18 }19 222 unmodified lines242 */243 244 formatHelp(cmd, helper) {245 const termWidth = helper.padWidth(cmd, helper);246- const columns = helper.columns;246+ const columns = helper.columns || 80;247 const itemIndentWidth = 2;248 const itemSeparatorWidth = 2;249 // itemIndent term itemSeparator description250 const descriptionWidth = columns - termWidth - itemIndentWidth - itemSeparatorWidth;291 unmodified lines542 this._combineFlagAndOptionalValue = true;543 this._description = '';544 this._argsDescription = undefined;545 546+ // see .configureOutput() for docs547+ this._outputConfiguration = {548+ writeOut: (str) => process.stdout.write(str),549+ writeErr: (str) => process.stderr.write(str),550+ getOutColumns: () => process.stdout.isTTY ? process.stdout.columns : undefined,551+ getErrColumns: () => process.stderr.isTTY ? process.stderr.columns : undefined,552+ outputError: (str, write) => write(str)553+ };554+555 this._hidden = false;556 this._hasHelpOption = true;557 this._helpFlags = '-h, --help';558 this._helpDescription = 'display help for command';113 unmodified lines672 return this;673 }674 675 /**676+ * The default output goes to stdout and stderr. You can customise this for special677+ * applications. You can also customise the display of errors by overriding outputError.678+ *679+ * The configuration properties are all functions:680+ *681+ * // functions to change where being written, stdout and stderr682+ * writeOut(str)683+ * writeErr(str)684+ * // matching functions to specify columns for wrapping help685+ * getOutColumns()686+ * getErrColumns()687+ * // functions based on what is being written out688+ * outputError(str, write) // used for displaying errors, and not used for displaying help689+ *690+ * @param {Object} [configuration] - configuration options691+ * @return {Command|Object} `this` command for chaining, or stored configuration692+ */693+694+ configureOutput(configuration) {695+ if (configuration === undefined) return this._outputConfiguration;696+697+ Object.assign(this._outputConfiguration, configuration);698+ return this;699+ }700+701+ /**702 * Add a prepared subcommand.703 *704 * See .command() for creating an attached subcommand which inherits settings from its parent.705 *296 unmodified lines1002 try {1003 val = option.parseArg(val, oldValue === undefined ? defaultValue : oldValue);1004 } catch (err) {1005 if (err.code === 'commander.optionArgumentRejected') {971- console.error(err.message);972- this._exit(err.exitCode, err.code, err.message);1006+ this._displayError(err.exitCode, err.code, err.message);1007 }1008 throw err;1009 }1010 } else if (val !== null && option.variadic) {662 unmodified lines1673 return this._optionValues;1674 };1675 1676 /**1677+ * Internal bottleneck for handling of parsing errors.1678+ *1679+ * @api private1680+ */1681+ _displayError(exitCode, code, message) {1682+ this._outputConfiguration.outputError(`${message}\n`, this._outputConfiguration.writeErr);1683+ this._exit(exitCode, code, message);1684+ }1685+1686+ /**1687 * Argument `name` is missing.1688 *1689 * @param {string} name1690 * @api private1691 */1692 1693 missingArgument(name) {1694 const message = `error: missing required argument '${name}'`;1651- console.error(message);1652- this._exit(1, 'commander.missingArgument', message);1695+ this._displayError(1, 'commander.missingArgument', message);1696 };1697 1698 /**1699 * `Option` is missing an argument, but received `flag` or nothing.9 unmodified lines1709 message = `error: option '${option.flags}' argument missing, got '${flag}'`;1710 } else {1711 message = `error: option '${option.flags}' argument missing`;1712 }1670- console.error(message);1671- this._exit(1, 'commander.optionMissingArgument', message);1713+ this._displayError(1, 'commander.optionMissingArgument', message);1714 };1715 1716 /**1717 * `Option` does not have a value, and is a mandatory option.3 unmodified lines1721 */1722 1723 missingMandatoryOptionValue(option) {1724 const message = `error: required option '${option.flags}' not specified`;1683- console.error(message);1684- this._exit(1, 'commander.missingMandatoryOptionValue', message);1725+ this._displayError(1, 'commander.missingMandatoryOptionValue', message);1726 };1727 1728 /**1729 * Unknown option `flag`.4 unmodified lines1734 1735 unknownOption(flag) {1736 if (this._allowUnknownOption) return;1737 const message = `error: unknown option '${flag}'`;1697- console.error(message);1698- this._exit(1, 'commander.unknownOption', message);1738+ this._displayError(1, 'commander.unknownOption', message);1739 };1740 1741 /**1742 * Unknown command.8 unmodified lines1751 }1752 const fullCommand = partCommands.join(' ');1753 const message = `error: unknown command '${this.args[0]}'.` +1754 (this._hasHelpOption ? ` See '${fullCommand} ${this._helpLongFlag}'.` : '');1715- console.error(message);1716- this._exit(1, 'commander.unknownCommand', message);1755+ this._displayError(1, 'commander.unknownCommand', message);1756 };1757 1758 /**1759 * Set the program version to `str`.17 unmodified lines1777 const versionOption = this.createOption(flags, description);1778 this._versionOptionName = versionOption.attributeName();1779 this.options.push(versionOption);1780 this.on('option:' + versionOption.name(), () => {1742- process.stdout.write(str + '\n');1781+ this._outputConfiguration.writeOut(`${str}\n`);1782 this._exit(0, 'commander.version', str);1783 });1784 return this;1785 };93 unmodified lines1879 1880 /**1881 * Return program help documentation.1882 *1883+ * @param {{ error: boolean }} [contextOptions] - pass {error:true} to wrap for stderr instead of stdout1884 * @return {string}1885 */1886 1847- helpInformation() {1887+ helpInformation(contextOptions) {1888 const helper = this.createHelp();1889+ if (helper.columns === undefined) {1890+ helper.columns = (contextOptions && contextOptions.error) ? this._outputConfiguration.getErrColumns() : this._outputConfiguration.getOutColumns();1891+ }1892 return helper.formatHelp(this, helper);1893 };1894 1895 /**4 unmodified lines1900 contextOptions = contextOptions || {};1901 const context = { error: !!contextOptions.error };1902 let write;1903 if (context.error) {1861- write = (arg, ...args) => process.stderr.write(arg, ...args);1904+ write = (arg) => this._outputConfiguration.writeErr(arg);1905 } else {1863- write = (arg, ...args) => process.stdout.write(arg, ...args);1906+ write = (arg) => this._outputConfiguration.writeOut(arg);1907 }1908 context.write = contextOptions.write || write;1909 context.command = this;1910 return context;24 unmodified lines1935 1936 groupListeners.slice().reverse().forEach(command => command.emit('beforeAllHelp', context));1937 this.emit('beforeHelp', context);1938 1896- let helpInformation = this.helpInformation();1939+ let helpInformation = this.helpInformation(context);1940 if (deprecatedCallback) {1941 helpInformation = deprecatedCallback(helpInformation);1942 if (typeof helpInformation !== 'string' && !Buffer.isBuffer(helpInformation)) {1943 throw new Error('outputHelp callback must return a string or a Buffer');216 unmodified linesmodified:Readme.md+24 added-2 removed
39 unmodified lines40 - [createCommand()](#createcommand)41 - [Import into ECMAScript Module](#import-into-ecmascript-module)42 - [Node options such as `--harmony`](#node-options-such-as---harmony)43 - [Debugging stand-alone executable subcommands](#debugging-stand-alone-executable-subcommands)44- - [Override exit handling](#override-exit-handling)44+ - [Override exit and output handling](#override-exit-and-output-handling)45 - [Additional documentation](#additional-documentation)46 - [Examples](#examples)47 - [Support](#support)48 - [Commander for enterprise](#commander-for-enterprise)722 unmodified lines771 the inspector port is incremented by 1 for the spawned subcommand.772 773 If you are using VSCode to debug executable subcommands you need to set the `"autoAttachChildProcesses": true` flag in your launch.json configuration.774 775-### Override exit handling775+### Override exit and output handling776 777 By default Commander calls `process.exit` when it detects errors, or after displaying the help or version. You can override778 this behaviour and optionally supply a callback. The default override throws a `CommanderError`.779 9 unmodified lines789 // custom processing...790 }791 ```792 793+By default Commander is configured for a command-line application and writes to stdout and stderr.794+You can modify this behaviour for custom applications. In addition, you can modify the display of error messages.795+796+Example file: [configure-output.js](./examples/configure-output.js)797+798+799+```js800+function errorColor(str) {801+ // Add ANSI escape codes to display text in red.802+ return `\x1b[31m${str}\x1b[0m`;803+}804+805+program806+ .configureOutput({807+ // Visibly override write routines as example!808+ writeOut: (str) => process.stdout.write(`[OUT] ${str}`),809+ writeErr: (str) => process.stdout.write(`[ERR] ${str}`),810+ // Highlight errors in color.811+ outputError: (str, write) => write(errorColor(str))812+ });813+```814+815 ### Additional documentation816 817 There is more information available about:818 56 unmodified lines