Software /
code /
prosody
Comparison
util/argparse.lua @ 10651:1196f1e8d178
util.startup: Break out command line argument parsing into util.argparse
This will allow using it from other places such as prosodyctl
sub-commands and plugins
author | Kim Alvefur <zash@zash.se> |
---|---|
date | Wed, 19 Feb 2020 21:38:00 +0100 |
child | 10936:d770435f0f84 |
comparison
equal
deleted
inserted
replaced
10650:324a0c7d1c6a | 10651:1196f1e8d178 |
---|---|
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 print("Unknown command-line option: "..tostring(param)); | |
30 print("Perhaps you meant to use prosodyctl instead?"); | |
31 os.exit(1); | |
32 end | |
33 | |
34 local param_k, param_v; | |
35 if value_params[param] then | |
36 param_k, param_v = param, table.remove(arg, 1); | |
37 if not param_v then | |
38 print("Expected a value to follow command-line option: "..raw_param); | |
39 os.exit(1); | |
40 end | |
41 else | |
42 param_k, param_v = param:match("^([^=]+)=(.+)$"); | |
43 if not param_k then | |
44 if param:match("^no%-") then | |
45 param_k, param_v = param:sub(4), false; | |
46 else | |
47 param_k, param_v = param, true; | |
48 end | |
49 end | |
50 end | |
51 parsed_opts[param_k] = param_v; | |
52 end | |
53 return parsed_opts; | |
54 end | |
55 | |
56 return { | |
57 parse = parse; | |
58 } |