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

fix: variadic arguments error parsing #155

Open
wants to merge 1 commit into
base: master
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: 2 additions & 0 deletions src/CAC.ts
Original file line number Diff line number Diff line change
Expand Up @@ -328,6 +328,8 @@ class CAC extends EventEmitter {

command.checkRequiredArgs()

command.checkPreviousArgument()

const actionArgs: any[] = []
command.args.forEach((arg, index) => {
if (arg.variadic) {
Expand Down
12 changes: 12 additions & 0 deletions src/Command.ts
Original file line number Diff line number Diff line change
Expand Up @@ -253,6 +253,18 @@ class Command {
}
}

checkPreviousArgument() {
const length = this.args.length

for (let i = 0; i < length; i++) {
const { variadic, value } = this.args[i]

if (variadic && i !== length - 1) {
throw new CACError(`only the last argument can be variadic '${value}'`)
}
}
}

/**
* Check if the parsed options contain any unknown options
*
Expand Down
17 changes: 6 additions & 11 deletions src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,14 @@ import Option from './Option'
export const removeBrackets = (v: string) => v.replace(/[<[].+/, '').trim()

export const findAllBrackets = (v: string) => {
const ANGLED_BRACKET_RE_GLOBAL = /<([^>]+)>/g
const SQUARE_BRACKET_RE_GLOBAL = /\[([^\]]+)\]/g
const BRACKET_RE_GLOBAL = /<([^>]+)>|\[([^\]]+)\]/g

const res = []

const parse = (match: string[]) => {
let variadic = false
let value = match[1]
let value = match[1] ?? match[2]

if (value.startsWith('...')) {
value = value.slice(3)
variadic = true
Expand All @@ -22,14 +22,9 @@ export const findAllBrackets = (v: string) => {
}
}

let angledMatch
while ((angledMatch = ANGLED_BRACKET_RE_GLOBAL.exec(v))) {
res.push(parse(angledMatch))
}

let squareMatch
while ((squareMatch = SQUARE_BRACKET_RE_GLOBAL.exec(v))) {
res.push(parse(squareMatch))
let match
while ((match = BRACKET_RE_GLOBAL.exec(v))) {
res.push(parse(match))
}

return res
Expand Down