# HG changeset patch # User Kim Alvefur # Date 1641354387 -3600 # Node ID 4ee9a912ceea4f2a0ce6ebc3cbc5ff295f36dda2 # Parent 706f7d1affc28f395c479a79386220aa9904967c util.argparse: Add support for repeatable parameters These are gathered into arrays diff -r 706f7d1affc2 -r 4ee9a912ceea spec/util_argparse_spec.lua --- a/spec/util_argparse_spec.lua Sat Jun 17 13:37:33 2023 +0200 +++ b/spec/util_argparse_spec.lua Wed Jan 05 04:46:27 2022 +0100 @@ -50,4 +50,9 @@ assert.equal("-h", where, "returned where"); end); + it("supports array arguments", function () + local opts, err = parse({ "--item"; "foo"; "--item"; "bar" }, { array_params = { item = true } }); + assert.falsy(err); + assert.same({"foo","bar"}, opts.item); + end) end); diff -r 706f7d1affc2 -r 4ee9a912ceea util/argparse.lua --- a/util/argparse.lua Sat Jun 17 13:37:33 2023 +0200 +++ b/util/argparse.lua Wed Jan 05 04:46:27 2022 +0100 @@ -1,6 +1,7 @@ local function parse(arg, config) local short_params = config and config.short_params or {}; local value_params = config and config.value_params or {}; + local array_params = config and config.array_params or {}; local parsed_opts = {}; @@ -30,7 +31,7 @@ end local param_k, param_v; - if value_params[param] then + if value_params[param] or array_params[param] then param_k, param_v = param, table.remove(arg, 1); if not param_v then return nil, "missing-value", raw_param; @@ -46,7 +47,15 @@ end param_k = param_k:gsub("%-", "_"); end - parsed_opts[param_k] = param_v; + if array_params[param] then + if parsed_opts[param_k] then + table.insert(parsed_opts[param_k], param_v); + else + parsed_opts[param_k] = { param_v }; + end + else + parsed_opts[param_k] = param_v; + end end for i = 1, #arg do parsed_opts[i] = arg[i];