Skip to content
Merged
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
9 changes: 7 additions & 2 deletions lib/cli/kit/parse_args.rb
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,12 @@ module ParseArgs
# and the resulting args[:opts] is pretty broad. There seems to be minimal value in expressing a
# tighter subset of T.untyped.

sig { params(args: String, opts_defn: T::Hash[Symbol, T::Array[T.untyped]]).returns(T::Hash[Symbol, T.untyped]) }
sig do
params(
args: T.any(Array, String),
opts_defn: T::Hash[Symbol, T::Array[T.untyped]],
).returns(T::Hash[Symbol, T.untyped])
end
def parse_args(args, opts_defn)
start_opts, parser_config = opts_defn.reduce([{}, []]) do |(ini, pcfg), (n, cfg)|
(vals, desc, short, klass) = cfg
Expand Down Expand Up @@ -43,7 +48,7 @@ def parse_args(args, opts_defn)
end
end

arg_v = args.strip.split(/\s+/).map(&:strip)
arg_v = (args.is_a?(Array) ? args : args.strip.split(/\s+/)).map(&:strip)
sub = prsr.parse(arg_v)

{ opts: start_opts.merge(acc_opts) }.tap do |a|
Expand Down
23 changes: 23 additions & 0 deletions test/cli/kit/parse_args_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,9 @@ def test_positional

@cmd.call('alpha 1')
assert_equal(['alpha', '1'], @cmd.args[:sub])

@cmd.call(['alpha', '1'])
assert_equal(['alpha', '1'], @cmd.args[:sub])
end

def test_options_default
Expand All @@ -46,6 +49,11 @@ def test_options_default
{ maybe: false, sum: 11, str: 'foo', opt: 'init_val', snake_squad_alpha: 'snakes' },
@cmd.args[:opts],
)
@cmd.call([])
assert_equal(
{ maybe: false, sum: 11, str: 'foo', opt: 'init_val', snake_squad_alpha: 'snakes' },
@cmd.args[:opts],
)
end

def test_options_short
Expand All @@ -64,6 +72,21 @@ def test_options_short
@cmd.args[:opts],
)

@cmd.call(['-m', '-i', '-c', '100', '-s', '111', '-v', 'bar', '-x', 'baz', '-o', 'other_val', '-k', 'cobras'])
assert_equal(
{
maybe: true,
choice: true,
count: 100,
sum: 111,
val: 'bar',
str: 'baz',
opt: 'other_val',
snake_squad_alpha: 'cobras',
},
@cmd.args[:opts],
)

# assume the default value for '-o'
@cmd.call('-m -i -c 100 -s 111 -v bar -x baz -o -k cobras')
assert_equal(
Expand Down
Loading