aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorKim Alvefur <zash@zash.se>2022-01-05 04:46:27 +0100
committerKim Alvefur <zash@zash.se>2022-01-05 04:46:27 +0100
commit21740a1382cfd83686051df3cfcaed48e4ef79d5 (patch)
tree9045d2db4f0d7af6afbf00c6d63fa00f93e5ba6d
parent9f0a28f1c498a20c51af4686a5ecc9ff1b7c852c (diff)
downloadprosody-21740a1382cfd83686051df3cfcaed48e4ef79d5.tar.gz
prosody-21740a1382cfd83686051df3cfcaed48e4ef79d5.zip
util.argparse: Add support for repeatable parameters
These are gathered into arrays
-rw-r--r--spec/util_argparse_spec.lua5
-rw-r--r--util/argparse.lua13
2 files changed, 16 insertions, 2 deletions
diff --git a/spec/util_argparse_spec.lua b/spec/util_argparse_spec.lua
index 0f2430b7..40f647c9 100644
--- a/spec/util_argparse_spec.lua
+++ b/spec/util_argparse_spec.lua
@@ -50,4 +50,9 @@ describe("parse", function()
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 --git a/util/argparse.lua b/util/argparse.lua
index bd4eb220..7a55cb0b 100644
--- a/util/argparse.lua
+++ b/util/argparse.lua
@@ -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 @@ local function parse(arg, config)
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 @@ local function parse(arg, config)
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];