rewrite commander.d.ts for 2.3.0

This commit is contained in:
vvakame
2014-10-06 16:49:26 +09:00
parent 09304bb527
commit fc1dc3e173
3 changed files with 468 additions and 255 deletions

View File

@@ -1,53 +1,100 @@
///<reference path="commander.d.ts"/>
//
// TODO: improve tests
// [the code below was extracted from the documentation and examples, but does not seem to cover all cases]
//
// NOTE: import statement can not use in TypeScript 1.0.1
var program:commander.IExportedCommand = require('commander');
import program = require("commander");
declare module commander {
interface IExportedCommand {
peppers:boolean;
pineapple:boolean;
bbq:boolean;
cheese:string;
}
}
program
.version('0.0.1')
.option('-C, --chdir <path>', 'change the working directory')
.option('-c, --config <path>', 'set config path [./deploy.conf]')
.option('-T, --no-tests', 'ignore test hook')
.option('-p, --peppers', 'Add peppers')
.option('-P, --pineapple', 'Add pineapple')
.option('-b, --bbq', 'Add bbq sauce')
.option('-c, --cheese [type]', 'Add the specified type of cheese [marble]', 'marble')
.parse(process.argv);
console.log('you ordered a pizza with:');
if (program.peppers) console.log(' - peppers');
if (program.pineapple) console.log(' - pineapple');
if (program.bbq) console.log(' - bbq');
console.log(' - %s cheese', program.cheese);
function range(val:string) {
return val.split('..').map(Number);
}
function list(val:string) {
return val.split(',');
}
function collect(val:string, memo:string[]) {
memo.push(val);
return memo;
}
function increaseVerbosity(v:any, total:number) {
return total + 1;
}
declare module commander {
interface IExportedCommand {
integer:number;
float:number;
optional:string;
range:number[];
list:string[];
collect:string[];
verbose:number;
}
}
// $ deploy setup stage
// $ deploy setup
program
.command('setup [env]')
.description('run setup commands for all envs')
.action(function (env?) {
env = env || 'all';
console.log('setup for %s env(s)', env);
});
.version('0.0.1')
.usage('[options] <file ...>')
.option('-i, --integer <n>', 'An integer argument', parseInt)
.option('-f, --float <n>', 'A float argument', parseFloat)
.option('-r, --range <a>..<b>', 'A range', range)
.option('-l, --list <items>', 'A list', list)
.option('-o, --optional [value]', 'An optional value')
.option('-c, --collect [value]', 'A repeatable value', collect, [])
.option('-v, --verbose', 'A value that can be increased', increaseVerbosity, 0)
.parse(process.argv);
console.log(' int: %j', program.integer);
console.log(' float: %j', program.float);
console.log(' optional: %j', program.optional);
program.range = program.range || [];
console.log(' range: %j..%j', program.range[0], program.range[1]);
console.log(' list: %j', program.list);
console.log(' collect: %j', program.collect);
console.log(' verbosity: %j', program.verbose);
console.log(' args: %j', program.args);
// $ deploy stage
// $ deploy production
program
.command('*')
.action(function (env?) {
console.log('deploying "%s"', env);
});
.version('0.0.1')
.option('-f, --foo', 'enable some foo')
.option('-b, --bar', 'enable some bar')
.option('-B, --baz', 'enable some baz');
program.option('-p, --pepper', 'add pepper');
// must be before .parse() since
// node's emit() is immediate
program.option('-C, --chdir <path>', 'change the working directory');
program.prompt('Username: ', function (name) {
console.log('hi %s', name);
program.on('--help', () => {
console.log(' Examples:');
console.log('');
console.log(' $ custom-help --help');
console.log(' $ custom-help -h');
console.log('');
});
program.prompt('Description:', function (desc) {
console.log('description was "%s"', desc.trim());
});
program.parse(process.argv);
program.promptForNumber("Enter a number:", (n) => {
});
program.confirm("Confirm? ", (f) => {
});
program.choose(["a", "b", "c"], (i) => {
});
console.log('stuff');

View File

@@ -1,236 +1,402 @@
// Type definitions for commanderjs 1.1.1
// Type definitions for commanderjs 2.3.0
// Project: https://github.com/visionmedia/commander.js
// Definitions by: Marcelo Dezem <http://github.com/mdezem>
// Definitions by: Marcelo Dezem <http://github.com/mdezem>, vvakame <http://github.com/vvakame>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
declare module "commander" {
export interface Command {
/**
* The command name.
*/
name: string;
//
//
// NOTE: the methods below are COPIED to the module
// as functions exports. If changes need to be made here,
// remember to re-paste the definitions in the module.
// Read below to know why such ugly thing is required.
//
//
/// <reference path="../node/node.d.ts" />
declare module commander {
interface ICommandStatic {
/**
* Register callback fn for the command.
*/
action(fn:(...args:any[]) => any): Command;
/**
* Define option with flags, description and optional coercion function and default value.
* The flags string should contain both the short and long flags
* separated by comma, a pipe or space. The following are all valid
* all will output this way when --help is used.
* Initialize a new `Command`.
*
* "-p, --pepper"
* "-p|--pepper"
* "-p --pepper"
* @param {String} name
* @api public
*/
new (name?:string):ICommand;
}
interface ICommand extends NodeJS.EventEmitter {
args: string[];
_args: { required:boolean; name: string; }[];
/**
* Add command `name`.
*
* @param flags the option flags.
* @param description the option description. The description is printed when "--help" is used.
* @param coerceFn (optional) specifies a callback function to coerce the option arg.
* @param defaultValue (optional) specifies a default value.
*/
option(flags:string, description:string, coerceFn?:(value:string) => any, defaultValue?:any): Command;
/**
* Sets the command version
*/
version(version:string): Command;
/**
* Parse the arguments array and invokes the commands passing the parsed options.
* @param argv the arguments array.
*/
parse(argv:string[]): Command;
/**
* Gets or sets the command description.
* @param description the new description for the command. When ommited this returns the current description, otherwise returns the current Command.
*/
description(description:string): Command;
description(): string;
/**
* Gets or sets the usage help string.
*/
usage(usage:string): Command;
usage(): string;
/**
* Prompt the user for a value, calling the callback function.
*
* Supports single-line and multi-line prompts.
* To issue a single-line prompt simply add a whitespace
* to the end of label, something like "name: ", whereas
* for a multi-line prompt omit this "description:".
* @param label the label string to be printed in console.
* @param callback a callback function to handle the inputed string.
*/
prompt(label:string, callback:(value:string) => any): void;
promptForNumber(label:string, callback:(value:number) => any): void;
promptForDate(label:string, callback:(value:Date) => any): void;
promptSingleLine(label:string, callback:(value:string) => any): void;
promptMultiLine(label:string, callback:(value:string) => any): void;
/**
* Prompt for password with a label, a optional mask char and callback function.
* The mask string defaults to '', aka no output is written while typing, you may want to use "*" etc.
*/
password(label:string, mask:string, callback:(value:string) => any): void;
password(label:string, callback:(value:string) => any): void;
/**
* Prompts the user for a confirmation.
*/
confirm(label:string, callback:(flag:boolean) => any): void;
/**
* Prompt for password with str, mask char and callback fn(val).
* The mask string defaults to '', aka no output is written while typing, you may want to use "*" etc.
*/
choose(options:string[], callback:(idx:number) => any): void;
choose(options:any[], callback:(idx:number) => any): void;
/**
* Add command with the specified name. Returns a new instance of Command.
*
* The .action() callback is invoked when the
* command name is specified via ARGV,
* The `.action()` callback is invoked when the
* command `name` is specified via __ARGV__,
* and the remaining arguments are applied to the
* function for access.
*
* When the name is "*" an un-matched command
* When the `name` is "*" an un-matched command
* will be passed as the first arg, followed by
* the rest of ARGV remaining.
* the rest of __ARGV__ remaining.
*
* @param name the name of the command. Pass "*" to trap un-matched commands.
* Examples:
*
* program
* .version('0.0.1')
* .option('-C, --chdir <path>', 'change the working directory')
* .option('-c, --config <path>', 'set config path. defaults to ./deploy.conf')
* .option('-T, --no-tests', 'ignore test hook')
*
* program
* .command('setup')
* .description('run remote setup commands')
* .action(function(){
* console.log('setup');
* });
*
* program
* .command('exec <cmd>')
* .description('run the given remote command')
* .action(function(cmd){
* console.log('exec "%s"', cmd);
* });
*
* program
* .command('*')
* .description('deploy the given env')
* .action(function(env){
* console.log('deploying "%s"', env);
* });
*
* program.parse(process.argv);
*
* @param {String} name
* @param {String} [desc]
* @return {Command} the new command
* @api public
*/
command(name:string): Command;
command(name:string, desc?:string):ICommand;
/**
* Add an implicit `help [cmd]` subcommand
* which invokes `--help` for the given command.
*
* @api private
*/
addImplicitHelpCommand():void;
/**
* Parse expected `args`.
*
* For example `["[type]"]` becomes `[{ required: false, name: 'type' }]`.
*
* @param {Array} args
* @return {Command} for chaining
* @api public
*/
parseExpectedArgs(args:string[]):ICommand;
/**
* Register callback `fn` for the command.
*
* Examples:
*
* program
* .command('help')
* .description('display verbose help')
* .action(function(){
* // output help here
* });
*
* @param {Function} fn
* @return {Command} for chaining
* @api public
*/
action(fn:(...args:any[])=>void):ICommand;
/**
* Define option with `flags`, `description` and optional
* coercion `fn`.
*
* The `flags` string should contain both the short and long flags,
* separated by comma, a pipe or space. The following are all valid
* all will output this way when `--help` is used.
*
* "-p, --pepper"
* "-p|--pepper"
* "-p --pepper"
*
* Examples:
*
* // simple boolean defaulting to false
* program.option('-p, --pepper', 'add pepper');
*
* --pepper
* program.pepper
* // => Boolean
*
* // simple boolean defaulting to true
* program.option('-C, --no-cheese', 'remove cheese');
*
* program.cheese
* // => true
*
* --no-cheese
* program.cheese
* // => false
*
* // required argument
* program.option('-C, --chdir <path>', 'change the working directory');
*
* --chdir /tmp
* program.chdir
* // => "/tmp"
*
* // optional argument
* program.option('-c, --cheese [type]', 'add cheese [marble]');
*
* @param {String} flags
* @param {String} description
* @param {Function|Mixed} fn or default
* @param {Mixed} defaultValue
* @return {Command} for chaining
* @api public
*/
option(flags:string, description?:string, fn?:(arg1:any, arg2:any)=>void, defaultValue?:any):ICommand;
option(flags:string, description?:string, defaultValue?:any):ICommand;
/**
* Parse `argv`, settings options and invoking commands when defined.
*
* @param {Array} argv
* @return {Command} for chaining
* @api public
*/
parse(argv:string[]):ICommand;
/**
* Execute a sub-command executable.
*
* @param {Array} argv
* @param {Array} args
* @param {Array} unknown
* @api private
*/
executeSubCommand(argv:string[], args:string[], unknown:string[]):any; /* child_process.ChildProcess */
/**
* Normalize `args`, splitting joined short flags. For example
* the arg "-abc" is equivalent to "-a -b -c".
* This also normalizes equal sign and splits "--abc=def" into "--abc def".
*
* @param {Array} args
* @return {Array}
* @api private
*/
normalize(args:string[]):string[];
/**
* Parse command `args`.
*
* When listener(s) are available those
* callbacks are invoked, otherwise the "*"
* event is emitted and those actions are invoked.
*
* @param {Array} args
* @return {Command} for chaining
* @api private
*/
parseArgs(args:string[], unknown:string[]):ICommand;
/**
* Return an option matching `arg` if any.
*
* @param {String} arg
* @return {Option}
* @api private
*/
optionFor(arg:string):IOption;
/**
* Parse options from `argv` returning `argv`
* void of these options.
*
* @param {Array} argv
* @return {Array}
* @api public
*/
parseOptions(argv:string[]): {args:string[]; unknown:string[];};
/**
* Return an object containing options as key-value pairs
*
* @return {Object}
* @api public
*/
opts():any;
/**
* Argument `name` is missing.
*
* @param {String} name
* @api private
*/
missingArgument(name:string):void;
/**
* `Option` is missing an argument, but received `flag` or nothing.
*
* @param {String} option
* @param {String} flag
* @api private
*/
optionMissingArgument(option:{flags:string;}, flag?:string):void;
/**
* Unknown option `flag`.
*
* @param {String} flag
* @api private
*/
unknownOption(flag:string):void;
/**
* Set the program version to `str`.
*
* This method auto-registers the "-V, --version" flag
* which will print the version number when passed.
*
* @param {String} str
* @param {String} flags
* @return {Command} for chaining
* @api public
*/
version(str:string, flags?:string):ICommand;
/**
* Set the description to `str`.
*
* @param {String} str
* @return {String|Command}
* @api public
*/
description(str:string):ICommand;
description():string;
/**
* Set an alias for the command
*
* @param {String} alias
* @return {String|Command}
* @api public
*/
alias(alias:string):ICommand;
alias():string;
/**
* Set / get the command usage `str`.
*
* @param {String} str
* @return {String|Command}
* @api public
*/
usage(str:string):ICommand;
usage():string;
/**
* Get the name of the command
*
* @param {String} name
* @return {String|Command}
* @api public
*/
name():string;
/**
* Return the largest option length.
*
* @return {Number}
* @api private
*/
largestOptionLength():number;
/**
* Return help for options.
*
* @return {String}
* @api private
*/
optionHelp():string;
/**
* Return command help documentation.
*
* @return {String}
* @api private
*/
commandHelp():string;
/**
* Return program help documentation.
*
* @return {String}
* @api private
*/
helpInformation():string;
/**
* Output help information for this command
*
* @api public
*/
outputHelp():void;
/**
* Output help information and exit.
*
* @api public
*/
help():void;
}
//
//
// since TypeScript (and ECMA6) does not supports module.exports,
// there is no way to set the default Command instance as the module itself.
// It's ugly but the only way is to copy all the methods from Command
// and paste it in the module as functions exports.
//
//
interface IOptionStatic {
/**
* Initialize a new `Option` with the given `flags` and `description`.
*
* @param {String} flags
* @param {String} description
* @api public
*/
new (flags:string, description?:string):IOption;
}
/**
* Register callback fn for the command.
*/
export function action(fn:(...args:any[]) => any):Command;
interface IOption {
flags:string;
required:boolean;
optional:boolean;
bool:boolean;
short?:string;
long:string;
description:string;
/**
* Define option with flags, description and optional coercion function and default value.
* The flags string should contain both the short and long flags
* separated by comma, a pipe or space. The following are all valid
* all will output this way when --help is used.
*
* "-p, --pepper"
* "-p|--pepper"
* "-p --pepper"
*
* @param flags the option flags.
* @param description the option description. The description is printed when "--help" is used.
* @param coerceFn (optional) specifies a callback function to coerce the option arg.
* @param defaultValue (optional) specifies a default value.
*/
export function option(flags:string, description:string, coerceFn?:(value:string) => any, defaultValue?:any):Command;
/**
* Return option name.
*
* @return {String}
* @api private
*/
name():string;
/**
* Check if `arg` matches the short or long flag.
*
* @param {String} arg
* @return {Boolean}
* @api private
*/
is(arg:string):boolean;
}
/**
* Sets the command version
*/
export function version(version:string):Command;
interface IExportedCommand extends ICommand {
Command: commander.ICommandStatic;
Option: commander.IOptionStatic;
}
}
/**
* Parse the arguments array and invokes the commands passing the parsed options.
* @param argv the arguments array.
*/
export function parse(argv:string[]):Command;
/**
* Gets or sets the command description.
* @param description the new description for the command. When ommited this returns the current description, otherwise returns the current Command.
*/
export function description(description:string):Command;
export function description():string;
/**
* Gets or sets the usage help string.
*/
export function usage(usage:string):Command;
export function usage():string;
/*
* Prompt the user for a value, calling the callback function.
*
* Supports single-line and multi-line prompts.
* To issue a single-line prompt simply add a whitespace
* to the end of label, something like "name: ", whereas
* for a multi-line prompt omit this "description:".
* @param label the label string to be printed in console.
* @param callback a callback function to handle the inputed string.
*/
export function prompt(label:string, callback:(value:string) => any):void;
export function promptForNumber(label:string, callback:(value:number) => any):void;
export function promptForDate(label:string, callback:(value:Date) => any):void;
export function promptSingleLine(label:string, callback:(value:string) => any):void;
export function promptMultiLine(label:string, callback:(value:string) => any):void;
/**
* Prompt for password with a label, a optional mask char and callback function.
* The mask string defaults to '', aka no output is written while typing, you may want to use "*" etc.
*/
export function password(label:string, mask:string, callback:(value:string) => any):void;
export function password(label:string, callback:(value:string) => any):void;
/**
* Prompts the user for a confirmation.
*/
export function confirm(label:string, callback:(flag:boolean) => any):void;
/**
* Prompt for password with str, mask char and callback fn(val).
* The mask string defaults to '', aka no output is written while typing, you may want to use "*" etc.
*/
export function choose(options:string[], callback:(idx:number) => any):void;
export function choose(options:any[], callback:(idx:number) => any):void;
/**
* Add command with the specified name. Returns a new instance of Command.
*
* The .action() callback is invoked when the
* command name is specified via ARGV,
* and the remaining arguments are applied to the
* function for access.
* When the name is "*" an un-matched command
* will be passed as the first arg, followed by
* the rest of ARGV remaining.
*
* @param name the name of the command. Pass "*" to trap un-matched commands.
*/
export function command(name:string):Command;
}
declare module "commander" {
var _tmp:commander.IExportedCommand;
export = _tmp;
}