-
Notifications
You must be signed in to change notification settings - Fork 0
/
args
executable file
·578 lines (513 loc) · 21.3 KB
/
args
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
#!/usr/bin/env bash
#
# ############################################################################
# Project: xSHELL (none)
# File...: args
# Created: Friday, 2022/02/11 - 20:09:07
# Author.: @fbnmtz, fgm ([email protected])
# ~·~·~·~·~·~·~·~·~·~·~·~·~~·~·~·~·~·~·~·~·~·~·~·~·~~·~·~·~·~·~~·~·~·~·~·~·~·~
# Last Modified: Monday, 2024/12/09 - 14:57:25
# Modified By..: @fbnmtz, ([email protected])
# ~·~·~·~·~·~·~·~·~·~·~·~·~~·~·~·~·~·~·~·~·~·~·~·~·~~·~·~·~·~·~~·~·~·~·~·~·~·~
# Version: 0.2.16.1369
# ~·~·~·~·~·~·~·~·~·~·~·~·~~·~·~·~·~·~·~·~·~·~·~·~·~~·~·~·~·~·~~·~·~·~·~·~·~·~
# Description:
# >
# ############################################################################
# HISTORY:
#
_xLIB_ARGS_=true;
use args.utils system hashs
# hash to save app params
Hash.new main_params
block=''
# update text used in function 'xusage'
# @param $1 -> string to customize each text of help sections. Use this pattern:
# -<option>="<text>"
# <options> identify a section and it can be:
# -h or --header
# -p or --param
# -b or --body
# -f or --footer
# "<text>" is the string associated to this section and is required to be inside ""
xhelp(){
# loop all params
for param in "$@"; do
# split key and value
key=$(echo $param | cut -d '=' -f1)
val=$(echo $param | cut -d '=' -f2)
# check key arg
case $key in
-p|--param )
param_id="$(echo $val | cut -d '+' -f1)";
param_text="$(echo $val | cut -d '+' -f2-3)";
Hash.put main_params "$param_id" "$param_text";;
-b|--body ) __HELP_BODY__+="$val" ;;
-h|--header ) __HELP_HEADER__+="\n$val\n" ;;
-f|--footer ) __HELP_FOOTER__+="$val" ;;
--long-usage) __HELP_SHOW_ARGS__=true ;;
esac
done
# set vars VERSION, _CREATED_AT_, _AUTHOR_
xversion
xcreated
xauthor
# get all keys in main_params hash (format: key:value)
# --> key pattern (shortkey,longkey): Ex: -k,--key
# --> sed remove second key;
# --> tr replace breaklines '\n' for a space ' ' .
# result: all shortkeys in one line
# __HELP_USAGE__="usage: \n $APP $(Hash.keys main_params | sed 's/,--.[a-z]*//g' | tr -s '\n' ' ')"
__HELP_USAGE__="usage: \n ${GREEN}$APP${RESET} "
if [ $(Hash.count main_params) -le 10 ] || [ -n "$__HELP_SHOW_ARGS__" ]; then
__HELP_USAGE__+="$(
Hash.keys main_params | \
sed 's/,--.[a-z,-]*//g' | \
sed 's/,.[a-z,-]*//g' | \
sed 's/^/[/g' | \
sed 's/$/]/g' | \
tr -s '\n' ' '
)"
if [ -n "$RED" ]; then
# apply colors
__HELP_USAGE__=${__HELP_USAGE__//-/${MAGENTA}-}
__HELP_USAGE__=${__HELP_USAGE__//</${YELLOW}<}
__HELP_USAGE__=${__HELP_USAGE__//\]/${RESET}\]}
# TODO: optional arguments highlighting
__HELP_USAGE__=${__HELP_USAGE__//'{'/${YELLOW}'{'}
fi
else
__HELP_USAGE__+="[OPTIONS] "
fi
}
xusage(){
# generate default help text if user not difined one
[ -z "$__HELP_USAGE__" ] && xhelp --long-usage
case "$1" in
-f|--field-error)
xhelp --long-usage
__exit_code=3
__usage_msg="${RED}Error!${RESET} empty value for ${YELLOW}'$2'${RESET} param.${RESET}\n\n"
;;
-m|--missing-param)
xhelp --long-usage
__exit_code=1
__usage_msg="${RED}Error!${RESET} Missing required param.${RESET}\n\n"
;;
-r|--reject-unknow)
xhelp --long-usage
__exit_code=2
__usage_msg="${RED}Error!${RESET} invalid option ${YELLOW}($2)${RESET}.${RESET}\n\n"
;;
-c|--custom)
xhelp --long-usage
__exit_code=4
__usage_msg="$2\n\n"
;;
-h|--help)
xhelp
# helpOptionsDarwin
__usage_full=true
;;
*)
__exit_code=0
__usage_msg=""
;;
esac
# prints initial help text
echo -e "${BLUE}${__HELP_HEADER__}${RESET}\n${__usage_msg}${__HELP_USAGE__}"
if [ -n "$__usage_full" ]; then
# help body text (before params/args)
[ -n "$__HELP_BODY__" ] && echo -e "\n${__HELP_BODY__}"
# [ -z "$block" ] && echo -e "Available options:" || echo -e "$block"
# get all key/values from main_params hash
# pairs stored as 'key:value'. We parse to ':key:value'
# --> sed to add ':' in begin of each line
# --> column to equaly expand texts
# Hash.all main_params | sed 's/^-/:-/g' | sed 's/,/,:/' | column -t -s ':'
# case sys.os in
case $(xsys.os) in
Darwin)
_HELP_OPTIONS_DESCRIPTION__="\n$(helpOptionsDarwin)\n"
;;
Linux)
__HELP_OPTIONS_DESCRIPTION__="$(helpOptionsLinux)"
;;
esac
# v1
# echo -e "$____HELP_OPTIONS_DESCRIPTION" | column -t -s ':' | sed 's/;/:/g'
# __HELP_OPTIONS_DESCRIPTION__=$(echo -e "${__HELP_OPTIONS_DESCRIPTION__//./ }" | \
# column -L -t -s ':' -o ' ' | \
# sed "s/;/:/g" | \
# sed 's/,/, /g' )
# v2
# __HELP_OPTIONS_DESCRIPTION__=$(echo -e "${__HELP_OPTIONS_DESCRIPTION__//./ }" | \
# column -t -s ':' | \
# sed "s/;/:/g" | \
# sed 's/,/, /g' )
# v3
__HELP_OPTIONS_DESCRIPTION__="\n$(helpOptionsDarwin)\n"
echo -e "${__HELP_OPTIONS_DESCRIPTION__}${RESET}"
# sed '/^#/ s/ \{1,\}/ /g' | \
# not null? prints footer
[ -n "$__HELP_FOOTER__" ] && echo -e "${__HELP_FOOTER__}\n"
echo -e "${GREEN}v${_CURRENT_VERSION_}${RESET} - writen by ${BOLD}${CYAN}${_AUTHOR_} ${YELLOW}${_CREATED_AT_}${RESET}"
else
echo -e ""
fi
# quit with error code
exit $__exit_code
}
# xarg: id="-h,--help" var=variable:value
# --> dynamic create ARGs/actions
# @param $1: ARGs keys. Use comma (,) to separete multiple keys to same action
# --> id="-h,--help"
# @param $2: action to execute with keys
# this can be: [code] or [var]
# --> code="cmd1; cmd2;"
# run custom commands (cmd1 ; cmd2)
# --> var=myVar1:value
# create a var named 'myVar1' and assign 'value'
# * var=myVar1+r
# create a var 'myVar1' and require another param as value. If next arg was empyt raise a error.
# @param $3: description to generate help for this arg/action
# --> desc="text"
xarg(){
#TODO: refactor code below
while [ "$1" != "" ]; do
case $1 in
# planning a new feature
# --value)
# # echo ''
# method=value
# value=$2
# ;;
-i| --id)
key=$1; shift
option_key=$(echo "$1" | tr -s ',' '|')
option_default=$1
description=''
;;
# TODO: implements joint shortflags (ex: -lsa)
-v|--var)
key=$1; shift
method=var
action_vars=''
option_rule=""
desc_var=""
# $1 content -> can be a list of values comma separated
# value,value
for v in ${1//,/ }; do
# method used in this arg
option_content=$v
var_name="$(echo "$option_content" | cut -d ':' -f1 | cut -d '+' -f1 )"
case "$option_content" in
*:* )
# ":" will directly set value to variable
# variable:value
var_value="$(echo "$option_content" | cut -d ':' -f2 | cut -d '+' -f1)"
assign_vars=" $var_name=\"$var_value\" "
# clear rules
option_rule=""
var_value=''
;;
*+* )
# "+" will require a new arg in command line. this value will be set to variable
# variable+r
current_rule="$(echo "$option_content" | cut -d '+' -f2)"
case "$current_rule" in
# 'r' means 'required'
r)
option_rule+=" shift; xflag_require_value \"\$1\" \"$var_name\" ;"
desc_var+=" <$var_name>"
if [ -z "$var_value" ]; then
assign_vars=" $var_name=\"\$1\" "
fi
;;
# 'o' for 'optional'
o)
option_rule+=" "
desc_var+=" {$var_name}"
if [ -z "$var_value" ]; then
assign_vars=" [ -n \"\$2\" ] && { shift ; $var_name=\"\$1\" ; } "
fi
;;
esac
;;
esac
[ -n "$action_vars" ] && action_vars+=" ; "
action_vars+=" $option_rule $assign_vars "
# fix priblem when require two vars
# ex --var v1+r,v2+r
option_rule=''
done
;;
-c|--code)
key=$1; shift
method=code
option_content=$1
desc_var=''
;;
-d|--desc)
key=$1; shift
description="$*"
;;
-b|--block|-g|--group|-s|--section)
method=block
block="$2"
;;
-n|--longflag-nodash)
method=longflags
_xARGS_NO_DAHS=true
;;
-h|--header)
method=header
xflag_require_value "$1" "$2"
xhelp --header="$2"
;;
-f|--footer)
method=footer
xflag_require_value "$1" "$2"
xhelp --footer="$2"
;;
esac
shift
done
# bypass when no arguments has been defined
if [ "$method" != "block" ] && [ "$method" != "longflags" ] && [ "$method" != "footer" ] && [ "$method" != "header" ]; then
xhelp --param="${option_default}${desc_var}+${description}+${block}"
fi
# generate output
case $method in
var ) __runARGS_case_options+=" $option_key) $action_vars ;; \n" ;;
code) __runARGS_case_options+=" $option_key) $option_content ;; \n" ;;
# --reject-unknow) __runARGS_case_options+="*) xusage -r \$1 ;; \n" ;;
esac
}
# xrun "$@"
# generates a loop with case struct to evaluate all ARGs defined using `xarg`
xrun(){
xrunHelp(){
echo -e "${GREEN}${UNDERLINE}'lib/args'${RESET} main functions (${YELLOW}xarg${RESET}, ${YELLOW}xrun${RESET})
\n${YELLOW}1) xarg${RESET} -> set args to be validate in 'xrun' function
\nusage: ${YELLOW}xarg ${CYAN}[OPTION] ${MAGENTA}<VALUE>${RESET}\
\n\nAvailable options:\
"
echo -e "\
\n${CYAN} -i, --id ${MAGENTA} <VALUE>${RESET}; short and long key. ex: '-h,--help'\
\n${CYAN} -c, --code ${MAGENTA} <VALUE>${RESET}; shell code to run by 'eval'\
\n${CYAN} -v, --var ${MAGENTA} <VALUE>${RESET}; define vars\
\n${CYAN} -d, --desc ${MAGENTA} <TEXT> ${RESET}; description to this 'arg'\
\n
\n # Grouping options #
\n${CYAN} -b, --block ${MAGENTA}<VALUE>${RESET} or\
\n${CYAN} -g, --group ${MAGENTA}<VALUE>${RESET} or\
\n${CYAN} -s, --section ${MAGENTA}<VALUE>${RESET} or\
\
" | column -t -s ';'
echo -e "\
\nExamples:\
\n ${YELLOW}xarg ${CYAN}--id -h,--help ${MAGENTA}--code 'xusage --help' ${CYAN}--desc ${MAGENTA}'run function \"xusage\"'${RESET}\
\n ${YELLOW}xarg ${CYAN}--id -v,--var ${MAGENTA}--var var:value,url+r ${CYAN}--desc ${MAGENTA}'equivalent to \"var=value; read url\"'${RESET}\
\n ${YELLOW}xarg ${CYAN}--block ${MAGENTA}'new block'${RESET}\
\n${YELLOW}2) xrun${RESET} -> create 'case struct/validate args' defined via 'function xarg' for your application\
\n\nusage: ${YELLOW}xrun ${CYAN}[OPTIONS] ${MAGENTA}\"\$@\"${RESET}\
\n\nAvailable options:\
"
echo -e "
\n ${CYAN}--xrequire-one${RESET};script will require at least one argument\
\n ${CYAN}--xreject-unknow${RESET};raise an error if your script receives args not defined\
\n ${CYAN}--xversionrc${RESET};use full version with rc (release candidate)
\n ${CYAN}--xcolors${RESET};enable color support\
\n ${CYAN}--xdebug${RESET};prints generated case with args for inspection\
\n ${CYAN}--xhelp${RESET};prints this message
" | column -t -s ';'
# echo -e "\n[!] ATENTION:\
# \n 1-You can't use 'xrun' arguments in your application.\
# \n 2-You must pass all of your app/script args to 'xrun' validate then.\
# \n\tex: xrun --xrequire-one \"\$@\"\
# \n 3-xrun args will be removed via shift; so they need to be before incoming args (\"\$@\")\
# "
exit 0
}
generateCase(){
# fill case with options (xarg)
__runARGS_case_='case $1 in \n'
__runARGS_case_+=$__runARGS_case_options
__runARGS_case_+='esac'
# apply escape codes (\n \t) when print
__runARGS_case_=$(echo -e $__runARGS_case_)
[ -n "$_ARGS_DEBUG" ] && echo -e "#${RED} show debug information${RESET}:\n\n$__runARGS_case_\n" ;
[ -n "$_ARGS_REQUIRED" ] && xrequire_one "$1" && unset _ARGS_REQUIRED;
# loop all params
while [ "$1" != "" ]; do
# run generated 'case' code
eval "$__runARGS_case_"
shift
done
}
# set default grouping (has more than zero entries with groups? user defined)
if [ "$(Hash.all | grep -Ei '\+[a-z]' | wc -l)" -gt 0 ]; then
# create this group for --help and --version options
xarg --block "Information Options"
else
# no user group? use this for all options
xarg --block "Available Options"
fi
# set default args for any script
_CURRENT_VERSION_=$_VERSION_
# add support to logflags without '--' prefix
if [ -z "$_xARGS_NO_DAHS" ]; then
_arg_prefix_="--"
fi
# gen default help argument
xarg --id "-h,${_arg_prefix_}help" \
--code "xusage --help" \
--desc "show this help"
# --code "formatHelpOptions" \
# gen default version argument
xarg --id "-v,${_arg_prefix_}version" \
--code "echo \"\$_CURRENT_VERSION_\"; exit" \
--desc "print version and exit"
# store arguments/params to be passed to the script
_PARAMS_=()
# search for xrun args
while [ "$1" != "" ]; do
case "$1" in
# function to force script to receive at last one param/arg
--xrequire-one | --xrequire_one | --require-one | --notNull)
shift; _ARGS_REQUIRED=true
;;
--xreject-unknow | --reject-unknow)
shift
__runARGS_case_options+="*) xusage --reject-unknow \$1 ;; \n"
;;
--xdebug)
shift; _ARGS_DEBUG=true;
;;
--xversion-full | --xversionrc)
shift; _CURRENT_VERSION_=$_VERSIONRC_
;;
--xcolors)
shift; use colors;
;;
--xhelp)
use utils
local _help_viewer=$(getPath bat less more cat)
shift; xrunHelp | $_help_viewer
;;
--xlib-dirs)
shift;
[ -z "$RED" ] && use colors
echo -e "\n${YELLOW}xSHELL LIB directories:${RESET}\n"
for dir in "${xSHELL_DIRS[@]}"; do
echo -e "${GREEN} \`-> '${dir}${RESET})"
done
echo
exit
;;
*)
_PARAMS_+=("$1")
shift
esac
done
# Function to handle joint short flags
handleJointShortFlags() {
local joint_flags="$1" # The joint short flags passed as an argument
local length=${#joint_flags} # The length of the joint short flags string
# Iterate over each character in the joint short flags string
for (( i=0; i<length; i++ )); do
local flag="${joint_flags:i:1}" # Extract the current character (flag)
_PARAMS_+=("-$flag") # Add the individual flag to the _PARAMS_ array
done
}
# Check for joint short flags and expand them
for arg in "${_PARAMS_[@]}"; do
# Check if the argument is a joint short flag (e.g., -abc)
if [[ "$arg" =~ ^-[a-zA-Z]{2,}$ ]]; then
handleJointShortFlags "${arg:1}" # Call the function to handle the joint short flags
unset _PARAMS_[$arg] # Remove the joint short flag from the _PARAMS_ array
fi
done
generateCase "${_PARAMS_[@]}"
}
# check if one flag is set and require a value for it
# @param $1 -> flag to be checked (cant be null)
# @param $2 -> field name to throw an error when flag is not set
xflag_require_value(){
# $1 is empty? call xusage with field name to get a error msg
test -z "$1" && { xusage --field-error "$2"; }
# || { true; } #echo "1"; -r}
}
# function to force script to receive at last one param/arg
xrequire_one(){
test -z "$1" && xusage --missing-param;
}
# Function to format help options with standard spacing on Darwin systems
helpOptionsDarwin() {
local max_length=0
local options=()
# Find the maximum length of the options
while IFS= read -r line; do
# Extract the option key (first word) from the line
local option=$(echo "$line" | cut -d ':' -f 1)
# Determine the length of the option key
local length=${#option}
# Update the maximum length if the current option key is longer
if [ $length -gt $max_length ]; then
max_length=$length
fi
# Add the entire line to the options array
options+=("$line")
done <<< "$(Hash.all main_params)"
# Format the options with standard spacing
for option in "${options[@]}"; do
# Extract the option key (first word) from the option
local key=$(echo "$option" | cut -d ':' -f 1)
key=${key/\:/ }
# Extract the description (remaining words) from the option
local desc=$(echo "$option" | cut -d ':' -f 2-)
desc=$(echo "$desc" | cut -d '+' -f1)
# Print the option key and description with standard spacing
printf " %-${max_length}s %s\n" "$key" "$desc"
done
}
# Function to format help options with standard spacing on Linux systems
helpOptionsLinux(){
for h in $(
Hash.all main_params | # get all hashes \
sed "s/:/:/g" | # add blue color to options description':'\
sed "s/^-/:-/g" | # add color to options/flags \
sed 's/ /./g' # replace ' ' with '.'
); do
b=$(echo -e $h | cut -d '+' -f2)
# echo "'$b' - '$block'"
if [ -n "${b// }" ]; then
[ "${b}" != "${block// /.}" ] && block="${b}" \
&& __HELP_OPTIONS_DESCRIPTION__+="\n${BLUE}->:$block;${RESET}\n"
# echo
else
if [ -z "$outblock" ];then
block="Available.Options" && __HELP_OPTIONS_DESCRIPTION__+="\n${BLUE}->:$block;${RESET}\n"
outblock=true
fi
# [ -z "$block" ] && block="Available options" && __HELP_OPTIONS_DESCRIPTION__+="\n->:$block;\n"
fi
__HELP_OPTIONS_DESCRIPTION__+="$(echo -e ${h//./ } | cut -d '+' -f1)\n"
# apply colors
if [ -n "$RED" ]; then
# arguments description highlighting
__HELP_OPTIONS_DESCRIPTION__=${__HELP_OPTIONS_DESCRIPTION__//\:/${BLUE}\:}
# flags highlighting
__HELP_OPTIONS_DESCRIPTION__=${__HELP_OPTIONS_DESCRIPTION__//-/${MAGENTA}-}
# block highlighting
__HELP_OPTIONS_DESCRIPTION__=${__HELP_OPTIONS_DESCRIPTION__//->/${BLUE}->}
# required arguments highlighting
__HELP_OPTIONS_DESCRIPTION__=${__HELP_OPTIONS_DESCRIPTION__//</${YELLOW}<}
# required arguments closing
__HELP_OPTIONS_DESCRIPTION__=${__HELP_OPTIONS_DESCRIPTION__//>/>${BLUE}}
# TODO: optional arguments highlighting
__HELP_OPTIONS_DESCRIPTION__=${__HELP_OPTIONS_DESCRIPTION__//"{"/"${YELLOW}{"}
fi
done
}