Mercurial > prosody-hg
comparison util/argparse.lua @ 13733:48c056c10e5a 13.0
util.argparse: Add strict mode + tests
| author | Matthew Wild <mwild1@gmail.com> |
|---|---|
| date | Mon, 17 Feb 2025 18:24:23 +0000 |
| parents | d78e0f422464 |
| children | 81856814d74f |
comparison
equal
deleted
inserted
replaced
| 13732:1465b1e305df | 13733:48c056c10e5a |
|---|---|
| 1 local function parse(arg, config) | 1 local function parse(arg, config) |
| 2 local short_params = config and config.short_params or {}; | 2 local short_params = config and config.short_params or {}; |
| 3 local value_params = config and config.value_params or {}; | 3 local value_params = config and config.value_params or {}; |
| 4 local array_params = config and config.array_params or {}; | 4 local array_params = config and config.array_params or {}; |
| 5 local kv_params = config and config.kv_params or {}; | |
| 6 local strict = config and config.strict; | |
| 5 local stop_on_positional = not config or config.stop_on_positional ~= false; | 7 local stop_on_positional = not config or config.stop_on_positional ~= false; |
| 6 | 8 |
| 7 local parsed_opts = {}; | 9 local parsed_opts = {}; |
| 8 | 10 |
| 9 if #arg == 0 then | 11 if #arg == 0 then |
| 31 | 33 |
| 32 if not param then | 34 if not param then |
| 33 return nil, "param-not-found", raw_param; | 35 return nil, "param-not-found", raw_param; |
| 34 end | 36 end |
| 35 | 37 |
| 38 local uparam = param:match("^[^=]*"):gsub("%-", "_"); | |
| 39 | |
| 36 local param_k, param_v; | 40 local param_k, param_v; |
| 37 if value_params[param] or array_params[param] then | 41 if value_params[uparam] or array_params[uparam] then |
| 38 param_k, param_v = param, table.remove(arg, 1); | 42 param_k, param_v = uparam, table.remove(arg, 1); |
| 39 if not param_v then | 43 if not param_v then |
| 40 return nil, "missing-value", raw_param; | 44 return nil, "missing-value", raw_param; |
| 41 end | 45 end |
| 42 else | 46 else |
| 43 param_k, param_v = param:match("^([^=]+)=(.+)$"); | 47 param_k, param_v = param:match("^([^=]+)=(.+)$"); |
| 47 else | 51 else |
| 48 param_k, param_v = param, true; | 52 param_k, param_v = param, true; |
| 49 end | 53 end |
| 50 end | 54 end |
| 51 param_k = param_k:gsub("%-", "_"); | 55 param_k = param_k:gsub("%-", "_"); |
| 56 if strict and not kv_params[param_k] then | |
| 57 return nil, "param-not-found", raw_param; | |
| 58 end | |
| 52 end | 59 end |
| 53 if array_params[param] then | 60 if array_params[uparam] then |
| 54 if parsed_opts[param_k] then | 61 if parsed_opts[param_k] then |
| 55 table.insert(parsed_opts[param_k], param_v); | 62 table.insert(parsed_opts[param_k], param_v); |
| 56 else | 63 else |
| 57 parsed_opts[param_k] = { param_v }; | 64 parsed_opts[param_k] = { param_v }; |
| 58 end | 65 end |
