-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathargparser
1304 lines (1233 loc) · 51.9 KB
/
argparser
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
#!/usr/bin/env bash
# -*- coding: utf-8 -*-
##
# Author: Ekeyme Mo <[email protected]>
#
# Some conceptions of this script are a little bit like python argparser module, so you can visit
# https://docs.python.org/3/library/argparse.html to make you easier to understand the conceptions.
#
# argparser initial function
# This function initials some globals variables and defines some functions
# requied to parse parameters from command line.
# It accepts the following optional parameters to initail globals variables:
#
# - $1: program name, default script name
# - prologue=*: text show before `usage`
# - usage=*: message show how to use program(short help message),
# default: generated from arguments added to parser
# - desc=*: short message to show what program can do, show after `usage`
# - epilog=*: text show after help message
# - prefix_chars=*: the set of characters that prefix optional arguments (default: '-')
# - help=*: full program help text, default: generated from prologue/usage/desc/epilog added to argparser
# - add_help=*: whether to add -h/--help option to argparser, default: true
# - nargs_extending_EOT=*: the character that indecates where the extending nargs(+/*) argument should stop,
# default: '-'
function argparser()
{
# Argparser reserved functions or variables.
# Attributes in this array will not be unset(tear down) after
# parser_parse() call.
__argparser_reserved_attrs__=(argparser_subargs)
# Argparser API functions or variables.
# This is a fake array which is to indicate the argparser api.
# Attributes in this array will be unset after parser_parse() call.
__argparser_api_attrs__=(argparser argparser_add_arg argparser_parse argparser_DEBUG argparser_help \
argparser_store argparser_reserve_usage)
# Functions and variables which will be unset after argparser_parser call
__argparser_tear_down_attr__=( \
# variables defined by argparse, this is generated by command line scripts
ARGPARSER_NAME ARGPARSER_UN_DEFINE __argparser_values__ __argparser_shift__num__ ARGPARSER_PA_NO_PARSE ARGPARSER_PA_PARSED ARGPARSER_OA_NO_PARSE ARGPARSER_OA_PARSED Argparser_prog_name Argparser_help Argparser_prefix_chars Argparser_nargs_extending_EOT Argparser_prologue Argparser_usage Argparser_desc Argparser_epilog Argparser_add_help _argparser_usage Argparser_argument_flag Argparser_argument_dest Argparser_argument_check Argparser_argument_action Argparser_argument_default Argparser_argument_const Argparser_argument_nargs Argparser_argument_desc Argparser_argument_metavar Argparser_argument_required Argparser_argument_choices _Argparser_argument_status __argparser_reserved_attrs__ __argparser_api_attrs__ __argparser_tear_down_attr__ \
# functions defined by argparse, this is generated by command line scripts
__tear_down__ _argparser_check_value_narg_matching _argparser_choose_dest _argparser_choose_longest_argument_string _argparser_choose_metavar _argparser_choose_shortest_optional_string _argparser_cl_arg_amount_need2reserved_now _argparser_do_action _argparser_error _argparser_final_check_argparser_aguments _argparser_format_arg_help _argparser_format_argument_flag _argparser_format_usge _argparser_get_argparser_optional_arg_key _argparser_get_argparser_positional_arg_key _argparser_get_cl_arg_values _argparser_get_extending_values _argparser_globals_register _argparser_is_callback _argparser_is_long_optional_argument _argparser_is_optional_argment _argparser_is_positional_argment _argparser_parse_long_option _argparser_parse_positional_arg _argparser_parse_short_option _argparser_prepare_argparser_aguments _argparser_reset_values_and_shift_num _argparser_set_default2dest _argparser_set_value2dest _argparser_translate _argparser_trim_option_prefixs _argparser_usage argparser argparser_DEBUG argparser_add_arg argparser_check argparser_help argparser_parse argparser_reserve_usage argparser_store)
# argparser name
# for error message
ARGPARSER_NAME=argparser
# data structure like undef in perl
# So empty `string '' != $ARGPARSER_UN_DEFINE`
ARGPARSER_UN_DEFINE=_undef_
# Internal value exchanging variable; so if you assign it a value
# you must get the value and assign value to another variable immediately,
# or it would be overwrited by other operations.
__argparser_values__=$ARGPARSER_UN_DEFINE
# Internal value exchanging variable, like __argparser_values__, but just used to exchange
# the shift num.
__argparser_shift__num__=0
# argparser app level info
Argparser_prog_name=$(basename $0)
Argparser_help=$ARGPARSER_UN_DEFINE
Argparser_prefix_chars='-'
Argparser_nargs_extending_EOT='-'
Argparser_prologue=''
Argparser_usage=$ARGPARSER_UN_DEFINE
Argparser_desc=''
Argparser_epilog=''
Argparser_add_help=true
# this is the stored string of usage
# used by _usage() and _format_usage
_argparser_usage=$ARGPARSER_UN_DEFINE
# Argument level info:
# array type, order is very important. we use the array index to get the
# right info for the argument you registerd.
Argparser_argument_flag=()
Argparser_argument_dest=()
Argparser_argument_check=()
Argparser_argument_action=()
Argparser_argument_default=()
Argparser_argument_const=()
Argparser_argument_nargs=()
Argparser_argument_desc=()
Argparser_argument_metavar=()
Argparser_argument_required=()
Argparser_argument_choices=()
# argparser argument parsing status
# 0: Positional Parameter(pp) do not show up in $@, so haven't been parsed
# 2: pp have been parsed
# 1: Optional Parameter(op) haven't been parsed
# 3: op have been parsed
ARGPARSER_PA_NO_PARSE=0
ARGPARSER_PA_PARSED=2
ARGPARSER_OA_NO_PARSE=1
ARGPARSER_OA_PARSED=3
_Argparser_argument_status=()
# subarguments
# sotre all arguments after `--`
argparser_subargs=()
# unset variables and functions after argparser_parse
function __tear_down__()
{
set -- "${__argparser_tear_down_attr__[@]}"
while (($# > 0)); do
unset "$1"
shift
done
}
# - $1: program name
# - $2: error message
# - $3: error level, like warning, error, fatal, internal
# - $4: no exit flag, if this value is set, program only prints error
# error message and do not exit.
function _argparser_error()
{
local prog=$1
local message=$2
local error_type=$(tr '[A-Z]' '[a-z]' <<< "${3:-error}")
local no_exit=$4
printf "$prog: $error_type: "'%s\n' "$message" >&2
[[ $no_exit ]] || exit 1
}
# Turn on DEBUG model
# This function implement DEBUG model by overwrite the argparser_parser function
function argparser_DEBUG()
{
_argparser_old_parse_func=$(declare -f argparser_parse)
[[ $_argparser_old_parse_func = '' ]] && \
_argparser_error "$ARGPARSER_NAME" "$FUNCNAME: debug model setup fail: argparser_parse function not found." internal
# get value from variable name
# - $1: variable name
function __argparser_get_()
{
local variable=$1
local v=$(declare -p "$variable" 2>/dev/null)
v=${v#*=}
v=${v#\'}
v=${v%\'}
printf "%s" "$v"
}
# the new argparser_parse
function argparser_parse()
{
printf "%s\n%s\n" "$ARGPARSER_NAME debug info:" "----"
# APP infomation
printf "|APP level info:\n"
printf " %s: '%s'\n" "Program name" "$Argparser_prog_name"
printf " %s: '%s'\n" "Prefix chars" "$Argparser_prefix_chars"
printf " %s: '%s'\n" "Nargs Extending EOT" "$Argparser_nargs_extending_EOT"
printf " %s: '%s'\n" "Help adding" "$Argparser_add_help"
printf " %s: '%s'\n" "Help prologue" "$Argparser_prologue"
printf " %s: '%s'\n" "Help usage" "$Argparser_usage"
printf " %s: '%s'\n" "Help desciption" "$Argparser_desc"
printf " %s: '%s'\n" "Help string" "$Argparser_help"
printf " %s: '%s'\n" "Help epilog" "$Argparser_epilog"
# help doc
printf "\n|APP help doc:\n"
echo "$(argparser_help)"
# argument infomation
printf "\n|Argument level info:\n"
local ___argparser_k_ ___argparser_arg_string_ ___argparser_dest_ \
___dest_has_value_before_ ___argparser_stored_dest_ \
___argparser_arg_desc_
# reserve the argparser_argument_* values avoiding unseting by argparser_parse
local ___argparser_argument_flag_=("${Argparser_argument_flag[@]}")
local ___argparser_argument_dest_=("${Argparser_argument_dest[@]}")
local ___argparser_argument_default_=("${Argparser_argument_default[@]}")
local ___argparser_argument_const_=("${Argparser_argument_const[@]}")
local ___argparser_argument_nargs_=("${Argparser_argument_nargs[@]}")
local ___argparser_argument_metavar_=("${Argparser_argument_metavar[@]}")
# check whether the dest variable has value before
for ___argparser_k_ in ${!___argparser_argument_flag_[@]}; do
___argparser_dest_=$(_argparser_choose_dest "${___argparser_argument_dest_[$___argparser_k_]}" \
"${___argparser_argument_flag_[$___argparser_k_]}")
___argparser_stored_dest_[$___argparser_k_]=$___argparser_dest_
if (declare -p "$___argparser_dest_" 2>/dev/null 1>/dev/null); then
___dest_has_value_before_[$___argparser_k_]='!'
fi
done
# call back the old argparser_parse function and unset _argparser_old_parse_func
eval "$_argparser_old_parse_func"
argparser_parse "$@"
unset _argparser_old_parse_func
# print debug info after argparser_parse
printf " %-15s %-5s %-10s %-10s %-10s %-13s %s\n" \
"argument" "nargs" "default" "const" "dest" "overwriting" "value"
for ___argparser_k_ in ${!___argparser_argument_flag_[@]}; do
___argparser_arg_string_=${___argparser_argument_flag_[$___argparser_k_]}
___argparser_arg_string_=${___argparser_arg_string_//'|'/,}
printf " %-15s %5s %-10s %-10s %-10s %-13s %s\n" \
"$___argparser_arg_string_" \
"${___argparser_argument_nargs_[$___argparser_k_]}" \
"${___argparser_argument_default_[$___argparser_k_]}" \
"${___argparser_argument_const_[$___argparser_k_]}" \
'$'"${___argparser_stored_dest_[$___argparser_k_]}" \
"${___dest_has_value_before_[$___argparser_k_]}" \
"$(__argparser_get_ "${___argparser_stored_dest_[$___argparser_k_]}")"
done
# subarguments
printf "\n%s\n" "|Sub arguments: $(__argparser_get_ argparser_subargs)"
unset -f __argparser_get_
}
}
# Define how a single command-line argument should be parsed.
# argparser_add_arg arg_flag [arg_flag...] [options]
# - arg_flag: either a name or a list of option strings
# [options]
# - const=*: the value produced if optional argument is encountered in standalone style(like only -f)
# (optionals only)
# - default=*: the value produced if the argument is absent from the command line
# - nargs=*: number of command-line arguments that should be consumed
# - metavar=*: a name for the argument in usage messages
# - dest=*: an destination variable name to accept value parsed by argparser
# - desc=*: description of this argument
# - action=*: an callback to be called when this argument is encountered at the command line,
# default `argparser_store`
# - choices=*: a container of the allowable values for the argument, use RegulateExpression pattern
# - required=*: whether or not the command-line option may be omitted (optionals only)
# - check=*: an callable function use to check whether values of this argument gotten is valid
function argparser_add_arg()
{
# fetch option name
local _is_positional=false
local _pattern='^[-_0-9a-zA-Z]+$'
local arg_flag=$1
shift
if _argparser_is_positional_argment "$arg_flag"; then
[[ $1 != '' && $1 != *=* ]] && \
_argparser_error $ARGPARSER_NAME "positional argument name should not exceed 1: $arg_flag $1."
_is_positional=true
else
while (( $# > 0 )); do
[[ $1 = *=* ]] && break
_argparser_is_positional_argment "$1" && \
_argparser_error "$ARGPARSER_NAME" "$FUNCNAME: positional argument shouldn't mix in optional argument."
[[ ! $1 =~ $_pattern ]] && \
_argparser_error "$ARGPARSER_NAME" "$FUNCNAME: argument string should only contain [-_0-9a-zA-Z]: $1."
arg_flag="$arg_flag|$1"
shift
done
fi
Argparser_argument_flag[${#Argparser_argument_flag[@]}]=$arg_flag
# fetch other option data
local const=$ARGPARSER_UN_DEFINE
local default=$ARGPARSER_UN_DEFINE
local nargs=$ARGPARSER_UN_DEFINE
local metavar=$ARGPARSER_UN_DEFINE
local dest=''
local desc=''
local action=''
local choices=''
local required=false
local check=argparser_check
while (($# > 0)); do
case $1 in
const=*) const=${1#*=}
;;
default=*) default=${1#*=}
;;
nargs=*) nargs=${1#*=}
;;
metavar=*) metavar=${1#*=}
;;
dest=*) dest=${1#*=}
;;
desc=*) desc=${1#*=}
;;
action=*) action=${1#*=}
;;
choices=*) choices=${1#*=}
;;
required=*) required=${1#*=}
;;
check=*) check=${1#*=}
;;
*) _argparser_error $ARGPARSER_NAME "$FUNCNAME: unrecognized argument: $1"
;;
esac
shift
done
# dest must be an valid variable name
_pattern='^[_a-zA-Z][_0-9a-zA-Z]*$'
if [[ $dest != '' && ! $dest =~ $_pattern ]]; then
_argparser_error $FUNCNAME "$arg_flag: dest must be a valid variable name: $dest."
fi
# action must be callable
if [[ $action != '' ]] && ! _argparser_is_callback "$action"; then
_argparser_error $FUNCNAME "$arg_flag: action must be callable: $action."
fi
# check must be callable
if ! _argparser_is_callback "$check"; then
_argparser_error $FUNCNAME "$arg_flag: check must be callable: $check."
fi
# required: 1.positional argument not support required; 2.only true or false to choose
if [[ $required = true ]]; then
[[ $_is_positional = true ]] && \
_argparser_error $FUNCNAME "positional argument $arg_flag do not support required option."
elif [[ $required = false ]]; then
: # do nothing
else
_argparser_error $FUNCNAME "$arg_flag: required only could be true or false."
fi
# const: positional argument not support const
if [[ $const != $ARGPARSER_UN_DEFINE && $_is_positional = true ]]; then
_argparser_error $FUNCNAME "positional argument $arg_flag do not support const option."
fi
# check nargs and set nargs depending on const/default
# 1. nargs only support number, ?, *, +, remain these 5 types
if [[ $nargs = $ARGPARSER_UN_DEFINE ]]; then
if [[ $_is_positional = true ]]; then
# define nargs of positional argument
if [[ $default = $ARGPARSER_UN_DEFINE ]]; then
nargs=1
else
nargs='?'
fi
else
# define nargs of positional argument
if [[ $const = $ARGPARSER_UN_DEFINE ]]; then
nargs=1
else
nargs='?'
fi
fi
else
local zero_like_nargs_pattern='^(0|\?|\*|remain)$'
local non_zero_nargs_pattern='^([1-9][0-9]*|\+)$'
if [[ $nargs =~ $non_zero_nargs_pattern ]]; then
# non zero like nargs do not support const for optional and default for positional argument
if [[ $_is_positional = true ]]; then
[[ $default != $ARGPARSER_UN_DEFINE ]] &&\
_argparser_error $FUNCNAME "positional argument $arg_flag: when default supplied, nargs must be 0|?|*|remain."
else
[[ $const != $ARGPARSER_UN_DEFINE ]] &&\
_argparser_error $FUNCNAME "optional argument $arg_flag: when const supplied, nargs must be 0|?|*."
fi
elif [[ $nargs =~ $zero_like_nargs_pattern ]]; then
: # nothing
else
_argparser_error $FUNCNAME "$arg_flag: nargs must be in (?|*|+|remain|[number])."
fi
fi
Argparser_argument_dest[${#Argparser_argument_dest[@]}]=$dest
Argparser_argument_check[${#Argparser_argument_check[@]}]=$check
Argparser_argument_action[${#Argparser_argument_action[@]}]=$action
Argparser_argument_default[${#Argparser_argument_default[@]}]=$default
Argparser_argument_const[${#Argparser_argument_const[@]}]=$const
Argparser_argument_nargs[${#Argparser_argument_nargs[@]}]=$nargs
Argparser_argument_desc[${#Argparser_argument_desc[@]}]=$desc
Argparser_argument_metavar[${#Argparser_argument_metavar[@]}]=$metavar
Argparser_argument_required[${#Argparser_argument_required[@]}]=$required
Argparser_argument_choices[${#Argparser_argument_choices[@]}]=$choices
}
# parse the command line arguments and set the right value to dest...
# it will tear down all the non reserved functions and variables in __argparser_tear_down_attr__
# used like: argparser_parse "$@"
function argparser_parse()
{
_argparser_prepare_argparser_aguments
# find hyphen command-line args(sub args)
# use this type of ugly variable names for escaping local variable for _argparser_globals_register
local ___argparser_args_=()
while (($# > 0)); do
if [[ $1 = '--' ]]; then
shift
break
fi
___argparser_args_[${#___argparser_args_[@]}]=$1
shift
done
argparser_subargs=("$@")
set -- "${___argparser_args_[@]}"
# parsing arguments
while (($# > 0)); do
if _argparser_is_optional_argment "$1"; then
if _argparser_is_long_optional_argument "$1"; then
_argparser_parse_long_option "$@" && shift $__argparser_shift__num__
else
_argparser_parse_short_option "$@" && shift $__argparser_shift__num__
fi
else
_argparser_parse_positional_arg "$@" && shift $__argparser_shift__num__
fi
done
# final check unparsed args and dump all the dest
_argparser_final_check_argparser_aguments
_argparser_globals_register dump
__tear_down__
}
# reserve argparser usage to avoid __tear_down__
function argparser_reserve_usage()
{
printf "%s" "$(_argparser_usage)"
}
# check API
# fake check, always return true
# - $1...: values of the argparser argument gotten
function argparser_check() { :; }
# action API
# action_callback dest option_string option_strings - - value
# store|help|?version?
# argparser action
# - $1: dest
# - $2: command-line argument string
# - $3: argparser argument string
# - $4: reserved
# - $5: reserved
# - $6: reserved
# - $7...: values
function argparser_store()
{
local dest=$1
shift 6
_argparser_globals_register register "$dest" "$@"
}
# format help string, print it and exit
function argparser_help()
{
local help=''
if [[ $Argparser_help = $ARGPARSER_UN_DEFINE ]]; then
local prologue=$Argparser_prologue
local usage=$(_argparser_usage)
local app_desc=$Argparser_desc
local args_help=$(_argparser_format_arg_help)
local epilog=$Argparser_epilog
if [[ $prologue != '' ]]; then
prologue+=$'\n'$'\n'
fi
if [[ $usage != '' ]]; then
usage+=$'\n'
fi
if [[ $app_desc != '' ]]; then
app_desc+=$'\n'
fi
if [[ $args_help != '' ]]; then
args_help=$'\n'$args_help$'\n'
fi
if [[ $epilog != '' ]]; then
epilog=$'\n'$epilog
fi
help=$prologue$usage$app_desc$args_help$epilog
else
help=$Argparser_help
fi
help=$(_argparser_translate "$help" prog "$Argparser_prog_name")
echo -e "$help"
exit
}
# check whether $1 is callable
function _argparser_is_callback()
{
hash "$1" 1>/dev/null 2>&1
}
function _argparser_is_optional_argment()
{
((${#1} > 1)) && [[ ${1:0:1} = ["$Argparser_prefix_chars"] ]]
}
function _argparser_is_positional_argment()
{
[[ ${1:0:1} != ["$Argparser_prefix_chars"] ]]
}
function _argparser_is_long_optional_argument()
{
((${#1} > 2)) && \
[[ ${1:0:1} = ["$Argparser_prefix_chars"] ]] &&\
[[ ${1:1:1} = ["$Argparser_prefix_chars"] ]]
}
# initial work befor argparser_parse
# set all arguments status to NO_PARSE
function _argparser_prepare_argparser_aguments()
{
local key argument_strings
for ((key=0; key < ${#Argparser_argument_flag[@]}; key++)); do
# set all arguments status to NO_PARSE
argument_strings=${Argparser_argument_flag[$key]}
if _argparser_is_positional_argment "$argument_strings"; then
_Argparser_argument_status[$key]=$ARGPARSER_PA_NO_PARSE
else
_Argparser_argument_status[$key]=$ARGPARSER_OA_NO_PARSE
fi
done
}
# works after parsing the arguments
# 1. set the default value if supplied
# 2. check whether optional arguments are required
function _argparser_final_check_argparser_aguments()
{
local key status default is_required nargs argument_strings
for ((key=0; key < ${#_Argparser_argument_status[@]}; key++)); do
status=${_Argparser_argument_status[$key]}
is_required=${Argparser_argument_required[$key]}
default=${Argparser_argument_default[$key]}
argument_strings=${Argparser_argument_flag[$key]}
if [[ $status = $ARGPARSER_OA_NO_PARSE ]]; then # optional argument
if [[ $is_required = false ]]; then
_argparser_set_default2dest "$key" "$ARGPARSER_OA_PARSED"
else
local short_option=$(_argparser_choose_shortest_optional_string "$argument_strings")
_argparser_error "$Argparser_prog_name" "argument $short_option is required."
fi
elif [[ $status = $ARGPARSER_PA_NO_PARSE ]]; then
nargs=${Argparser_argument_nargs[$key]}
if [[ $nargs = ['?*'] ]] || [[ $nargs = remain ]]; then
_argparser_set_default2dest "$key" "$ARGPARSER_PA_PARSED"
else
local metavar=$(_argparser_choose_metavar \
"${Argparser_argument_metavar[$key]}" \
"${Argparser_argument_dest[$key]}" \
"$argument_strings")
_argparser_usage >&2
_argparser_error "$Argparser_prog_name" "argument $metavar is missing."
fi
fi
done
}
# parse long optional arguments
# this function get the right number values from command-line arguments,
# according to nargs
# and assign value to ___value__, assign shift num to __argparser_shift__num__
# - $1: must be long optional arguments
# - $2...: the unshift command-line arguments
# used by argparser_parse
function _argparser_parse_long_option()
{
_argparser_reset_values_and_shift_num
local shift_num=0
local option_string=$1
shift
((shift_num++))
local sticking_value=$ARGPARSER_UN_DEFINE
if [[ $option_string = *=* ]]; then
sticking_value=${option_string#*=}
option_string=${option_string%%=*}
fi
local key=$(_argparser_get_argparser_optional_arg_key "$option_string" $ARGPARSER_OA_NO_PARSE)
if [[ $key = '' ]]; then
_argparser_error $Argparser_prog_name "unrecognized argument: $option_string"
fi
local nargs="${Argparser_argument_nargs[$key]}"
if [[ $sticking_value = $ARGPARSER_UN_DEFINE ]]; then
_argparser_get_cl_arg_values "$nargs" "$@"
((shift_num+=$__argparser_shift__num__))
else
if [[ $nargs = 0 ]]; then
_argparser_error $Argparser_prog_name "argument $option_string not need values: $option_string=$sticking_value"
fi
_argparser_get_cl_arg_values "$nargs" "$sticking_value" "$@"
(( shift_num+=($__argparser_shift__num__ - 1) ))
fi
# set the values to $@
set -- "${__argparser_values__[@]}"
# whether values count matches nargs
_argparser_set_value2dest $key "$option_string" "$@"
__argparser_shift__num__=$shift_num
}
# parse short optional argument
# this function get the right number values from command-line arguments,
# according to nargs
# and assign value to ___value__, assign shift num to __argparser_shift__num__
# - $1: must be short optional arguments
# - $2...: the unshift command-line arguments
# used by argparser_parse
function _argparser_parse_short_option()
{
_argparser_reset_values_and_shift_num
local shift_num=0
local command_line_1st_arg=$1
shift
((shift_num++))
local sticking_value=$ARGPARSER_UN_DEFINE
# parse short option like -abcValue
local key nargs arg_string dest _option_string _arg_residues
while ((${#command_line_1st_arg} > 2)); do
_option_string=${command_line_1st_arg:0:2}
_arg_residues=${command_line_1st_arg:2}
key=$(_argparser_get_argparser_optional_arg_key "$_option_string" $ARGPARSER_OA_NO_PARSE)
if [[ $key = '' ]]; then
_argparser_error $Argparser_prog_name "unrecognized argument: $_option_string"
fi
nargs=${Argparser_argument_nargs[$key]}
if [[ $nargs = 0 ]]; then
_argparser_set_value2dest $key "$_option_string"
# rebuilt command_line_1st_arg
command_line_1st_arg='-'$_arg_residues
else
command_line_1st_arg=$_option_string
sticking_value=$_arg_residues
break
fi
done
# parsing starts
local option_string=$command_line_1st_arg
key=$(_argparser_get_argparser_optional_arg_key "$option_string" $ARGPARSER_OA_NO_PARSE)
if [[ $key = '' ]]; then
_argparser_error $Argparser_prog_name "unrecognized argument: $option_string"
fi
nargs=${Argparser_argument_nargs[$key]}
if [[ $sticking_value = $ARGPARSER_UN_DEFINE ]]; then
_argparser_get_cl_arg_values "$nargs" "$@"
((shift_num+=$__argparser_shift__num__))
else
if [[ $nargs = 0 ]]; then
_argparser_error $Argparser_prog_name "$option_string not need values: $option_string=$sticking_value"
fi
_argparser_get_cl_arg_values "$nargs" "$sticking_value" "$@"
(( shift_num+=($__argparser_shift__num__ - 1) ))
fi
# set the values to $@
set -- "${__argparser_values__[@]}"
_argparser_set_value2dest $key "$option_string" "$@"
__argparser_shift__num__=$shift_num
}
# parse positional argument
# this function get the right number values from command-line arguments,
# according to nargs
# and assign values to ___value__, assign shift num to __argparser_shift__num__
# - $1: must be positional argument
# - $2...: the unshift command-line arguments
# used by argparser_parse
function _argparser_parse_positional_arg()
{
local shift_num=0
local key status
key=$(_argparser_get_argparser_positional_arg_key "$ARGPARSER_PA_NO_PARSE")
if [[ $key = '' ]]; then
_argparser_error $Argparser_prog_name "unrecognized argument: $1"
fi
local nargs=${Argparser_argument_nargs[$key]}
_argparser_get_cl_arg_values "$nargs" "$@"
(($__argparser_shift__num__ == 0)) && \
_argparser_error $ARGPARSER_NAME "$FUNCNAME: shift number can not be 0." 'internal fatal'
((shift_num+=$__argparser_shift__num__))
set -- "${__argparser_values__[@]}"
_argparser_set_value2dest $key - "$@"
__argparser_shift__num__=$shift_num
}
# check the value number matching the nargs
# - $1: nargs
# - $2: error identifer: command-line optional string for optional argument; metavar for positional argument
# - $3...: values
function _argparser_check_value_narg_matching()
{
local nargs=$1
local error_identifer=$2
local ignore_pattern='^\*|\?|remain$'
shift 2
local pattern='^[1-9][0-9]*|0$'
if [[ $nargs =~ $pattern ]]; then
if (($# < $nargs)); then
_argparser_usage >&2
_argparser_error $Argparser_prog_name "argument $error_identifer: expected $nargs arguments, but $# you supplied: $1... ."
elif (($# > $nargs)); then
_argparser_error $ARGPARSER_NAME "$FUNCNAME: argument $error_identifer nargs $nargs < $# value amount." internal
fi
elif [[ $nargs = '+' ]]; then # only used for optional argument
if (($# < 1)); then
_argparser_usage >&2
_argparser_error $Argparser_prog_name "argument $error_identifer expected at least 1 argument."
fi
elif [[ $nargs =~ $ignore_pattern ]]; then
: # do nothing
else
_argparser_error $ARGPARSER_NAME "$FUNCNAME: argument $error_identifer: invalid nargs: $nargs." internal
fi
}
# Assign values to the destination variable name of argument
# - $1: key
# - $2: -(positional)|command-line arg option string(optional)
# - $?...: values
function _argparser_set_value2dest()
{
local key=$1
local error_identifer=$2
shift 2
local nargs=${Argparser_argument_nargs[$key]}
local is_positional=false
local parsed_status=$ARGPARSER_OA_PARSED
if [[ $error_identifer = '-' ]]; then
is_positional=true
parsed_status=$ARGPARSER_PA_PARSED
error_identifer=$(_argparser_choose_metavar \
"${Argparser_argument_metavar[$key]}" \
"${Argparser_argument_dest[$key]}" \
"${Argparser_argument_flag[$key]}")
fi
_argparser_check_value_narg_matching "$nargs" "$error_identifer" "$@"
if (($# == 0)); then
if [[ $is_positional = false ]]; then
if [[ $nargs = remain ]]; then
_argparser_do_action set "$key" "$error_identifer"
_Argparser_argument_status[$key]=$parsed_status
return 0
fi
local const=${Argparser_argument_const[$key]}
if [[ $const = $ARGPARSER_UN_DEFINE ]]; then
_argparser_do_action no_set "$key" "$error_identifer"
else
_argparser_do_action set "$key" "$error_identifer" "$const"
fi
else
_argparser_error $ARGPARSER_NAME "$FUNCNAME: positional argument $error_identifer: value couldn't be empty." internal
fi
else
local v
# is in choices?
local choices="${Argparser_argument_choices[$key]}"
if [[ $choices != '' ]]; then
local pattern='^('$choices')$'
for v in "$@"; do
[[ $v =~ $pattern ]] || \
_argparser_error $Argparser_prog_name "argument $error_identifer: $v not in [$choices]"
done
fi
# check values
local check="${Argparser_argument_check[$key]}"
$check "$@"
_argparser_do_action set "$key" "$error_identifer" "$@"
fi
# argument have been parsed
_Argparser_argument_status[$key]=$parsed_status
}
# final check; we set the default value to the destination variables
# - $1: key
# - $2: parsed status you want to change
function _argparser_set_default2dest()
{
local key=$1
local parsed_status=$2
local dest=$(_argparser_choose_dest "${Argparser_argument_dest[$key]}" "${Argparser_argument_flag[$key]}")
local default=${Argparser_argument_default[$key]}
if [[ $default != $ARGPARSER_UN_DEFINE ]]; then
_argparser_globals_register register "$dest" "$default"
fi
_Argparser_argument_status[$key]=$parsed_status
}
# get the command-line-arg matching argparser optional argument index(key)
# - $1: command line optional string
# - $2...: status from _Argparser_argument_status
function _argparser_get_argparser_optional_arg_key()
{
local cl_arg=$1
shift
local status=$*
if [[ $status = '' ]]; then
status=$ARGPARSER_OA_PARSED$ARGPARSER_OA_NO_PARSE
fi
local key _option_pattern
for ((key=0; key < ${#_Argparser_argument_status[@]}; key++)); do
if [[ ${_Argparser_argument_status[$key]} = [$status] ]]; then
_option_pattern='^('${Argparser_argument_flag[$key]}')$'
if [[ $cl_arg =~ $_option_pattern ]]; then
echo $key
return
fi
fi
done
}
# get the first argparser positional argument index
# - $1...: status from _Argparser_argument_status
function _argparser_get_argparser_positional_arg_key()
{
local status=$*
if [[ $status = '' ]]; then
status=$ARGPARSER_PA_PARSED$ARGPARSER_PA_NO_PARSE
fi
for ((key=0; key < ${#_Argparser_argument_status[@]}; key++)); do
if [[ ${_Argparser_argument_status[$key]} = [$status] ]]; then
echo $key
return
fi
done
}
# get values from command line arguments according to nargs
# - $1: nargs
# - $2...: command line args
# set to __argparser_values__
function _argparser_get_cl_arg_values()
{
_argparser_reset_values_and_shift_num
local values=()
local shift_num=0
local nargs=$1
shift
if [[ $nargs = '?' ]]; then
if _argparser_is_positional_argment "$1"; then
values=("$1")
shift_num=1
fi
elif [[ $nargs = ['*+'] ]]; then
_argparser_get_extending_values "$@" &&\
values=("${__argparser_values__[@]}")
shift_num=$__argparser_shift__num__
elif [[ $nargs = 'remain' ]]; then
values=("$@")
shift_num=$#
elif [[ $nargs > 0 ]]; then
local value_len=0
while (($# > 0)); do
if _argparser_is_positional_argment "$1"; then
values=("${values[@]}" "$1")
value_len=${#values[@]}
if [[ $value_len = "$nargs" ]]; then
break
fi
shift
else
break
fi
done
shift_num=$value_len
elif [[ $nargs = 0 ]]; then
: # do nothing
else
_argparser_error $ARGPARSER_NAME "$FUNCNAME: invalid nargs: $nargs." internal
fi
__argparser_values__=("${values[@]}")
__argparser_shift__num__=$shift_num
}
# reset the internal exchanging variable __argparser_values__ and __argparser_shift__num__
# for safty reason
function _argparser_reset_values_and_shift_num()
{
__argparser_values__=$ARGPARSER_UN_DEFINE
__argparser_shift__num__=0
}
# get values for the nargs=*|+ arguments
# this function have considerd how much arguments should left
# for the un_hitting registerd positional arguments on command-
# -line arguments. More to see the `_argparser_cl_arg_amount_need2reserved_now` function
# - $1...: command-line args
function _argparser_get_extending_values()
{
_argparser_reset_values_and_shift_num
# scaning
local has_extending_EOT=false
local are_all_args_positional=true
local shift_num=0
local values=()
# check if has_extending_EOT and are_all_args_positional
while (($# > 0)); do
if [[ $1 = "$Argparser_nargs_extending_EOT" ]]; then
has_extending_EOT=true
break
elif _argparser_is_optional_argment "$1"; then
are_all_args_positional=false
break
else
values[${#values[@]}]=$1
shift
fi
done
# get values
if [[ $has_extending_EOT = false && $are_all_args_positional = true ]]; then
local reserved_num=$(_argparser_cl_arg_amount_need2reserved_now)
local value_len=${#values[@]}
if (($value_len > $reserved_num > 0)); then
values=("${values[@]:0:$(($value_len - $reserved_num))}")
fi
fi
shift_num=${#values[@]}
if [[ $has_extending_EOT = true ]]; then
((shift_num++))
fi
__argparser_shift__num__=$shift_num
__argparser_values__=("${values[@]}")
}
# calculate how much argparser argument nargs(only number type nargs) needing to reserved
# used by _argparser_get_extending_values
function _argparser_cl_arg_amount_need2reserved_now()
{
local key nargs status
local reserved_num=0
local _pattern='^[0-9]+$'
for ((key=0; key < ${#_Argparser_argument_status[@]}; key++)); do
status=${_Argparser_argument_status[$key]}
nargs=${Argparser_argument_nargs[$key]}
if [[ $status = $ARGPARSER_PA_NO_PARSE ]] &&\
[[ $nargs =~ $_pattern ]]; then
((reserved_num+=$nargs))
fi
done
echo $reserved_num
}
function _argparser_format_arg_help()
{
local arg_flag key arg_desc arg_strings metavar dest _is_required
for key in ${!Argparser_argument_flag[@]}; do
arg_strings=${Argparser_argument_flag[$key]}
dest=${Argparser_argument_dest[$key]}
metavar=${Argparser_argument_metavar[$key]}
nargs=${Argparser_argument_nargs[$key]}
dest=$(_argparser_choose_dest "$dest" "$arg_strings")
metavar=$(_argparser_choose_metavar "$metavar" "$dest" "$arg_strings")
arg_flag=$(_argparser_format_argument_flag "$arg_strings" "$nargs" "$metavar")
if [[ ${Argparser_argument_required[$key]} != false ]]; then
_is_required='not required'
else
_is_required='required'
fi
# translate some user word
arg_desc=$(_argparser_translate "${Argparser_argument_desc[$key]}" \
prog "$Argparser_prog_name" \
default "${Argparser_argument_default[$key]}" \
choices "${Argparser_argument_choices[$key]}" \
const "${Argparser_argument_const[$key]}" \
dest "$dest" \
metavar "$metavar" \
nargs "$nargs" \
required "$_is_required")
printf "%-30s %-53s\n" "$arg_flag" "$arg_desc"
done
}
# format description message for every registerd arugments
# - $1: option_string
# - $2: nargs
# - $3: metavar
function _argparser_format_argument_flag()
{
local LEFT_FLAG=' ' # left 2 space in the flags left side.
local option_string=${1//'|'/ }
local nargs=$2
local metavar=$3
set -- $option_string
local last_one_option_str=${@:$#:1}
local option_flag
# add detail flag to the last one arg_string
if _argparser_is_positional_argment "$last_one_option_str"; then
echo "$LEFT_FLAG$metavar"
return
else
local pattern='^[1-9][0-9]*$'
local _metavar_string
if [[ $nargs =~ $pattern ]]; then
if (($nargs > 1)); then
_metavar_string="=$metavar ..."
else
_metavar_string="=$metavar"
fi
else
case $nargs in
'?') _metavar_string="=[$metavar]"
;;
'*') _metavar_string="=[$metavar ...]"
;;
'+') _metavar_string="=$metavar [...]"
;;
'remain') _metavar_string="=..."