Skip to content

Commit

Permalink
refactor: move invalid flags check to command setup function
Browse files Browse the repository at this point in the history
  • Loading branch information
eysi09 committed May 29, 2018
1 parent 5435951 commit ee89b74
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 24 deletions.
28 changes: 11 additions & 17 deletions src/cli/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
*/

import * as sywac from "sywac"
import { difference, merge, intersection } from "lodash"
import { merge, intersection } from "lodash"
import { resolve } from "path"
import { safeDump } from "js-yaml"
import stringify = require("json-stringify-safe")
Expand Down Expand Up @@ -59,7 +59,7 @@ import { Writer } from "../logger/writers/base"

import {
falsifyConflictingParams,
getAliases,
failOnInvalidOptions,
getArgSynopsis,
getKeys,
getOptionSynopsis,
Expand Down Expand Up @@ -204,19 +204,6 @@ export class GardenCli {
const root = resolve(process.cwd(), parsedOpts.root)
const { env, loglevel, silent, output } = parsedOpts

// Validate options (feels like the parser should handle this)
const builtinOptions = ["help", "h", "version", "v"]
const availableOptions = [...getAliases(options), ...getAliases(GLOBAL_OPTIONS), ...builtinOptions]
const passedOptions = cliContext.args
.filter(str => str.startsWith("-") || str.startsWith("--"))
.map(str => str.startsWith("--") ? str.slice(2) : str.slice(1))
.map(str => str.split("=")[0])
const invalid = difference(passedOptions, availableOptions)
if (invalid.length > 0) {
cliContext.cliMessage(`Received invalid flag(s): ${invalid.join(" ")}`)
return
}

// Init logger
const level = LogLevel[<string>loglevel]
let writers: Writer[] = []
Expand Down Expand Up @@ -264,16 +251,23 @@ export class GardenCli {
subCommands.forEach(subCommandCls => this.addCommand(new subCommandCls(command), parser))
argKeys.forEach(key => parser.positional(getArgSynopsis(key, args[key]), prepareArgConfig(args[key])))
optKeys.forEach(key => parser.option(getOptionSynopsis(key, options[key]), prepareOptionConfig(options[key])))

// We only check for invalid flags for the last command since it might contain flags that
// the parent is unaware of, thus causing the check to fail for the parent
if (subCommands.length < 1) {
parser.check(failOnInvalidOptions)
}
return parser
}

const commandOpts = {
const commandConfig = {
setup,
aliases: command.alias,
desc: command.help,
run: action,
}

program.command(command.name, commandOpts)
program.command(command.name, commandConfig)
}

async parse(): Promise<ParseResults> {
Expand Down
22 changes: 15 additions & 7 deletions src/cli/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
*/

import chalk from "chalk"
import { flatten, reduce } from "lodash"
import { difference, flatten, reduce } from "lodash"
import {
ChoicesParameter,
ParameterValues,
Expand Down Expand Up @@ -59,11 +59,6 @@ export const filterByArray = (obj: any, arr: string[]): any => {
}, {})
}

export function getAliases(params: ParameterValues<any>) {
return flatten(Object.entries(params)
.map(([key, param]) => param.alias ? [key, param.alias] : [key]))
}

export type FalsifiedParams = { [key: string]: false }

/**
Expand Down Expand Up @@ -92,7 +87,7 @@ export function falsifyConflictingParams(argv, params: ParameterValues<any>): Fa
}, {})
}

// Sywac transformers
// Sywac specific transformers and helpers
export function getOptionSynopsis(key: string, param: Parameter<any>): string {
return param.alias ? `-${param.alias}, --${key}` : `--${key}`
}
Expand Down Expand Up @@ -143,3 +138,16 @@ export function prepareOptionConfig(param: Parameter<any>): SywacOptionConfig {
}
return config
}

export function failOnInvalidOptions(argv, ctx) {
const validOptions = flatten(
ctx.details.types
.filter(t => t.datatype !== "command")
.map(t => t.aliases),
)
const receivedOptions = Object.keys(argv)
const invalid = difference(receivedOptions, validOptions)
if (invalid.length > 0) {
ctx.cliMessage(`Received invalid flag(s): ${invalid.join(", ")}`)
}
}

0 comments on commit ee89b74

Please sign in to comment.