Skip to content
Myr

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

authored by John Gee · committed by GitHub · parent 2f7aa33 · Browse files · 19 files+499 added−125 removed
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

19 files+499 added−125 removed

added:examples/configure-output.js+31 added
modified:tests/args.variadic.test.js-15 removed
modified:tests/command.action.test.js+1 added-3 removed
44 unmodified lines
45 expect(actionMock).toHaveBeenCalledWith('my-file', program);46});4748test('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});6162// Changes made in #729 to call program action handler63test('when .action on program and no arguments then action called', () => {
72 unmodified lines
modified:tests/command.allowUnknownOption.test.js+4 added-4 removed
modified:tests/command.chain.test.js+6 added
133 unmodified lines
134 const program = new Command();135 const result = program.configureHelp({ });136 expect(result).toBe(program);137 });138139 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
1const commander = require('../');23test('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();78 try {9 program.parse(['--unknown'], { from: 'user' });10 } catch (err) {11 }1213 expect(writeSpy).toHaveBeenCalledTimes(1);14 writeSpy.mockRestore();15});1617test('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 });2425 try {26 program.parse(['--unknown'], { from: 'user' });27 } catch (err) {28 }2930 expect(writeSpy).toHaveBeenCalledTimes(0);31 expect(customWrite).toHaveBeenCalledTimes(1);32 writeSpy.mockRestore();33});3435test('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');4142 expect(() => {43 program.parse(['--version'], { from: 'user' });44 }).toThrow();4546 expect(writeSpy).toHaveBeenCalledTimes(1);47 writeSpy.mockRestore();48});4950test('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 });5859 expect(() => {60 program.parse(['--version'], { from: 'user' });61 }).toThrow();6263 expect(writeSpy).toHaveBeenCalledTimes(0);64 expect(customWrite).toHaveBeenCalledTimes(1);65 writeSpy.mockRestore();66});6768test('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();7273 expect(writeSpy).toHaveBeenCalledTimes(1);74 writeSpy.mockRestore();75});7677test('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();8384 expect(writeSpy).toHaveBeenCalledTimes(0);85 expect(customWrite).toHaveBeenCalledTimes(1);86 writeSpy.mockRestore();87});8889test('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 });9394 expect(writeSpy).toHaveBeenCalledTimes(1);95 writeSpy.mockRestore();96});9798test('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 });104105 expect(writeSpy).toHaveBeenCalledTimes(0);106 expect(customWrite).toHaveBeenCalledTimes(1);107 writeSpy.mockRestore();108});109110test('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;115116 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();128129 expect(helpColumns).toBe(expectedColumns);130 process.stdout.columns = holdColumns;131 process.stdout.isTTY = holdIsTTY;132});133134test('when custom getOutColumns then help columns custom', () => {135 const expectedColumns = 123;136 let helpColumns;137138 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();149150 expect(helpColumns).toBe(expectedColumns);151});152153test('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;158159 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 });170171 expect(helpColumns).toBe(expectedColumns);172 process.stderr.isTTY = holdIsTTY;173 process.stderr.columns = holdColumns;174});175176test('when custom getErrColumns then help error columns custom', () => {177 const expectedColumns = 123;178 let helpColumns;179180 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 });191192 expect(helpColumns).toBe(expectedColumns);193});194195test('when custom getOutColumns and configureHelp:columns then help columns from configureHelp', () => {196 const expectedColumns = 123;197 let helpColumns;198199 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();211212 expect(helpColumns).toBe(expectedColumns);213});214215test('when custom getErrColumns and configureHelp:columns then help error columns from configureHelp', () => {216 const expectedColumns = 123;217 let helpColumns;218219 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 });231232 expect(helpColumns).toBe(expectedColumns);233});234235test('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});247248test('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 });256257 expect(() => {258 program.parse(['--unknownOption'], { from: 'user' });259 }).toThrow();260 expect(outputError).toHaveBeenCalledWith("error: unknown option '--unknownOption'\n", program._outputConfiguration.writeErr);261});262263test('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 });270271 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 lines
16}1718describe('.exitOverride and error details', () => {19 // Use internal knowledge to suppress output to keep test output clean.20 let consoleErrorSpy;20 let stderrSpy;2122 beforeAll(() => {23 consoleErrorSpy = jest.spyOn(console, 'error').mockImplementation(() => { });23 stderrSpy = jest.spyOn(process.stderr, 'write').mockImplementation(() => { });24 });2526 afterEach(() => {27 consoleErrorSpy.mockClear();27 stderrSpy.mockClear();28 });2930 afterAll(() => {31 consoleErrorSpy.mockRestore();31 stderrSpy.mockRestore();32 });3334 test('when specify unknown program option then throw CommanderError', () => {35 const program = new commander.Command();
6 unmodified lines
42 } catch (err) {43 caughtErr = err;44 }4546 expect(consoleErrorSpy).toHaveBeenCalled();46 expect(stderrSpy).toHaveBeenCalled();47 expectCommanderError(caughtErr, 1, 'commander.unknownOption', "error: unknown option '-m'");48 });4950 test('when specify unknown command then throw CommanderError', () => {
9 unmodified lines
60 } catch (err) {61 caughtErr = err;62 }6364 expect(consoleErrorSpy).toHaveBeenCalled();64 expect(stderrSpy).toHaveBeenCalled();65 expectCommanderError(caughtErr, 1, 'commander.unknownCommand', "error: unknown command 'oops'. See 'prog --help'.");66 });6768 // Same error as above, but with custom handler.
28 unmodified lines
97 } catch (err) {98 caughtErr = err;99 }100101 expect(consoleErrorSpy).toHaveBeenCalled();101 expect(stderrSpy).toHaveBeenCalled();102 expectCommanderError(caughtErr, 1, 'commander.optionMissingArgument', `error: option '${optionFlags}' argument missing`);103 });104105 test('when specify command without required argument then throw CommanderError', () => {
9 unmodified lines
115 } catch (err) {116 caughtErr = err;117 }118119 expect(consoleErrorSpy).toHaveBeenCalled();119 expect(stderrSpy).toHaveBeenCalled();120 expectCommanderError(caughtErr, 1, 'commander.missingArgument', "error: missing required argument 'arg-name'");121 });122123 test('when specify --help then throw CommanderError', () => {
13 unmodified lines
137 writeSpy.mockRestore();138 });139140 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 lines
150 caughtErr = err;151 }152153 expectCommanderError(caughtErr, 1, 'commander.help', '(outputHelp)');155 writeSpy.mockRestore();154 });155156 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 lines
168 caughtErr = err;169 }170171 expectCommanderError(caughtErr, 0, 'commander.version', myVersion);174 writeSpy.mockRestore();172 stdoutSpy.mockRestore();173 });174175 test('when executableSubcommand succeeds then call exitOverride', async() => {176 expect.hasAssertions();
47 unmodified lines
modified:tests/command.helpCommand.test.js+4 added-4 removed
37 unmodified lines
38});3940describe('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;4445 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 });4950 afterEach(() => {51 consoleErrorSpy.mockClear();51 writeErrorSpy.mockClear();52 writeSpy.mockClear();53 });5455 afterAll(() => {56 consoleErrorSpy.mockRestore();56 writeErrorSpy.mockRestore();57 writeSpy.mockRestore();58 });5960 test('when "program help" then program', () => {
40 unmodified lines
modified:tests/command.helpOption.test.js+4 added-4 removed
1const commander = require('../');23describe('helpOption', () => {4 let writeSpy;5 let consoleErrorSpy;5 let writeErrorSpy;67 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 });1213 afterEach(() => {14 writeSpy.mockClear();15 consoleErrorSpy.mockClear();15 writeErrorSpy.mockClear();16 });1718 afterAll(() => {19 writeSpy.mockRestore();20 consoleErrorSpy.mockRestore();20 writeErrorSpy.mockRestore();21 });2223 test('when helpOption has custom flags then custom short flag invokes help', () => {24 const program = new commander.Command();
93 unmodified lines
modified:tests/command.unknownCommand.test.js+4 added-4 removed
1const commander = require('../');23describe('unknownOption', () => {4 // Optional. Use internal knowledge to suppress output to keep test output clean.5 let consoleErrorSpy;5 let writeErrorSpy;67 beforeAll(() => {8 consoleErrorSpy = jest.spyOn(console, 'error').mockImplementation(() => { });8 writeErrorSpy = jest.spyOn(process.stderr, 'write').mockImplementation(() => { });9 });1011 afterEach(() => {12 consoleErrorSpy.mockClear();12 writeErrorSpy.mockClear();13 });1415 afterAll(() => {16 consoleErrorSpy.mockRestore();16 writeErrorSpy.mockRestore();17 });1819 test('when unknown argument in simple program then no error', () => {20 const program = new commander.Command();
44 unmodified lines
modified:tests/command.unknownOption.test.js+4 added-4 removed
2 unmodified lines
3// Checking for detection of unknown options, including regression tests for some past issues.45describe('unknownOption', () => {6 // Optional. Use internal knowledge to suppress output to keep test output clean.7 let consoleErrorSpy;7 let writeErrorSpy;89 beforeAll(() => {10 consoleErrorSpy = jest.spyOn(console, 'error').mockImplementation(() => { });10 writeErrorSpy = jest.spyOn(process.stderr, 'write').mockImplementation(() => { });11 });1213 afterEach(() => {14 consoleErrorSpy.mockClear();14 writeErrorSpy.mockClear();15 });1617 afterAll(() => {18 consoleErrorSpy.mockRestore();18 writeErrorSpy.mockRestore();19 });2021 test('when specify unknown option with subcommand and action handler then error', () => {22 const program = new commander.Command();
63 unmodified lines
deleted:tests/help.columns.test.js-22 removed
1const commander = require('../');23// 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).56describe('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 });1516 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 lines
102});103104describe('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;107108 beforeAll(() => {109 consoleErrorSpy = jest.spyOn(console, 'error').mockImplementation(() => { });109 writeErrorSpy = jest.spyOn(process.stderr, 'write').mockImplementation(() => { });110 });111112 afterEach(() => {113 consoleErrorSpy.mockClear();113 writeErrorSpy.mockClear();114 });115116 afterAll(() => {117 consoleErrorSpy.mockRestore();117 writeErrorSpy.mockRestore();118 });119120 test('when program has required option not specified then error', () => {121 const program = new commander.Command();
62 unmodified lines
184});185186describe('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;189190 beforeAll(() => {191 consoleErrorSpy = jest.spyOn(console, 'error').mockImplementation(() => { });191 writeErrorSpy = jest.spyOn(process.stderr, 'write').mockImplementation(() => { });192 });193194 afterEach(() => {195 consoleErrorSpy.mockClear();195 writeErrorSpy.mockClear();196 });197198 afterAll(() => {199 consoleErrorSpy.mockRestore();199 writeErrorSpy.mockRestore();200 });201202 test('when command has required value not specified then error', () => {203 const program = new commander.Command();
77 unmodified lines
modified:tests/options.variadic.test.js+1 added-5 removed
1const commander = require('../');23describe('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(() => { });75 const program = new commander.Command();6 program7 .exitOverride()8 .configureOutput({ writeErr: jest.fn() })9 .option('-r,--required <value...>');1011 expect(() => {12 program.parse(['--required'], { from: 'user' });13 }).toThrow();1617 consoleErrorSpy.mockRestore();14 });1516 test('when variadic with one value then set in array', () => {17 const program = new commander.Command();
135 unmodified lines
modified:tests/options.version.test.js+21 added-18 removed
1 unmodified line
23// Test .version. Using exitOverride to check behaviour (instead of mocking process.exit).45describe('.version', () => {6 // Optional. Suppress normal output to keep test output clean.7 let writeSpy;89 beforeAll(() => {10 writeSpy = jest.spyOn(process.stdout, 'write').mockImplementation(() => { });11 });1213 afterEach(() => {14 writeSpy.mockClear();15 });1617 afterAll(() => {18 writeSpy.mockRestore();19 });206 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 lines
24 });2526 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);3435 expect(() => {36 program.parse(['node', 'test', '-V']);37 }).toThrow(myVersion);5152 // 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 });4041 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);4950 expect(() => {51 program.parse(['node', 'test', '--version']);52 }).toThrow(myVersion);53 expect(writeMock).toHaveBeenCalledWith(`${myVersion}\n`);54 });5556 test('when default .version then helpInformation includes default version help', () => {57 const myVersion = '1.2.3';
8 unmodified lines
66 });6768 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');7677 expect(() => {78 program.parse(['node', 'test', '-r']);79 }).toThrow(myVersion);80 expect(writeMock).toHaveBeenCalledWith(`${myVersion}\n`);81 });8283 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');9192 expect(() => {93 program.parse(['node', 'test', '-r']);94 }).toThrow(myVersion);95 expect(writeMock).toHaveBeenCalledWith(`${myVersion}\n`);96 });9798 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');106107 expect(() => {108 program.parse(['node', 'test', '--revision']);109 }).toThrow(myVersion);110 expect(writeMock).toHaveBeenCalledWith(`${myVersion}\n`);111 });112113 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');121122 expect(() => {123 program.parse(['node', 'test', '--revision']);124 }).toThrow(myVersion);125 expect(writeMock).toHaveBeenCalledWith(`${myVersion}\n`);126 });127128 test('when custom .version then helpInformation includes custom version help', () => {129 const myVersion = '1.2.3';
23 unmodified lines
153 });154155 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(() => {});165166 expect(() => {167 program.parse(['node', 'test', '--version']);168 }).toThrow(myVersion);169 expect(writeMock).toHaveBeenCalledWith(`${myVersion}\n`);170 });171172 test('when specify version then can get version', () => {173 const myVersion = '1.2.3';
5 unmodified lines
modified:typings/commander-tests.ts+12 added
261 unmodified lines
262 visibleCommands: (cmd: commander.Command) => [] // override method263});264const helpConfiguration: commander.HelpConfiguration = program.configureHelp();265266// configureOutput267const configureOutputThis: commander.Command = program.configureOutput({ });268const configureOutputConfig: commander.OutputConfiguration = program.configureOutput();269270program.configureOutput({271 writeOut: (str: string) => { },272 writeErr: (str: string) => { },273 getOutColumns: () => 80,274 getErrColumns: () => 80,275 outputError: (str: string, write: (str: string) => void) => { }276});277278// Help279const helper = new commander.Help();280const helperCommand = new commander.Command();281const helperOption = new commander.Option('-a, --all');
59 unmodified lines
modified:typings/index.d.ts+28 added-1 removed
75 unmodified lines
76 type OptionConstructor = new (flags: string, description?: string) => Option;7778 interface Help {79 /** output columns, long lines are wrapped to fit */80 columns: number;80 columns?: number;81 sortSubcommands: boolean;82 sortOptions: boolean;8384 /** Get the command term to show in the list of subcommands. */
48 unmodified lines
133 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;143144 }145146 type AddHelpTextPosition = 'beforeAll' | 'before' | 'after' | 'afterAll';147148 interface Command {149 [key: string]: any; // options as properties
107 unmodified lines
257 /** Get configuration */258 configureHelp(): HelpConfiguration;259260 /**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;278279 /**280 * Register callback `fn` for the command.281 *282 * @example283 * program
306 unmodified lines
modified:index.js+62 added-19 removed
10 unmodified lines
1112// Although this is a class, methods are static in style to allow override using subclass or just functions.13class 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 lines
242 */243244 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 lines
542 this._combineFlagAndOptionalValue = true;543 this._description = '';544 this._argsDescription = undefined;545546 // 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 };554555 this._hidden = false;556 this._hasHelpOption = true;557 this._helpFlags = '-h, --help';558 this._helpDescription = 'display help for command';
113 unmodified lines
672 return this;673 }674675 /**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 */693694 configureOutput(configuration) {695 if (configuration === undefined) return this._outputConfiguration;696697 Object.assign(this._outputConfiguration, configuration);698 return this;699 }700701 /**702 * Add a prepared subcommand.703 *704 * See .command() for creating an attached subcommand which inherits settings from its parent.705 *
296 unmodified lines
1002 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 lines
1673 return this._optionValues;1674 };16751676 /**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 }16851686 /**1687 * Argument `name` is missing.1688 *1689 * @param {string} name1690 * @api private1691 */16921693 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 };16971698 /**1699 * `Option` is missing an argument, but received `flag` or nothing.
9 unmodified lines
1709 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 };17151716 /**1717 * `Option` does not have a value, and is a mandatory option.
3 unmodified lines
1721 */17221723 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 };17271728 /**1729 * Unknown option `flag`.
4 unmodified lines
17341735 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 };17401741 /**1742 * Unknown command.
8 unmodified lines
1751 }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 };17571758 /**1759 * Set the program version to `str`.
17 unmodified lines
1777 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 lines
18791880 /**1881 * Return program help documentation.1882 *1883 * @param {{ error: boolean }} [contextOptions] - pass {error:true} to wrap for stderr instead of stdout1884 * @return {string}1885 */18861847 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 };18941895 /**
4 unmodified lines
1900 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 lines
19351936 groupListeners.slice().reverse().forEach(command => command.emit('beforeAllHelp', context));1937 this.emit('beforeHelp', context);19381896 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 lines
modified:Readme.md+24 added-2 removed
39 unmodified lines
40 - [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 lines
771the inspector port is incremented by 1 for the spawned subcommand.772773If you are using VSCode to debug executable subcommands you need to set the `"autoAttachChildProcesses": true` flag in your launch.json configuration.774775### Override exit handling775### Override exit and output handling776777By default Commander calls `process.exit` when it detects errors, or after displaying the help or version. You can override778this behaviour and optionally supply a callback. The default override throws a `CommanderError`.779
9 unmodified lines
789 // custom processing...790}791```792793By default Commander is configured for a command-line application and writes to stdout and stderr.794You can modify this behaviour for custom applications. In addition, you can modify the display of error messages.795796Example file: [configure-output.js](./examples/configure-output.js)797798799```js800function errorColor(str) {801 // Add ANSI escape codes to display text in red.802 return `\x1b[31m${str}\x1b[0m`;803}804805program806 .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```814815### Additional documentation816817There is more information available about:818
56 unmodified lines