Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Run a command from within a command #1

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
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 src/command/command-contract.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,5 +19,5 @@ export interface CommandContract {
/**
* Run the console command.
*/
run(): any | Promise<any>
run(): Promise<any> | any
}
30 changes: 23 additions & 7 deletions src/command/command.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,12 @@
import { IO } from '../io/io'
import Map from '@supercharge/map'
import Str from '@supercharge/strings'
import { Input } from '../input/input'
import { tap } from '@supercharge/goodies'
import { Application } from '../application'
import { ArgvInput } from '../input/argv-input'
import { InputOption } from '../input/input-option'
import { ObjectInput } from '../input/object-input'
import { CommandContract } from './command-contract'
import { InputArgument } from '../input/input-argument'
import { InputDefinition } from '../input/input-definition'
Expand All @@ -19,8 +21,8 @@ interface CommandMeta {
ignoreValidationErrors: boolean
application?: Application

input: Input
definition: InputDefinition
input: ArgvInput

io: IO
}
Expand Down Expand Up @@ -225,7 +227,7 @@ export class Command implements CommandContract {
*
* @returns {ArgvInput}
*/
private input (): ArgvInput {
private input (): Input {
if (!this.meta.input) {
throw new Error('Missing input')
}
Expand All @@ -236,13 +238,13 @@ export class Command implements CommandContract {
/**
* Assign the given `argv` input to this command.
*
* @param argv
* @param args
*
* @returns {ThisType}
*/
private withInput (argv: ArgvInput): this {
private withInput (args: Input): this {
try {
this.meta.input = argv.bind(this.definition())
this.meta.input = args.bind(this.definition())
} catch (error) {
if (this.shouldThrowValidationErrors()) {
throw error
Expand Down Expand Up @@ -351,7 +353,7 @@ export class Command implements CommandContract {
* The code to run is provided in the `handle` method. This
* `handle` method must be implemented by subclasses.
*/
async handle (argv: ArgvInput): Promise<any> {
async handle (argv: Input): Promise<void> {
await this.withInput(argv).run()
}

Expand All @@ -360,7 +362,21 @@ export class Command implements CommandContract {
*
* @returns {Promise}
*/
run (): any | Promise<any> {
run (): Promise<any> | any {
throw new Error(`You must implement the "run" method in your "${this.getName()}" command`)
}

/**
* Run the given `commandName` with the provided `parameters`.
*
* @param commandName
* @param parameters
*/
async runCommand (commandName: string, parameters?: { arguments?: Record<string, any>, options?: Record<string, any> }): Promise<void> {
const command = this.application().get(commandName)

await command.handle(
new ObjectInput(commandName, parameters)
)
}
}
127 changes: 127 additions & 0 deletions src/input/object-input.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
'use strict'

import { Input } from './input'
import { ValidationError } from '../errors'

export class ObjectInput extends Input {
private readonly commandName: string

/**
* The input arguments. By default `process.argv.slice(2)`
*/
private readonly parameters: {
arguments?: Record<string, any>
options?: Record<string, any>
}

/**
* Create a new instance for the given `args`.
*
* @param parameters
*/
constructor (commandName: string, parameters?: { arguments?: Record<string, any>, options?: Record<string, any> }) {
super()

this.commandName = commandName
this.parameters = parameters ?? { arguments: {}, options: {} }
}

/**
* Parse the command line input (arguments and options).
*/
parse (): this {
return this
.assignArgumentsFrom(this.parameters.arguments ?? {})
.assignOptionsFrom(this.parameters.options ?? {})
}

/**
* Assign the input values from `argv` to the defined arguments.
*
* @param argv
*
* @returns {ThisType}
*/
private assignArgumentsFrom (args: { [key: string]: any }): this {
Object.entries(args).forEach(([name, value]) => {
// add another argument if the command expects it
if (this.definition().hasArgument(name)) {
const arg = this.definition().argument(name)

return this.arguments().set(arg?.name(), value)
}

this.ensureExpectedArguments(Object.keys(args))

throw new ValidationError(`Too many arguments: expected arguments "${
this.definition().argumentNames().join(', ')
}"`)
})

return this
}

/**
* Ensure the input definition expects arguments. Throws an
* error if the comamnd doesn’t expect any arg arguments.
*
* @param {String[]} args
*
* @throws
*/
private ensureExpectedArguments (args: string[]): void {
if (this.definition().arguments().isNotEmpty()) {
// expects arguments
return
}

if (args[0]) {
throw new ValidationError(`No arguments expected for command "${this.commandName}"`)
}

throw new ValidationError(`No arguments expected, got ${args.join(', ')}`)
}

/**
* Assign the input values from `argv` to the defined options.
*
* @param argv
*
* @returns {ThisType}
*/
private assignOptionsFrom (options: { [key: string]: any }): this {
Object.entries(options).forEach(([name, value]) => {
if (this.definition().hasOptionShortcut(name)) {
const option = this.definition().optionByShortcut(name)

return this.setOption(option?.name(), value)
}

if (this.definition().isMissingOption(name)) {
throw new ValidationError(`Unexpected option "${name}"`)
}

const option = this.definition().option(name)

if (option.isRequired() && !value) {
throw new ValidationError(`The option "${name}" requires a value`)
}

this.options().set(name, value)
})

return this
}

/**
* Returns the first argument. This typically represents the command name (if available).
*
* @returns {String}
*/
firstArgument (): string {
return ''

// TODO
// return this.parsed._[0] ?? ''
}
}
43 changes: 43 additions & 0 deletions test/command/command.js
Original file line number Diff line number Diff line change
Expand Up @@ -249,6 +249,49 @@ test('Command', async () => {
command.input()
})
})

test('runCommand', async t => {
const app = new Application()

const command1 = new Command('first')
app.add(command1)

let didCommand2Ran = false
let parametersFromCommand2 = {}

class SecondCommand extends Command {
configure () {
this
.addArgument('path', argument => argument.optional())
.addOption('help', option => option.optional())
.addOption('value', option => option.optional())
}

run () {
didCommand2Ran = true

parametersFromCommand2 = {
arguments: this.input().arguments().toObject(),
options: this.input().options().toObject()
}
}
}

const command2 = new SecondCommand('second-command')
app.add(command2)

const runCommandParameters = {
arguments: {
path: 'a/b/c'
},
options: { help: true, value: 1 }
}

await command1.runCommand('second-command', runCommandParameters)

t.equal(didCommand2Ran, true)
t.same(parametersFromCommand2, runCommandParameters)
})
})

class HiddenCommand extends Command {
Expand Down
Loading