feat(typings): add typings to support TypeScript (#646)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Add typings to support for TypeScript in favor of `@types/commander`
authored by Alan Agius · committed by Roman Vanesyan · parent 90b7fef · Browse files · 4 files·+415 added−6 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
4 files+415 added−6 removed
- other:+415 added−6 removed
Provenance
- Commit
66dfb8c- Tree
24be6aa- Author
Alan Agius <alan.agius4@gmail.com>- Committer
Roman Vanesyan <romain.vanesyan@gmail.com>- Parent
90b7fef
4 files changed+415 added−6 removed
added:typings/commander-tests.ts+96 added
1+import * as program from './index';2+3+interface ExtendedOptions extends program.CommandOptions {4+ isNew: any;5+}6+7+const commandInstance = new program.Command('-f');8+const optionsInstance = new program.Option('-f');9+10+program11+ .version('0.0.1')12+ .option('-p, --peppers', 'Add peppers')13+ .option('-P, --pineapple', 'Add pineapple')14+ .option('-b, --bbq', 'Add bbq sauce')15+ .option('-c, --cheese [type]', 'Add the specified type of cheese [marble]', 'marble')16+ .parse(process.argv);17+18+console.log('you ordered a pizza with:');19+if (program['peppers']) console.log(' - peppers');20+if (program['pineapple']) console.log(' - pineapple');21+if (program['bbq']) console.log(' - bbq');22+console.log(' - %s cheese', program['cheese']);23+24+function range(val: string) {25+ return val.split('..').map(Number);26+}27+28+function list(val: string) {29+ return val.split(',');30+}31+32+function collect(val: string, memo: string[]) {33+ memo.push(val);34+ return memo;35+}36+37+function increaseVerbosity(v: any, total: number) {38+ return total + 1;39+}40+41+program42+ .version('0.0.1')43+ .usage('[options] <file ...>')44+ .option('-i, --integer <n>', 'An integer argument', parseInt)45+ .option('-f, --float <n>', 'A float argument', parseFloat)46+ .option('-r, --range <a>..<b>', 'A range', range)47+ .option('-l, --list <items>', 'A list', list)48+ .option('-o, --optional [value]', 'An optional value')49+ .option('-c, --collect [value]', 'A repeatable value', collect, [])50+ .option('-v, --verbose', 'A value that can be increased', increaseVerbosity, 0)51+ .parse(process.argv);52+53+console.log(' int: %j', program['integer']);54+console.log(' float: %j', program['float']);55+console.log(' optional: %j', program['optional']);56+program['range'] = program['range'] || [];57+console.log(' range: %j..%j', program['range'][0], program['range'][1]);58+console.log(' list: %j', program['list']);59+console.log(' collect: %j', program['collect']);60+console.log(' verbosity: %j', program['verbose']);61+console.log(' args: %j', program['args']);62+63+program64+ .version('0.0.1')65+ .option('-f, --foo', 'enable some foo')66+ .option('-b, --bar', 'enable some bar')67+ .option('-B, --baz', 'enable some baz');68+69+// must be before .parse() since70+// node's emit() is immediate71+72+program.on('--help', () => {73+ console.log(' Examples:');74+ console.log('');75+ console.log(' $ custom-help --help');76+ console.log(' $ custom-help -h');77+ console.log('');78+});79+80+program81+ .command('allow-unknown-option')82+ .allowUnknownOption()83+ .action(() => {84+ console.log('unknown option is allowed');85+ });86+87+program88+ .version('0.0.1')89+ .arguments('<cmd> [env]')90+ .action((cmd, env) => {91+ console.log(cmd, env);92+ });93+94+program.parse(process.argv);95+96+console.log('stuff');added:typings/index.d.ts+288 added
1+// Type definitions for commander 2.92+// Project: https://github.com/visionmedia/commander.js3+// Definitions by: Alan Agius <https://github.com/alan-agius4>, Marcelo Dezem <http://github.com/mdezem>, vvakame <http://github.com/vvakame>4+5+declare class Option {6+ flags: string;7+ required: boolean;8+ optional: boolean;9+ bool: boolean;10+ short?: string;11+ long: string;12+ description: string;13+14+ /**15+ * Initialize a new `Option` with the given `flags` and `description`.16+ *17+ * @param {string} flags18+ * @param {string} [description]19+ */20+ constructor(flags: string, description?: string);21+}22+23+declare class Command extends NodeJS.EventEmitter {24+ [key: string]: any;25+26+ args: string[];27+28+ /**29+ * Initialize a new `Command`.30+ *31+ * @param {string} [name]32+ */33+ constructor(name?: string);34+35+ /**36+ * Set the program version to `str`.37+ *38+ * This method auto-registers the "-V, --version" flag39+ * which will print the version number when passed.40+ *41+ * @param {string} str42+ * @param {string} [flags]43+ * @returns {Command} for chaining44+ */45+ version(str: string, flags?: string): Command;46+47+ /**48+ * Add command `name`.49+ *50+ * The `.action()` callback is invoked when the51+ * command `name` is specified via __ARGV__,52+ * and the remaining arguments are applied to the53+ * function for access.54+ *55+ * When the `name` is "*" an un-matched command56+ * will be passed as the first arg, followed by57+ * the rest of __ARGV__ remaining.58+ *59+ * @example60+ * program61+ * .version('0.0.1')62+ * .option('-C, --chdir <path>', 'change the working directory')63+ * .option('-c, --config <path>', 'set config path. defaults to ./deploy.conf')64+ * .option('-T, --no-tests', 'ignore test hook')65+ *66+ * program67+ * .command('setup')68+ * .description('run remote setup commands')69+ * .action(function() {70+ * console.log('setup');71+ * });72+ *73+ * program74+ * .command('exec <cmd>')75+ * .description('run the given remote command')76+ * .action(function(cmd) {77+ * console.log('exec "%s"', cmd);78+ * });79+ *80+ * program81+ * .command('teardown <dir> [otherDirs...]')82+ * .description('run teardown commands')83+ * .action(function(dir, otherDirs) {84+ * console.log('dir "%s"', dir);85+ * if (otherDirs) {86+ * otherDirs.forEach(function (oDir) {87+ * console.log('dir "%s"', oDir);88+ * });89+ * }90+ * });91+ *92+ * program93+ * .command('*')94+ * .description('deploy the given env')95+ * .action(function(env) {96+ * console.log('deploying "%s"', env);97+ * });98+ *99+ * program.parse(process.argv);100+ *101+ * @param {string} name102+ * @param {string} [desc] for git-style sub-commands103+ * @param {CommandOptions} [opts] command options104+ * @returns {Command} the new command105+ */106+ command(name: string, desc?: string, opts?: commander.CommandOptions): Command;107+108+ /**109+ * Define argument syntax for the top-level command.110+ *111+ * @param {string} desc112+ * @returns {Command} for chaining113+ */114+ arguments(desc: string): Command;115+116+ /**117+ * Parse expected `args`.118+ *119+ * For example `["[type]"]` becomes `[{ required: false, name: 'type' }]`.120+ *121+ * @param {string[]} args122+ * @returns {Command} for chaining123+ */124+ parseExpectedArgs(args: string[]): Command;125+ /**126+ * Register callback `fn` for the command.127+ *128+ * @example129+ * program130+ * .command('help')131+ * .description('display verbose help')132+ * .action(function() {133+ * // output help here134+ * });135+ *136+ * @param {(...args: any[]) => void} fn137+ * @returns {Command} for chaining138+ */139+ action(fn: (...args: any[]) => void): Command;140+141+ /**142+ * Define option with `flags`, `description` and optional143+ * coercion `fn`.144+ *145+ * The `flags` string should contain both the short and long flags,146+ * separated by comma, a pipe or space. The following are all valid147+ * all will output this way when `--help` is used.148+ *149+ * "-p, --pepper"150+ * "-p|--pepper"151+ * "-p --pepper"152+ *153+ * @example154+ * // simple boolean defaulting to false155+ * program.option('-p, --pepper', 'add pepper');156+ *157+ * --pepper158+ * program.pepper159+ * // => Boolean160+ *161+ * // simple boolean defaulting to true162+ * program.option('-C, --no-cheese', 'remove cheese');163+ *164+ * program.cheese165+ * // => true166+ *167+ * --no-cheese168+ * program.cheese169+ * // => false170+ *171+ * // required argument172+ * program.option('-C, --chdir <path>', 'change the working directory');173+ *174+ * --chdir /tmp175+ * program.chdir176+ * // => "/tmp"177+ *178+ * // optional argument179+ * program.option('-c, --cheese [type]', 'add cheese [marble]');180+ *181+ * @param {string} flags182+ * @param {string} [description]183+ * @param {((arg1: any, arg2: any) => void) | RegExp} [fn] function or default184+ * @param {*} [defaultValue]185+ * @returns {Command} for chaining186+ */187+ option(flags: string, description?: string, fn?: ((arg1: any, arg2: any) => void) | RegExp, defaultValue?: any): Command;188+ option(flags: string, description?: string, defaultValue?: any): Command;189+190+ /**191+ * Allow unknown options on the command line.192+ *193+ * @param {boolean} [arg] if `true` or omitted, no error will be thrown for unknown options.194+ * @returns {Command} for chaining195+ */196+ allowUnknownOption(arg?: boolean): Command;197+198+ /**199+ * Parse `argv`, settings options and invoking commands when defined.200+ *201+ * @param {string[]} argv202+ * @returns {Command} for chaining203+ */204+ parse(argv: string[]): Command;205+206+ /**207+ * Parse options from `argv` returning `argv` void of these options.208+ *209+ * @param {string[]} argv210+ * @returns {ParseOptionsResult}211+ */212+ parseOptions(argv: string[]): commander.ParseOptionsResult;213+214+ /**215+ * Return an object containing options as key-value pairs216+ *217+ * @returns {{[key: string]: string}}218+ */219+ opts(): { [key: string]: string };220+221+ /**222+ * Set the description to `str`.223+ *224+ * @param {string} str225+ * @return {(Command | string)}226+ */227+ description(str: string): Command;228+ description(): string;229+230+ /**231+ * Set an alias for the command.232+ *233+ * @param {string} alias234+ * @return {(Command | string)}235+ */236+ alias(alias: string): Command;237+ alias(): string;238+239+ /**240+ * Set or get the command usage.241+ *242+ * @param {string} str243+ * @return {(Command | string)}244+ */245+ usage(str: string): Command;246+ usage(): string;247+248+ /**249+ * Get the name of the command.250+ *251+ * @return {string}252+ */253+ name(): string;254+255+ /**256+ * Output help information for this command.257+ *258+ * @param {() => void} [cb] Callback method259+ */260+ outputHelp(cb?: () => void): void;261+262+ /** Output help information and exit. */263+ help(): void;264+}265+266+declare namespace commander {267+268+ interface CommandOptions {269+ noHelp?: boolean;270+ isDefault?: boolean;271+ }272+273+ interface ParseOptionsResult {274+ args: string[];275+ unknown: string[];276+ }277+278+ interface CommanderStatic extends Command {279+ Command: typeof Command;280+ Option: typeof Option;281+ CommandOptions: CommandOptions;282+ ParseOptionsResult: ParseOptionsResult;283+ }284+285+}286+287+declare const commander: commander.CommanderStatic;288+export = commander;modified:package.json+11 added-6 removed
12 unmodified lines1314151617181920172218192021222324282526272829303132333412 unmodified lines "repository": { "type": "git", "url": "https://github.com/tj/commander.js.git" }, "devDependencies": { "should": "^11.2.1", "sinon": "^2.3.5" }, "scripts": { "test": "make test" "test": "make test && npm run test-typings", "test-typings": "node_modules/typescript/bin/tsc -p tsconfig.json" }, "main": "index", "files": [ "index.js" ], "dependencies": {} "dependencies": { "@types/node": "^7.0.39" }, "devDependencies": { "should": "^11.2.1", "sinon": "^2.3.5", "typescript": "^2.4.1" }, "typings": "typings/index.d.ts"}added:tsconfig.json+20 added
1234567891011121314151617181920{ "compilerOptions": { "module": "commonjs", "lib": [ "es6" ], "noImplicitAny": true, "noImplicitThis": true, "strictNullChecks": false, "types": [ "node" ], "noEmit": true, "forceConsistentCasingInFileNames": true }, "files": [ "typings/index.d.ts", "typings/commander-tests.ts" ]}No newline at end of file