diff --git a/examples/command/generic.ts b/examples/command/generic.ts new file mode 100755 index 00000000..7307833c --- /dev/null +++ b/examples/command/generic.ts @@ -0,0 +1,27 @@ +#!/usr/bin/env -S deno run + +import { Command } from '../../packages/command/lib/command.ts'; +import { IParseResult } from '../../packages/command/lib/types.ts'; + +// define your argument types +type Arguments = [ string, string ]; + +// define your option types +interface Options { + name: string; + age: number; + email?: string; +} + +const result: IParseResult = await new Command() + .version( '0.1.0' ) + .arguments( ' [output:string]' ) + .option( '-n, --name ', 'description ...', { required: true } ) + .option( '-a, --age ', 'description ...', { required: true } ) + .option( '-e, --email ', 'description ...' ) + .action( ( options: Options, input: string, output?: string ) => {} ) + .parse( Deno.args ); + +const options: Options = result.options; +const input: string = result.args[ 0 ]; +const output: string | undefined = result.args[ 1 ]; diff --git a/packages/command/README.md b/packages/command/README.md index 02c4e432..a539895d 100644 --- a/packages/command/README.md +++ b/packages/command/README.md @@ -68,6 +68,7 @@ - [Override exit handling](#override-exit-handling) - [Specify environment variables](#specify-the-argument-syntax) - [Specify examples](#specify-examples) +- [Generic options and arguments](#generic-options-and-arguments) - [Default options & commands](#default-options--commands) - [Version option](#version-option) - [Help option & command](#help-option--command) @@ -833,6 +834,41 @@ $ ./examples/command/examples.ts help ``` +## Generic options and arguments + +You can define an interface for your command options and a tuple for the command arguments. + +Here's how to do that: + +```typescript +#!/usr/bin/env -S deno run + +import { Command, IParseResult } from 'https://deno.land/x/cliffy/command.ts'; + +type Arguments = [ string, string ]; + +interface Options { + name: string; + age: number; + email?: string; +} + +const result: IParseResult = await new Command() + .version( '0.1.0' ) + .arguments( ' [output:string]' ) + .option( '-n, --name ', 'description ...', { required: true } ) + .option( '-a, --age ', 'description ...', { required: true } ) + .option( '-e, --email ', 'description ...' ) + .action( ( options: Options, input: string, output?: string ) => {} ) + .parse( Deno.args ); + +const options: Options = result.options; +const input: string = result.args[ 0 ]; +const output: string | undefined = result.args[ 1 ]; +``` + +**Example**: `deno run https://deno.land/x/cliffy/examples/command/generic.ts` + ## Default options & commands Every instance of the `Command` class has some pre defenied options and sub-commands. If you don't need these pre defined option's and sub-command's you can use the `BaseCommand` class instedd of the `Command` class.