Mercurial > prosody-hg
comparison util/argparse.lua @ 11200:bf8f2da84007
Merge 0.11->trunk
| author | Kim Alvefur <zash@zash.se> |
|---|---|
| date | Thu, 05 Nov 2020 22:31:25 +0100 |
| parents | d770435f0f84 |
| children | 6425dfa3de45 |
comparison
equal
deleted
inserted
replaced
| 11199:6c7c50a4de32 | 11200:bf8f2da84007 |
|---|---|
| 1 local function parse(arg, config) | |
| 2 local short_params = config and config.short_params or {}; | |
| 3 local value_params = config and config.value_params or {}; | |
| 4 | |
| 5 local parsed_opts = {}; | |
| 6 | |
| 7 if #arg == 0 then | |
| 8 return parsed_opts; | |
| 9 end | |
| 10 while true do | |
| 11 local raw_param = arg[1]; | |
| 12 if not raw_param then | |
| 13 break; | |
| 14 end | |
| 15 | |
| 16 local prefix = raw_param:match("^%-%-?"); | |
| 17 if not prefix then | |
| 18 break; | |
| 19 elseif prefix == "--" and raw_param == "--" then | |
| 20 table.remove(arg, 1); | |
| 21 break; | |
| 22 end | |
| 23 local param = table.remove(arg, 1):sub(#prefix+1); | |
| 24 if #param == 1 and short_params then | |
| 25 param = short_params[param]; | |
| 26 end | |
| 27 | |
| 28 if not param then | |
| 29 return nil, "param-not-found", param; | |
| 30 end | |
| 31 | |
| 32 local param_k, param_v; | |
| 33 if value_params[param] then | |
| 34 param_k, param_v = param, table.remove(arg, 1); | |
| 35 if not param_v then | |
| 36 return nil, "missing-value", raw_param; | |
| 37 end | |
| 38 else | |
| 39 param_k, param_v = param:match("^([^=]+)=(.+)$"); | |
| 40 if not param_k then | |
| 41 if param:match("^no%-") then | |
| 42 param_k, param_v = param:sub(4), false; | |
| 43 else | |
| 44 param_k, param_v = param, true; | |
| 45 end | |
| 46 end | |
| 47 end | |
| 48 parsed_opts[param_k] = param_v; | |
| 49 end | |
| 50 return parsed_opts; | |
| 51 end | |
| 52 | |
| 53 return { | |
| 54 parse = parse; | |
| 55 } |
