Skip to content

Commit

Permalink
fix: merge dot-nested options
Browse files Browse the repository at this point in the history
  • Loading branch information
egoist committed Nov 26, 2018
1 parent dc3e2da commit 8ec05e9
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 2 deletions.
1 change: 1 addition & 0 deletions examples/dot-nested-options.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ const cli = require('../src/index')()
cli
.command('build', 'desc')
.option('--env <env>', 'Set envs')
.option('--foo-bar <value>', 'Set foo bar')
.example('--env.API_SECRET xxx')
.action(options => {
console.log(options)
Expand Down
7 changes: 5 additions & 2 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import path from 'path'
import mri, { Options as MriOpts } from 'mri'
import Command, { CommandConfig, HelpCallback, CommandExample } from './Command'
import { OptionConfig } from './Option'
import { getMriOptions, camelcase } from './utils'
import { getMriOptions, camelcase, setDotProp } from './utils'

interface ParsedArgv {
args: ReadonlyArray<string>
Expand Down Expand Up @@ -192,7 +192,10 @@ class CAC extends EventEmitter {
'--': argsAfterDoubleDashes
}
for (const key of Object.keys(parsed)) {
options[camelcase(key)] = parsed[key]
const keys = key.split('.').map((v, i) => {
return i === 0 ? camelcase(v) : v
})
setDotProp(options, keys, parsed[key])
}

return {
Expand Down
22 changes: 22 additions & 0 deletions src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -84,3 +84,25 @@ export const camelcase = (input: string) => {
return p1 + p2.toUpperCase()
})
}

export const setDotProp = (
obj: { [k: string]: any },
keys: string[],
val: any
) => {
let i = 0
let length = keys.length
let t = obj
let x
for (; i < length; ++i) {
x = t[keys[i]]
t = t[keys[i]] =
i === length - 1
? val
: x != null
? x
: !!~keys[i + 1].indexOf('.') || !(+keys[i + 1] > -1)
? {}
: []
}
}

0 comments on commit 8ec05e9

Please sign in to comment.