Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion examples/01-basic-flags/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
"description": "",
"main": "index.js",
"scripts": {
"start": "npm run build && node lib/index.js",
"start": "node --enable-source-maps lib/index.js",
"build": "tsc"
},
"keywords": [],
Expand Down
2 changes: 1 addition & 1 deletion examples/02-error-handling/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
"description": "",
"main": "index.js",
"scripts": {
"start": "npm run build && node lib/index.js",
"start": "node --enable-source-maps lib/index.js",
"build": "tsc"
},
"keywords": [],
Expand Down
2 changes: 1 addition & 1 deletion examples/03-simple-commands/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
"description": "",
"main": "index.js",
"scripts": {
"start": "npm run build && node lib/index.js",
"start": "node --enable-source-maps lib/index.js",
"build": "tsc"
},
"keywords": [],
Expand Down
2 changes: 1 addition & 1 deletion examples/04-package-manager/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
"description": "",
"main": "index.js",
"scripts": {
"start": "npm run build && node lib/index.js",
"start": "node --enable-source-maps lib/index.js",
"build": "tsc"
},
"keywords": [],
Expand Down
2 changes: 1 addition & 1 deletion examples/05-application-config/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
"description": "",
"main": "index.js",
"scripts": {
"start": "npm run build && node lib/index.js",
"start": "node --enable-source-maps lib/index.js",
"build": "tsc"
},
"keywords": [],
Expand Down
2 changes: 1 addition & 1 deletion examples/06-builtin-commands/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
"description": "",
"main": "index.js",
"scripts": {
"start": "npm run build && node lib/index.js",
"start": "node --enable-source-maps lib/index.js",
"build": "tsc"
},
"keywords": [],
Expand Down
2 changes: 1 addition & 1 deletion examples/07-prompting/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
"description": "",
"main": "index.js",
"scripts": {
"start": "npm run build && node lib/index.js",
"start": "node --enable-source-maps lib/index.js",
"build": "tsc"
},
"keywords": [],
Expand Down
10 changes: 2 additions & 8 deletions examples/07-prompting/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,6 @@ export const parserOpts: ParserOpts = {
programVersion: 'v1'
}

// Provide a custom resolver for the username key.
// This does have the downside that it will *always* try and resolve the key
// whether the user provides the flag or not.
//
// If this distinction matters, use an Argument and override the `resolveDefault` method
// to control the behaviour dependant on specificity
class UsernamePromptResolver extends Resolver {
private readonly rl: readline.Interface
constructor (id: string) {
Expand All @@ -25,9 +19,9 @@ class UsernamePromptResolver extends Resolver {
})
}

async keyExists (key: string): Promise<boolean> {
async keyExists (key: string, userDidPassArg: boolean): Promise<boolean> {
// We only care about resolving our username argument
return key === 'username'
return key === 'username' && userDidPassArg
}

async resolveKey (): Promise<string> {
Expand Down
47 changes: 47 additions & 0 deletions examples/08-command-context/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

17 changes: 17 additions & 0 deletions examples/08-command-context/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
{
"name": "08-command-context",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "node --enable-source-maps lib/index.js",
"build": "tsc"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"args.ts": "file:../..",
"typescript": "^5.1.6"
}
}
54 changes: 54 additions & 0 deletions examples/08-command-context/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
#!/usr/bin/env node
/* eslint-disable @typescript-eslint/explicit-function-return-type */

import { Args, Command, CommandRunner, ParserOpts, util } from 'args.ts'

export const parserOpts: ParserOpts = {
programName: '08-command-context',
programDescription: 'description',
programVersion: 'v1'
}

interface Context {
value: string
}

abstract class BaseCommand extends Command {
abstract runWithContext: CommandRunner<this, [Context]>

run = (): never => {
throw new TypeError('run called, expected runWithContext')
}
}

class ConcreteCommand extends BaseCommand {
runWithContext: CommandRunner<this, [Context]> = this.runner(async (args, context) => {
console.log('Ran with context:', context)
})

args = (parser: Args<{}>) => {
return parser
}
}

async function main (): Promise<void> {
const parser = new Args(parserOpts)
.command(['cmd'], new ConcreteCommand({
parserOpts,
description: 'command'
}))

const result = await parser.parse(util.makeArgs())

if (result.mode !== 'command') {
console.error('Did not get command back')
return
}

const command = result.command
await command.runWithContext({}, {
value: 'the context value!'
})
}

main().catch(console.error)
72 changes: 72 additions & 0 deletions examples/08-command-context/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
{
"exclude": [
"node_modules",
"test",
"lib"
],
"compilerOptions": {
/* Basic Options */
// "incremental": true, /* Enable incremental compilation */
"target": "ESNEXT", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019' or 'ESNEXT'. */
"module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */
"lib": ["ESNext"], /* Specify library files to be included in the compilation. */
// "allowJs": true, /* Allow javascript files to be compiled. */
// "checkJs": true, /* Report errors in .js files. */
// "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
"declaration": true, /* Generates corresponding '.d.ts' file. */
// "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */
"sourceMap": true, /* Generates corresponding '.map' file. */
// "outFile": "./", /* Concatenate and emit output to single file. */
"outDir": "lib", /* Redirect output structure to the directory. */
"rootDir": "src", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
// "composite": true, /* Enable project compilation */
// "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */
"removeComments": true, /* Do not emit comments to output. */
// "noEmit": true, /* Do not emit outputs. */
// "importHelpers": true, /* Import emit helpers from 'tslib'. */
// "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
// "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */

/* Strict Type-Checking Options */
"strict": true, /* Enable all strict type-checking options. */
// "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */
// "strictNullChecks": true, /* Enable strict null checks. */
// "strictFunctionTypes": true, /* Enable strict checking of function types. */
// "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */
// "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */
// "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */
// "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */

/* Additional Checks */
// "noUnusedLocals": true, /* Report errors on unused locals. */
// "noUnusedParameters": true, /* Report errors on unused parameters. */
// "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */
// "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */

/* Module Resolution Options */
// "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
// "baseUrl": "./", /* Base directory to resolve non-absolute module names. */
// "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
// "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */
// "typeRoots": [], /* List of folders to include type definitions from. */
// "types": [], /* Type declaration files to be included in compilation. */
// "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
"esModuleInterop": true, /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
// "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */

/* Source Map Options */
// "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
// "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */
// "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */

/* Experimental Options */
// "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */
// "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */

/* Advanced Options */
"forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */
}
}

26 changes: 14 additions & 12 deletions src/args.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,18 +16,18 @@ interface FoundCommand {
executionResult: unknown
}

interface ReturnedCommand<T> {
interface ReturnedCommand<TArgs, TCommand> {
mode: 'command'
command: Command
parsedArgs: T
command: TCommand
parsedArgs: TArgs
}

interface ParsedArgs<T> {
mode: 'args'
args: T
}

type ParseSuccess<TArgTypes> = FoundCommand | ReturnedCommand<TArgTypes> | ParsedArgs<TArgTypes>
type ParseSuccess<TArgTypes, TCommand> = FoundCommand | ReturnedCommand<TArgTypes, TCommand> | ParsedArgs<TArgTypes>
export interface DefaultArgTypes {
[k: string]: CoercedValue
['--']?: string
Expand All @@ -52,7 +52,7 @@ export interface ArgsState {
*
* It will hold all the state needed to parse inputs. This state is modified through the various helper methods defined on this class.
*/
export class Args<TArgTypes extends DefaultArgTypes = DefaultArgTypes> {
export class Args<TArgTypes extends DefaultArgTypes = DefaultArgTypes, TCommandType extends Command = Command> {
public readonly opts: StoredParserOpts
public readonly _state: ArgsState

Expand Down Expand Up @@ -116,11 +116,11 @@ export class Args<TArgTypes extends DefaultArgTypes = DefaultArgTypes> {
* @param inherit - Whether to inherit arguments from this configuration into the parser
* @returns this
*/
public command<TName extends string, TCommand extends Command> (
[name, ...aliases]: [`${TName}`, ...string[]],
command: TCommand,
public command <T extends Command> (
[name, ...aliases]: [string, ...string[]],
command: T,
inherit = false
): Args<TArgTypes> {
): Args<TArgTypes, T> {
if (this._state.commands.has(name)) {
throw new CommandError(`command '${name}' already declared`)
}
Expand Down Expand Up @@ -183,6 +183,7 @@ export class Args<TArgTypes extends DefaultArgTypes = DefaultArgTypes> {
})
}

// @ts-expect-error erased commands can't resolve into concrete type
return this
}

Expand Down Expand Up @@ -408,8 +409,8 @@ export class Args<TArgTypes extends DefaultArgTypes = DefaultArgTypes> {
* @param executeCommands - Whether to execute discovered commands, or return them
* @returns The result of the parse
*/
public async parseToResult (argString: string | string[], executeCommands = false): Promise<Result<ParseSuccess<TArgTypes>, ParseError | CoercionError[] | CommandError>> {
this.opts.logger.debug(`Beginning parse of input '${argString}'`)
public async parseToResult (argString: string | string[], executeCommands = false): Promise<Result<ParseSuccess<TArgTypes, TCommandType>, ParseError | CoercionError[] | CommandError>> {
this.opts.logger.internal(`Beginning parse of input '${argString}'`)

const tokenResult = tokenise(Array.isArray(argString) ? argString.join(' ') : argString)

Expand Down Expand Up @@ -495,6 +496,7 @@ export class Args<TArgTypes extends DefaultArgTypes = DefaultArgTypes> {
}

// Command was found, return it
// @ts-expect-error erased commands can't resolve into concrete type
return Ok({
mode: 'command',
parsedArgs: this.intoObject(args, rest?.value),
Expand All @@ -509,7 +511,7 @@ export class Args<TArgTypes extends DefaultArgTypes = DefaultArgTypes> {
* @param executeCommands - Whether to execute discovered commands, or return them
* @returns The result of the parse, never an error
*/
public async parse (argString: string | string[], executeCommands = false): Promise<ParseSuccess<TArgTypes>> {
public async parse (argString: string | string[], executeCommands = false): Promise<ParseSuccess<TArgTypes, TCommandType>> {
const result = await this.parseToResult(argString, executeCommands)

if (!result.ok) {
Expand Down
19 changes: 16 additions & 3 deletions src/builder/builtin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,8 +58,21 @@ export abstract class Builtin {
* @returns The generated help string
*/
public helpInfo (): string {
return `${this.commandTriggers.map(cmd => `${cmd} <...args>`).join(', ')} | ${this.argumentTriggers.map(arg => `--${arg}`).join(', ')}`
const commands = this.commandTriggers.map(cmd => `${cmd} <...args>`).join(', ')
const args = this.argumentTriggers.map(arg => `--${arg}`).join(', ')

if (commands && args) {
return `${commands} | ${args}`
}

if (commands) {
return commands
}

if (args) {
return args
}

return `${this.constructor.name} | no triggers`
}
}

export type BuiltinType = 'help' | 'completion' | 'version' | 'fallback'
Loading