-
Notifications
You must be signed in to change notification settings - Fork 0
/
argparse.lua
1527 lines (1219 loc) · 39.2 KB
/
argparse.lua
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
-- The MIT License (MIT)
-- Copyright (c) 2013 - 2018 Peter Melnichenko
-- Permission is hereby granted, free of charge, to any person obtaining a copy of
-- this software and associated documentation files (the "Software"), to deal in
-- the Software without restriction, including without limitation the rights to
-- use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
-- the Software, and to permit persons to whom the Software is furnished to do so,
-- subject to the following conditions:
-- The above copyright notice and this permission notice shall be included in all
-- copies or substantial portions of the Software.
-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
-- FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
-- COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
-- IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
-- CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
local function deep_update(t1, t2)
for k, v in pairs(t2) do
if type(v) == "table" then
v = deep_update({}, v)
end
t1[k] = v
end
return t1
end
-- A property is a tuple {name, callback}.
-- properties.args is number of properties that can be set as arguments
-- when calling an object.
local function class(prototype, properties, parent)
-- Class is the metatable of its instances.
local cl = {}
cl.__index = cl
if parent then
cl.__prototype = deep_update(deep_update({}, parent.__prototype), prototype)
else
cl.__prototype = prototype
end
if properties then
local names = {}
-- Create setter methods and fill set of property names.
for _, property in ipairs(properties) do
local name, callback = property[1], property[2]
cl[name] = function(self, value)
if not callback(self, value) then
self["_" .. name] = value
end
return self
end
names[name] = true
end
function cl.__call(self, ...)
-- When calling an object, if the first argument is a table,
-- interpret keys as property names, else delegate arguments
-- to corresponding setters in order.
if type((...)) == "table" then
for name, value in pairs((...)) do
if names[name] then
self[name](self, value)
end
end
else
local nargs = select("#", ...)
for i, property in ipairs(properties) do
if i > nargs or i > properties.args then
break
end
local arg = select(i, ...)
if arg ~= nil then
self[property[1]](self, arg)
end
end
end
return self
end
end
-- If indexing class fails, fallback to its parent.
local class_metatable = {}
class_metatable.__index = parent
function class_metatable.__call(self, ...)
-- Calling a class returns its instance.
-- Arguments are delegated to the instance.
local object = deep_update({}, self.__prototype)
setmetatable(object, self)
return object(...)
end
return setmetatable(cl, class_metatable)
end
local function typecheck(name, types, value)
for _, type_ in ipairs(types) do
if type(value) == type_ then
return true
end
end
error(("bad property '%s' (%s expected, got %s)"):format(name, table.concat(types, " or "), type(value)))
end
local function typechecked(name, ...)
local types = {...}
return {name, function(_, value) typecheck(name, types, value) end}
end
local multiname = {"name", function(self, value)
typecheck("name", {"string"}, value)
for alias in value:gmatch("%S+") do
self._name = self._name or alias
table.insert(self._aliases, alias)
end
-- Do not set _name as with other properties.
return true
end}
local function parse_boundaries(str)
if tonumber(str) then
return tonumber(str), tonumber(str)
end
if str == "*" then
return 0, math.huge
end
if str == "+" then
return 1, math.huge
end
if str == "?" then
return 0, 1
end
if str:match "^%d+%-%d+$" then
local min, max = str:match "^(%d+)%-(%d+)$"
return tonumber(min), tonumber(max)
end
if str:match "^%d+%+$" then
local min = str:match "^(%d+)%+$"
return tonumber(min), math.huge
end
end
local function boundaries(name)
return {name, function(self, value)
typecheck(name, {"number", "string"}, value)
local min, max = parse_boundaries(value)
if not min then
error(("bad property '%s'"):format(name))
end
self["_min" .. name], self["_max" .. name] = min, max
end}
end
local actions = {}
local option_action = {"action", function(_, value)
typecheck("action", {"function", "string"}, value)
if type(value) == "string" and not actions[value] then
error(("unknown action '%s'"):format(value))
end
end}
local option_init = {"init", function(self)
self._has_init = true
end}
local option_default = {"default", function(self, value)
if type(value) ~= "string" then
self._init = value
self._has_init = true
return true
end
end}
local add_help = {"add_help", function(self, value)
typecheck("add_help", {"boolean", "string", "table"}, value)
if self._has_help then
table.remove(self._options)
self._has_help = false
end
if value then
local help = self:flag()
:description "Show this help message and exit."
:action(function()
print(self:get_help())
os.exit(0)
end)
if value ~= true then
help = help(value)
end
if not help._name then
help "-h" "--help"
end
self._has_help = true
end
end}
local Parser = class({
_arguments = {},
_options = {},
_commands = {},
_mutexes = {},
_groups = {},
_require_command = true,
_handle_options = true
}, {
args = 3,
typechecked("name", "string"),
typechecked("description", "string"),
typechecked("epilog", "string"),
typechecked("usage", "string"),
typechecked("help", "string"),
typechecked("require_command", "boolean"),
typechecked("handle_options", "boolean"),
typechecked("action", "function"),
typechecked("command_target", "string"),
typechecked("help_vertical_space", "number"),
typechecked("usage_margin", "number"),
typechecked("usage_max_width", "number"),
typechecked("help_usage_margin", "number"),
typechecked("help_description_margin", "number"),
typechecked("help_max_width", "number"),
add_help
})
local Command = class({
_aliases = {}
}, {
args = 3,
multiname,
typechecked("description", "string"),
typechecked("epilog", "string"),
typechecked("target", "string"),
typechecked("usage", "string"),
typechecked("help", "string"),
typechecked("require_command", "boolean"),
typechecked("handle_options", "boolean"),
typechecked("action", "function"),
typechecked("command_target", "string"),
typechecked("help_vertical_space", "number"),
typechecked("usage_margin", "number"),
typechecked("usage_max_width", "number"),
typechecked("help_usage_margin", "number"),
typechecked("help_description_margin", "number"),
typechecked("help_max_width", "number"),
typechecked("hidden", "boolean"),
add_help
}, Parser)
local Argument = class({
_minargs = 1,
_maxargs = 1,
_mincount = 1,
_maxcount = 1,
_defmode = "unused",
_show_default = true
}, {
args = 5,
typechecked("name", "string"),
typechecked("description", "string"),
option_default,
typechecked("convert", "function", "table"),
boundaries("args"),
typechecked("target", "string"),
typechecked("defmode", "string"),
typechecked("show_default", "boolean"),
typechecked("argname", "string", "table"),
typechecked("hidden", "boolean"),
option_action,
option_init
})
local Option = class({
_aliases = {},
_mincount = 0,
_overwrite = true
}, {
args = 6,
multiname,
typechecked("description", "string"),
option_default,
typechecked("convert", "function", "table"),
boundaries("args"),
boundaries("count"),
typechecked("target", "string"),
typechecked("defmode", "string"),
typechecked("show_default", "boolean"),
typechecked("overwrite", "boolean"),
typechecked("argname", "string", "table"),
typechecked("hidden", "boolean"),
option_action,
option_init
}, Argument)
function Parser:_inherit_property(name, default)
local element = self
while true do
local value = element["_" .. name]
if value ~= nil then
return value
end
if not element._parent then
return default
end
element = element._parent
end
end
function Argument:_get_argument_list()
local buf = {}
local i = 1
while i <= math.min(self._minargs, 3) do
local argname = self:_get_argname(i)
if self._default and self._defmode:find "a" then
argname = "[" .. argname .. "]"
end
table.insert(buf, argname)
i = i+1
end
while i <= math.min(self._maxargs, 3) do
table.insert(buf, "[" .. self:_get_argname(i) .. "]")
i = i+1
if self._maxargs == math.huge then
break
end
end
if i < self._maxargs then
table.insert(buf, "...")
end
return buf
end
function Argument:_get_usage()
local usage = table.concat(self:_get_argument_list(), " ")
if self._default and self._defmode:find "u" then
if self._maxargs > 1 or (self._minargs == 1 and not self._defmode:find "a") then
usage = "[" .. usage .. "]"
end
end
return usage
end
function actions.store_true(result, target)
result[target] = true
end
function actions.store_false(result, target)
result[target] = false
end
function actions.store(result, target, argument)
result[target] = argument
end
function actions.count(result, target, _, overwrite)
if not overwrite then
result[target] = result[target] + 1
end
end
function actions.append(result, target, argument, overwrite)
result[target] = result[target] or {}
table.insert(result[target], argument)
if overwrite then
table.remove(result[target], 1)
end
end
function actions.concat(result, target, arguments, overwrite)
if overwrite then
error("'concat' action can't handle too many invocations")
end
result[target] = result[target] or {}
for _, argument in ipairs(arguments) do
table.insert(result[target], argument)
end
end
function Argument:_get_action()
local action, init
if self._maxcount == 1 then
if self._maxargs == 0 then
action, init = "store_true", nil
else
action, init = "store", nil
end
else
if self._maxargs == 0 then
action, init = "count", 0
else
action, init = "append", {}
end
end
if self._action then
action = self._action
end
if self._has_init then
init = self._init
end
if type(action) == "string" then
action = actions[action]
end
return action, init
end
-- Returns placeholder for `narg`-th argument.
function Argument:_get_argname(narg)
local argname = self._argname or self:_get_default_argname()
if type(argname) == "table" then
return argname[narg]
else
return argname
end
end
function Argument:_get_default_argname()
return "<" .. self._name .. ">"
end
function Option:_get_default_argname()
return "<" .. self:_get_default_target() .. ">"
end
-- Returns labels to be shown in the help message.
function Argument:_get_label_lines()
return {self._name}
end
function Option:_get_label_lines()
local argument_list = self:_get_argument_list()
if #argument_list == 0 then
-- Don't put aliases for simple flags like `-h` on different lines.
return {table.concat(self._aliases, ", ")}
end
local longest_alias_length = -1
for _, alias in ipairs(self._aliases) do
longest_alias_length = math.max(longest_alias_length, #alias)
end
local argument_list_repr = table.concat(argument_list, " ")
local lines = {}
for i, alias in ipairs(self._aliases) do
local line = (" "):rep(longest_alias_length - #alias) .. alias .. " " .. argument_list_repr
if i ~= #self._aliases then
line = line .. ","
end
table.insert(lines, line)
end
return lines
end
function Command:_get_label_lines()
return {table.concat(self._aliases, ", ")}
end
function Argument:_get_description()
if self._default and self._show_default then
if self._description then
return ("%s (default: %s)"):format(self._description, self._default)
else
return ("default: %s"):format(self._default)
end
else
return self._description or ""
end
end
function Command:_get_description()
return self._description or ""
end
function Option:_get_usage()
local usage = self:_get_argument_list()
table.insert(usage, 1, self._name)
usage = table.concat(usage, " ")
if self._mincount == 0 or self._default then
usage = "[" .. usage .. "]"
end
return usage
end
function Argument:_get_default_target()
return self._name
end
function Option:_get_default_target()
local res
for _, alias in ipairs(self._aliases) do
if alias:sub(1, 1) == alias:sub(2, 2) then
res = alias:sub(3)
break
end
end
res = res or self._name:sub(2)
return (res:gsub("-", "_"))
end
function Option:_is_vararg()
return self._maxargs ~= self._minargs
end
function Parser:_get_fullname()
local parent = self._parent
local buf = {self._name}
while parent do
table.insert(buf, 1, parent._name)
parent = parent._parent
end
return table.concat(buf, " ")
end
function Parser:_update_charset(charset)
charset = charset or {}
for _, command in ipairs(self._commands) do
command:_update_charset(charset)
end
for _, option in ipairs(self._options) do
for _, alias in ipairs(option._aliases) do
charset[alias:sub(1, 1)] = true
end
end
return charset
end
function Parser:argument(...)
local argument = Argument(...)
table.insert(self._arguments, argument)
return argument
end
function Parser:option(...)
local option = Option(...)
if self._has_help then
table.insert(self._options, #self._options, option)
else
table.insert(self._options, option)
end
return option
end
function Parser:flag(...)
return self:option():args(0)(...)
end
function Parser:command(...)
local command = Command():add_help(true)(...)
command._parent = self
table.insert(self._commands, command)
return command
end
function Parser:mutex(...)
local elements = {...}
for i, element in ipairs(elements) do
local mt = getmetatable(element)
assert(mt == Option or mt == Argument, ("bad argument #%d to 'mutex' (Option or Argument expected)"):format(i))
end
table.insert(self._mutexes, elements)
return self
end
function Parser:group(name, ...)
assert(type(name) == "string", ("bad argument #1 to 'group' (string expected, got %s)"):format(type(name)))
local group = {name = name, ...}
for i, element in ipairs(group) do
local mt = getmetatable(element)
assert(mt == Option or mt == Argument or mt == Command,
("bad argument #%d to 'group' (Option or Argument or Command expected)"):format(i + 1))
end
table.insert(self._groups, group)
return self
end
local usage_welcome = "Usage: "
function Parser:get_usage()
if self._usage then
return self._usage
end
local usage_margin = self:_inherit_property("usage_margin", #usage_welcome)
local max_usage_width = self:_inherit_property("usage_max_width", 70)
local lines = {usage_welcome .. self:_get_fullname()}
local function add(s)
if #lines[#lines]+1+#s <= max_usage_width then
lines[#lines] = lines[#lines] .. " " .. s
else
lines[#lines+1] = (" "):rep(usage_margin) .. s
end
end
-- Normally options are before positional arguments in usage messages.
-- However, vararg options should be after, because they can't be reliable used
-- before a positional argument.
-- Mutexes come into play, too, and are shown as soon as possible.
-- Overall, output usages in the following order:
-- 1. Mutexes that don't have positional arguments or vararg options.
-- 2. Options that are not in any mutexes and are not vararg.
-- 3. Positional arguments - on their own or as a part of a mutex.
-- 4. Remaining mutexes.
-- 5. Remaining options.
local elements_in_mutexes = {}
local added_elements = {}
local added_mutexes = {}
local argument_to_mutexes = {}
local function add_mutex(mutex, main_argument)
if added_mutexes[mutex] then
return
end
added_mutexes[mutex] = true
local buf = {}
for _, element in ipairs(mutex) do
if not element._hidden and not added_elements[element] then
if getmetatable(element) == Option or element == main_argument then
table.insert(buf, element:_get_usage())
added_elements[element] = true
end
end
end
if #buf == 1 then
add(buf[1])
elseif #buf > 1 then
add("(" .. table.concat(buf, " | ") .. ")")
end
end
local function add_element(element)
if not element._hidden and not added_elements[element] then
add(element:_get_usage())
added_elements[element] = true
end
end
for _, mutex in ipairs(self._mutexes) do
local is_vararg = false
local has_argument = false
for _, element in ipairs(mutex) do
if getmetatable(element) == Option then
if element:_is_vararg() then
is_vararg = true
end
else
has_argument = true
argument_to_mutexes[element] = argument_to_mutexes[element] or {}
table.insert(argument_to_mutexes[element], mutex)
end
elements_in_mutexes[element] = true
end
if not is_vararg and not has_argument then
add_mutex(mutex)
end
end
for _, option in ipairs(self._options) do
if not elements_in_mutexes[option] and not option:_is_vararg() then
add_element(option)
end
end
-- Add usages for positional arguments, together with one mutex containing them, if they are in a mutex.
for _, argument in ipairs(self._arguments) do
-- Pick a mutex as a part of which to show this argument, take the first one that's still available.
local mutex
if elements_in_mutexes[argument] then
for _, argument_mutex in ipairs(argument_to_mutexes[argument]) do
if not added_mutexes[argument_mutex] then
mutex = argument_mutex
end
end
end
if mutex then
add_mutex(mutex, argument)
else
add_element(argument)
end
end
for _, mutex in ipairs(self._mutexes) do
add_mutex(mutex)
end
for _, option in ipairs(self._options) do
add_element(option)
end
if #self._commands > 0 then
if self._require_command then
add("<command>")
else
add("[<command>]")
end
add("...")
end
return table.concat(lines, "\n")
end
local function split_lines(s)
if s == "" then
return {}
end
local lines = {}
if s:sub(-1) ~= "\n" then
s = s .. "\n"
end
for line in s:gmatch("([^\n]*)\n") do
table.insert(lines, line)
end
return lines
end
local function autowrap_line(line, max_length)
-- Algorithm for splitting lines is simple and greedy.
local result_lines = {}
-- Preserve original indentation of the line, put this at the beginning of each result line.
-- If the first word looks like a list marker ('*', '+', or '-'), add spaces so that starts
-- of the second and the following lines vertically align with the start of the second word.
local indentation = line:match("^ *")
if line:find("^ *[%*%+%-]") then
indentation = indentation .. " " .. line:match("^ *[%*%+%-]( *)")
end
-- Parts of the last line being assembled.
local line_parts = {}
-- Length of the current line.
local line_length = 0
-- Index of the next character to consider.
local index = 1
while true do
local word_start, word_finish, word = line:find("([^ ]+)", index)
if not word_start then
-- Ignore trailing spaces, if any.
break
end
local preceding_spaces = line:sub(index, word_start - 1)
index = word_finish + 1
if (#line_parts == 0) or (line_length + #preceding_spaces + #word <= max_length) then
-- Either this is the very first word or it fits as an addition to the current line, add it.
table.insert(line_parts, preceding_spaces) -- For the very first word this adds the indentation.
table.insert(line_parts, word)
line_length = line_length + #preceding_spaces + #word
else
-- Does not fit, finish current line and put the word into a new one.
table.insert(result_lines, table.concat(line_parts))
line_parts = {indentation, word}
line_length = #indentation + #word
end
end
if #line_parts > 0 then
table.insert(result_lines, table.concat(line_parts))
end
if #result_lines == 0 then
-- Preserve empty lines.
result_lines[1] = ""
end
return result_lines
end
-- Automatically wraps lines within given array,
-- attempting to limit line length to `max_length`.
-- Existing line splits are preserved.
local function autowrap(lines, max_length)
local result_lines = {}
for _, line in ipairs(lines) do
local autowrapped_lines = autowrap_line(line, max_length)
for _, autowrapped_line in ipairs(autowrapped_lines) do
table.insert(result_lines, autowrapped_line)
end
end
return result_lines
end
function Parser:_get_element_help(element)
local label_lines = element:_get_label_lines()
local description_lines = split_lines(element:_get_description())
local result_lines = {}
-- All label lines should have the same length (except the last one, it has no comma).
-- If too long, start description after all the label lines.
-- Otherwise, combine label and description lines.
local usage_margin_len = self:_inherit_property("help_usage_margin", 3)
local usage_margin = (" "):rep(usage_margin_len)
local description_margin_len = self:_inherit_property("help_description_margin", 25)
local description_margin = (" "):rep(description_margin_len)
local help_max_width = self:_inherit_property("help_max_width")
if help_max_width then
local description_max_width = math.max(help_max_width - description_margin_len, 10)
description_lines = autowrap(description_lines, description_max_width)
end
if #label_lines[1] >= (description_margin_len - usage_margin_len) then
for _, label_line in ipairs(label_lines) do
table.insert(result_lines, usage_margin .. label_line)
end
for _, description_line in ipairs(description_lines) do
table.insert(result_lines, description_margin .. description_line)
end
else
for i = 1, math.max(#label_lines, #description_lines) do
local label_line = label_lines[i]
local description_line = description_lines[i]
local line = ""
if label_line then
line = usage_margin .. label_line
end
if description_line and description_line ~= "" then
line = line .. (" "):rep(description_margin_len - #line) .. description_line
end
table.insert(result_lines, line)
end
end
return table.concat(result_lines, "\n")
end
local function get_group_types(group)
local types = {}
for _, element in ipairs(group) do
types[getmetatable(element)] = true
end
return types
end
function Parser:_add_group_help(blocks, added_elements, label, elements)
local buf = {label}
for _, element in ipairs(elements) do
if not element._hidden and not added_elements[element] then
added_elements[element] = true
table.insert(buf, self:_get_element_help(element))
end
end
if #buf > 1 then
table.insert(blocks, table.concat(buf, ("\n"):rep(self:_inherit_property("help_vertical_space", 0) + 1)))
end
end
function Parser:get_help()
if self._help then
return self._help
end
local blocks = {self:get_usage()}
local help_max_width = self:_inherit_property("help_max_width")
if self._description then
local description = self._description
if help_max_width then
description = table.concat(autowrap(split_lines(description), help_max_width), "\n")
end
table.insert(blocks, description)
end
-- 1. Put groups containing arguments first, then other arguments.
-- 2. Put remaining groups containing options, then other options.
-- 3. Put remaining groups containing commands, then other commands.
-- Assume that an element can't be in several groups.
local groups_by_type = {
[Argument] = {},
[Option] = {},
[Command] = {}
}
for _, group in ipairs(self._groups) do
local group_types = get_group_types(group)
for _, mt in ipairs({Argument, Option, Command}) do
if group_types[mt] then
table.insert(groups_by_type[mt], group)
break
end
end
end
local default_groups = {
{name = "Arguments", type = Argument, elements = self._arguments},
{name = "Options", type = Option, elements = self._options},
{name = "Commands", type = Command, elements = self._commands}