-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathxsh.sh
2462 lines (2200 loc) · 72 KB
/
xsh.sh
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
# shellcheck disable=SC2148
# shellcheck disable=SC2317
#? Description:
#? xsh is an extension of Bash. It works as a Bash library framework.
#?
#? Usage:
#? xsh <LPUE> [UTIL_OPTIONS]
#?
#? Options:
#? <LPUE> Call an individual utility.
#? [UTIL_OPTIONS] Will be passed to utility.
#?
#? The library of the utility must be loaded first.
#?
#? Builtin:
#? All xsh builtin functions are available without the prefix: `__xsh_`.
#? For example, the builtin function `__xsh_lib_dev_manager` can be called as
#? the syntax: `xsh lib_dev_manager` or `xsh lib-dev-manager`.
#?
#? If there's naming conflict between the builtin functions and the library
#? utilities, The builtin functions take precedence over the library utilities.
#?
#? Convention:
#? LPUE LPUE stands for `Lib/Package/Util Expression`.
#? The LPUE syntax is: `[LIB][/PACKAGE]/UTIL`.
#? An LPUE is also an special LPUR.
#?
#? Example:
#?
#? <lib>/<pkg>/<util>, /<pkg>/<util>
#? <lib>/<util>, /<util>
#?
#? LPUR LPUR stands for `Lib/Package/Util Regex`.
#? The LPUR syntax is: `[LIB][/PACKAGE][/UTIL]`.
#?
#? Example:
#?
#? '*'
#? /, <lib>
#? <lib>/<pkg>, /<pkg>
#? <lib>/<pkg>/<util>, /<pkg>/<util>
#? <lib>/<util>, /<util>
#?
#? Debug Mode:
#? With the debug mode enabled, the shell options: `-vx` is set for the
#? debugging utilities.
#? The debug mode is available only for the commands started with `xsh`.
#?
#? Enable the debug mode by setting an environment variable: `XSH_DEBUG` before
#? the command `xsh`.
#?
#? Values for XSH_DEBUG:
#? 1 : Enable the debug mode for whatever the LPUE input by `xsh`.
#? e.g: XSH_DEBUG=1 xsh /string/upper foo
#?
#? <LPUR>: Enabled the debug mode for the LPUE input by `xsh` if the
#? LPUE equals to or matches the <LPUR> set by XSH_DEBUG.
#? e.g: XSH_DEBUG=/string xsh /string/upper foo
#? e.g: XSH_DEBUG=/string/pipe/upper xsh /string/upper foo
#?
#? The debug mode applies to the following commands and internal functions:
#? * calls
#? * call, exec
#?
#? The debug mode is for debugging xsh libraries.
#? For the general debugging purpose, use `xsh debug`, see `xsh help debug`.
#?
#? Dev Mode:
#? The dev mode is for developers to develop xsh libraries.
#? With the dev mode enabled, the utilities from the development library will
#? be used rather than those from the normal library.
#? The dev mode is available only for the commands started with `xsh`.
#?
#? Before using the dev mode, you need to create symbol links for the
#? libraries that need to use dev mode, put the symbol links in the directory
#? `~/.xsh/lib-dev`, and point them to your development workspaces.
#? This can be done with the command: `xsh lib-dev-manager link ...`, and be
#? undone with the command `xsh lib-dev-manager unlink ...`.
#?
#? Then the dev mode is ready to use.
#? Enable the dev mode by setting an environment variable: `XSH_DEV` before the
#? command `xsh`.
#?
#? Values for XSH_DEV:
#? 1 : Enable the dev mode for whatever the LPUE or LPUR input by `xsh`.
#? e.g: XSH_DEV=1 xsh /string/upper foo
#? XSH_DEV=1 xsh import /string
#? XSH_DEV=1 xsh list
#?
#? <LPUR>: Enabled the dev mode for the LPUE or LPUR input by `xsh` if the
#? LPUE/LPUR equals to or matches the <LPUR> set by XSH_DEV.
#? e.g: XSH_DEV=/string xsh import /string
#? e.g: XSH_DEV=/string xsh help /string/upper
#? e.g: XSH_DEV=/string/pipe/upper xsh /string/upper foo
#? Be noted, the following usage won't work as expected:
#? e.g: XSH_DEV=/string xsh import /
#?
#? The dev mode applies to the following commands and internal functions:
#? * calls, imports, unimports, list, help
#? * call, import, unimport, lib_list, help_lib
#?
function xsh () {
#? Special Variables:
#?
#? +----------------+--------+------------+------------------------+---------------------+-------------+
#? | Variables | Scope | Predefined | Predefined Where | Predefined Value | Overridable |
#? +================+========+============+========================+=====================+=============+
#? | XSH_DEBUG | Global | N | - | - | Y |
#? +----------------+--------+------------+------------------------+---------------------+-------------+
#? | XSH_DEV | Global | N | - | - | Y |
#? +----------------+--------+------------+------------------------+---------------------+-------------+
#? | XSH_HOME | Global | Y | ~/.xshrc | ~/.xsh | Y |
#? +----------------+--------+------------+------------------------+---------------------+-------------+
#? | XSH_DEV_HOME | Global | Y | ~/.xshrc | ${XSH_HOME}/lib-dev | Y |
#? +----------------+--------+------------+------------------------+---------------------+-------------+
#? | XSH_LIB_HOME | xsh | Y | ${XSH_HOME}/xsh/xsh.sh | ${XSH_HOME}/lib | Y |
#? +----------------+--------+------------+------------------------+---------------------+-------------+
#? | XSH_REPO_HOME | xsh | Y | ${XSH_HOME}/xsh/xsh.sh | ${XSH_HOME}/repo | Y |
#? +----------------+--------+------------+------------------------+---------------------+-------------+
#? | XSH_GIT_SERVER | xsh | Y | ${XSH_HOME}/xsh/xsh.sh | https://github.com | Y |
#? +----------------+--------+------------+------------------------+---------------------+-------------+
#?
#? The text table is powered by: https://www.tablesgenerator.com/text_tables
#?
#? Description:
#? Get the mime type of a file.
#? A wrapper of `file -b --mime-type`, with enhancements:
#? * Only output the first line of the result.
#? e.g: file /bin/ls (version file-5.39)
#? * If the file does not exist, cannot be read, then send output to stderr.
#?
#? Usage:
#? __xsh_mime_type <FILE> [...]
#?
#? Options:
#? <FILE> Path to the file.
#?
#? Example:
#? $ __xsh_mime_type /dev/null /bin/ls ~
#? inode/chardevice
#? application/x-mach-binary
#? inode/directory
#?
function __xsh_mime_type () {
declare mime_type f fd
for f in "$@"; do
fd=1 # set default fd to stdout
mime_type=$(/usr/bin/file -b --mime-type "${f}")
# get the first line
mime_type=${mime_type%%$'\n'*}
if [[ ${mime_type} =~ 'No such file or directory' ]]; then
# set fd to stderr
fd=2
fi
printf '%s\n' "${mime_type}" >&${fd}
done
}
#? Description:
#? Output the current state of given shell options.
#? Any options setter `[+-]` before the option is ignored.
#?
#? Usage:
#? __xsh_shell_option [OPTION][ ][...]
#?
#? Options:
#? [OPTION] The syntax is `[+-]NAME`.
#? See the allowed names in `help set`.
#?
#? Example:
#? $ __xsh_shell_option himBH +v -x
#? -himBH +vx
#?
function __xsh_shell_option () {
# set IFS in local
declare IFS=$''
# squash all the arguments without whitespaces, `+`, and `-`
declare testing="${*//[ +-]}"
# remove all the shell options that are not in the testing list from the turned on shell options `$-`
# and prefix the `-`
declare on="-${-//[^${testing:-.}]}"
# remove all the shell options that are turned on from the testing list
# and prefix the `+`
declare off="+${testing//[$-]}"
# remove the `+` and `-` if there's no any shell option
# do not double quote the variables
# shellcheck disable=SC2086
echo ${on%-} ${off%+}
}
#? Description:
#? Call a function or a script with specific shell options.
#? The shell options will be restored afterwards.
#?
#? Usage:
#? __xsh_call_with_shell_option [-1 OPTION] [-0 OPTION] [...] <FUNCTION | SCRIPT>
#?
#? Options:
#? [-1 OPTION] Turn on followed options.
#? [-0 OPTION] Turn off followed options.
#?
#? OPTION The same with shell options.
#? See `help set`.
#?
#? Example:
#? $ __xsh_call_with_shell_option -1 vx echo $HOME
#?
function __xsh_call_with_shell_option () {
declare -a options
declare OPTIND OPTARG opt
while getopts 1:0: opt; do
case ${opt} in
1)
options+=(-"${OPTARG}")
;;
0)
options+=(+"${OPTARG}")
;;
*)
return 255
;;
esac
done
shift $((OPTIND - 1))
declare mime_type ret=0
mime_type=$(__xsh_mime_type "$(command -v "$1")" 2>/dev/null)
if [[ $(type -t "$1" || :) == file && ${mime_type%%/*} == text ]]; then
# call script with shell options enabled
bash "${options[@]}" "$(command -v "$1")" "${@:2}"
ret=$?
else
# save former state of options
declare exopts
exopts=$(__xsh_shell_option "${options[@]}")
# enable shell options
set "${options[@]}"
# call function
"$@"
ret=$?
# restore state of shell options
# shellcheck disable=SC2086
set ${exopts} # do not double quote the parameter
fi
return ${ret}
}
#? Description:
#? Enable debug mode for the called function or script.
#?
#? Usage:
#? __xsh_debug [-1 OPTION] [-0 OPTION] [...] <FUNCTION | SCRIPT>
#?
#? Options:
#? [-1 OPTION] Turn on the followed options.
#? [-0 OPTION] Turn off the followed options.
#?
#? OPTION The same with shell options.
#? See `help set`.
#?
#? If no option given, `-1 x` is set as default.
#?
#? Example:
#? $ __xsh_debug foo_func
#? $ __xsh_debug bar_script.sh
#?
function __xsh_debug () {
if [[ ${1:0:1} != - ]]; then
# prepend `-1 x` to $@
set -- -1 x "$@"
fi
__xsh_call_with_shell_option "$@"
}
#? Description:
#? Count the number of given function name in ${FUNCNAME[@]}
#?
#? Usage:
#? __xsh_count_in_funcstack <FUNCNAME>
#?
function __xsh_count_in_funcstack () {
printf '%s\n' "${FUNCNAME[@]}" \
| grep -c "^${1}$"
}
#? Description:
#? Fire the command on the RETURN signal of function `xsh`.
#? The trapped command is cleared after it's fired once.
#?
#? Usage:
#? __xsh_trap_return [COMMAND]
#?
function __xsh_trap_return () {
declare command="
if [[ \${FUNCNAME} == xsh ]]; then
trap - RETURN
${1:?}
fi;"
# shellcheck disable=SC2064
trap "${command}" RETURN
}
#? Description:
#? Log message to stdout/stderr.
#?
#? Usage:
#? __xsh_log [debug|info|warning|error|fail|fatal] <MESSAGE>
#?
function __xsh_log () {
declare level
level=$(echo "$1" | tr "[:lower:]" "[:upper:]")
declare caller
if [[ ${FUNCNAME[1]} == xsh && ${#FUNCNAME[@]} -gt 2 ]]; then
caller=${FUNCNAME[2]}
else
caller=${FUNCNAME[1]}
fi
case ${level} in
WARNING|ERROR|FAIL|FATAL)
printf "${caller}: ${level}: %s\n" "${*:2}" >&2
;;
DEBUG|INFO)
printf "${caller}: ${level}: %s\n" "${*:2}"
;;
*)
printf "${caller}: %s\n" "$*"
;;
esac
}
#? Description:
#? Compare two versions.
#? The version format is like `X.Y.Z`.
#?
#? Usage:
#? __xsh_version_comparator <VER1> <VER2>
#?
#? Output:
#? 0: VER1 == VER2
#? 1: VER1 > VER2
#? 2: VER1 < VER2
#?
function __xsh_version_comparator () {
if [[ $1 == "$2" ]]; then
echo 0
return
fi
# don't double quote `$1` and `$2`
# shellcheck disable=SC2206
declare -a ver1=( ${1//./ } ) ver2=( ${2//./ } )
declare n1=${#ver1[@]} n2=${#ver2[@]} index
for (( index = 0; index <= $((n1 > n2 ? n1 : n2)); index++ )); do
if [[ ${ver1[index]} -gt ${ver2[index]} ]]; then
echo 1
return
elif [[ ${ver1[index]} -lt ${ver2[index]} ]]; then
echo 2
return
fi
done
echo 0
}
#? Description:
#? chmod +x all .sh regular files under the given dir.
#?
#? Usage:
#? __xsh_chmod_x_by_dir <PATH>
#?
function __xsh_chmod_x_by_dir () {
find "${1:?}" \
-type f \
-name "*.sh" \
-exec chmod +x {} \;
}
#? Description:
#? chmod +x all .sh regular files under `./scripts`.
#?
#? Usage:
#? __xsh_git_chmod_x
#?
function __xsh_git_chmod_x () {
if [[ -d ./scripts ]]; then
__xsh_chmod_x_by_dir ./scripts
fi
}
#? Description:
#? Discard all local changes and untracked files.
#?
#? Usage:
#? __xsh_git_discard_all
#?
function __xsh_git_discard_all () {
git reset --hard \
&& git clean -d --force
}
#? Description:
#? Get git version.
#?
#? Usage:
#? __xsh_git_version
#?
function __xsh_git_version () {
# shellcheck disable=SC2207
declare versions=( $(git version) )
echo "${versions[2]}"
}
#? Description:
#? Get all tags, in ascending order of commit date.
#?
#? Usage:
#? __xsh_git_get_all_tags
#?
function __xsh_git_get_all_tags () {
git tag \
| xargs -I@ git log --format=format:"%ai @%n" -1 @ \
| sort \
| awk '{print $4}'
}
#? Description:
#? Fetch remote tags to local, and remove local tags no longer on remote.
#?
#? Usage:
#? __xsh_git_fetch_remote_tags
#?
function __xsh_git_fetch_remote_tags () {
# get ride of the moving tags on the remote
git fetch --tags -f
if [[ $(__xsh_version_comparator 1.9.0 "$(__xsh_git_version)") -eq 1 ]]; then
# git version < 1.9.0
git fetch --prune origin "+refs/tags/*:refs/tags/*"
else
# git version >= 1.9.0
git fetch --prune --prune-tags origin
fi
}
#? Description:
#? Get the tag current on.
#?
#? Usage:
#? __xsh_git_get_current_tag
#?
function __xsh_git_get_current_tag () {
git describe --tags
}
#? Description:
#? Get the latest tag
#?
#? Usage:
#? __xsh_git_get_latest_tag
#?
function __xsh_git_get_latest_tag () {
__xsh_git_get_all_tags | sed -n '$p'
}
#? Description:
#? Check if the work directory is dirty.
#?
#? Usage:
#? __xsh_git_is_workdir_dirty
#?
function __xsh_git_is_workdir_dirty () {
[[ -n "$(git status -s)" ]]
}
#? Description:
#? Get current branch.
#? Output 'HEAD' if detached at a tag.
#?
#? Usage:
#? __xsh_git_get_current_branch
#?
function __xsh_git_get_current_branch () {
git rev-parse --abbrev-ref HEAD
}
#? Description:
#? Clone a Git repo.
#?
#? Usage:
#? __xsh_git_clone [-s GIT_SERVER] [-b BRANCH | -t TAG] REPO
#?
#? Options:
#? [-s GIT_SERVER] Git server URL.
#? E.g. `https://github.com`
#? [-b BRANCH] Clone the BRANCH's latest state.
#? This option is for developers.
#? [-t TAG] Clone a specific TAG version.
#? REPO Git repo in syntax: `USERNAME/REPO`.
#? E.g. `username/xsh-lib-foo`
function __xsh_git_clone () {
declare -a git_options
declare git_server=${XSH_GIT_SERVER} \
OPTARG OPTIND opt
while getopts s:b:t: opt; do
case ${opt} in
s)
git_server=${OPTARG%/} # remove tailing '/'
;;
b|t)
git_options+=(-"${opt}")
git_options+=("${OPTARG}")
;;
*)
return 255
;;
esac
done
shift $((OPTIND - 1))
declare repo=$1
if [[ -z ${repo} ]]; then
__xsh_log error "Repo name is null or not set."
return 255
fi
if [[ -z ${git_server} ]]; then
__xsh_log error "Git server is null or not set."
return 255
fi
declare repo_path=${XSH_REPO_HOME:?}/${repo}
if [[ -e ${repo_path} ]]; then
__xsh_log error "Repo already exists at ${repo_path}."
return 255
fi
if [[ ${#git_options[@]} -gt 2 ]]; then
__xsh_log error "-b and -t can't be used together."
return 255
fi
# never use a shallow clone here
git clone "${git_server}/${repo}" "${repo_path}"
# update to latest tagged version
(cd "${repo_path}" \
&& __xsh_git_force_update "${git_options[@]}" \
&& __xsh_git_chmod_x
)
declare ret=$?
if [[ ${ret} -ne 0 ]]; then
__xsh_log warning "Deleting repo ${repo_path}."
/bin/rm -rf "${repo_path}"
return ${ret}
fi
}
#? Description:
#? Update current repo.
#? Any local changes will be DISCARDED after update.
#? Any untracked files will be REMOVED after update.
#?
#? Usage:
#? __xsh_git_force_update [-b BRANCH | -t TAG]
#?
#? Options:
#? [-b BRANCH] Update to the BRANCH's latest state.
#? This option is for developers.
#? [-t TAG] Update to a specific TAG version.
#?
function __xsh_git_force_update () {
declare target \
OPTIND OPTARG opt
while getopts b:t: opt; do
case ${opt} in
b|t)
target=${OPTARG}
;;
*)
return 255
;;
esac
done
if __xsh_git_is_workdir_dirty; then
# discard all local changes and untracked files
__xsh_git_discard_all
fi
# fetch remote tags to local
__xsh_git_fetch_remote_tags
if [[ -z ${target} ]]; then
target=$(__xsh_git_get_latest_tag)
if [[ -z ${target} ]]; then
__xsh_log error "No any available tagged version found."
return 255
fi
fi
declare current
current=$(__xsh_git_get_current_tag)
if [[ ${current} == "${target}" ]]; then
__xsh_log info "Already at the latest version: ${current}."
return
fi
# suppress the warning of 'detached HEAD' state
git config advice.detachedHead false
__xsh_log info "Updating repo to ${target}."
if ! git checkout -f "${target}"; then
__xsh_log error "Failed to checkout repo."
return 255
fi
if [[ $(__xsh_git_get_current_branch) != 'HEAD' ]]; then
git reset --hard origin/"${target}"
if ! git pull; then
__xsh_log error "Failed to pull repo."
return 255
fi
fi
}
#? Description:
#? Show help for xsh builtin functions or utilities.
#? The dev mode is being checked indirectly.
#?
#? Usage:
#? __xsh_help [-t] [-T] [-c] [-d] [-sS SECTION,...] [BUILTIN | LPUR]
#?
#? Options:
#? [-t] Show title.
#?
#? [-T] Show highlighted title surrounded with lines.
#?
#? [-c] Show code.
#? The shown code is formatted by shell with BUILTIN.
#?
#? [-d] Show entire document.
#?
#? [-sS SECTION] Show specific section of the document.
#? `-s` turns the section name on.
#? `-S` turns the section name off.
#? The section name is case sensitive.
#? The section list can be delimited with comma `,`.
#? The output order of section is determined by the document order
#? rather than the list order.
#?
#? [BUILTIN] xsh builtin function name without leading `__xsh_`.
#? Show help for xsh builtin functions.
#?
#? [LPUR] LPUR.
#? Show help for matched utilities.
#?
#? If none option presents for BUILTIN or LPUR, then `-T` and `-d` are being used.
#? If both BUILTIN and LPUR unset, then show help for xsh itself.
#? The options order matters to the output.
#? All options can be used multi times.
#?
function __xsh_help () {
declare topic
if [[ $# -gt 0 ]]; then
# get the last argument
topic=${!#}
# remove the last argument from argument list
set -- "${@:1:$#-1}"
fi
if [[ $# -eq 0 ]]; then
# add -d to $@
set -- -T -d
fi
{
if [[ -z ${topic} ]]; then
__xsh_help_self_cache
elif [[ $(type -t "__xsh_${topic//-/_}" || :) == function ]]; then
__xsh_help_builtin "$@" "__xsh_${topic//-/_}"
else
__xsh_help_lib "$@" "${topic}"
fi
} | awk '{gsub(/^[^ ]+.*/, "\033[1m&\033[0m"); print}'
}
#? Description:
#? A wrapper of sha1sum on Linux, and shasum on macOS.
#?
#? Usage:
#? __xsh_sha1sum [OPTIONS]
#?
function __xsh_sha1sum () {
if type -t sha1sum >/dev/null; then
sha1sum "$@"
else
shasum "$@"
fi
}
#? Description:
#? Repeat a string n times.
#?
#? Usage:
#? __xsh_repeat STRING [N]
#?
#? Options:
#? STRING String to repeat.
#? [N] Repeat N times, default is 1, means no repeat.
#?
#? Output:
#? Concatenation of N STRINGs.
#?
#? Example:
#? $ __xsh_repeat Foo 3
#? FooFooFoo
#?
function __xsh_repeat () {
declare str=$1 times=${2:-1}
if [[ -z ${str} ]]; then
return
fi
printf "%${times}s" | sed "s| |${str}|g"
}
#? Description:
#? Show cachable help for xsh itself.
#?
#? Usage:
#? __xsh_help_self_cache
#?
function __xsh_help_self_cache () {
declare hash cached_help
# shellcheck disable=SC2207
hash=( $(__xsh_sha1sum "${XSH_HOME}/xsh/xsh.sh") )
cached_help=/tmp/.${FUNCNAME[0]}_${hash[0]}
if [[ -f ${cached_help} ]]; then
cat "${cached_help}"
else
(umask 0000 && __xsh_help_self | tee "${cached_help}")
fi
}
#? Description:
#? Show help for xsh itself.
#?
#? Usage:
#? __xsh_help_self
#?
function __xsh_help_self () {
# show sections of Description and Usage of xsh itself
__xsh_help_builtin -s 'Description,Usage' xsh
declare -a names=(
calls imports unimports list load unload update
upgrade version versions lib_dev_manager debug help log
)
declare name
# show sections of Usage of xsh builtin functions
for name in "${names[@]}"; do
__xsh_help_builtin -S Usage "__xsh_${name}" \
| sed -e '/^$/d' -e 's/__xsh_/xsh /g'
done
printf '\nCommands:\n'
# show sections of Description and Option of xsh builtin functions
for name in "${names[@]}"; do
__xsh_help_builtin -i "${name}\n" -S Description "__xsh_${name}" \
| sed '/^$/! s/^/ /'
__xsh_help_builtin -S Usage "__xsh_${name}" \
| sed -e '/^$/! s/^/ /' -e 's/__xsh_/xsh /g'
__xsh_help_builtin -s Commands,Option "__xsh_${name}" \
| sed '/^$/! s/^/ /'
done
# show rest sections of xsh itself
__xsh_help_builtin -s 'Builtin,Convention,Debug Mode,Dev Mode' xsh
}
#? Description:
#? Show help for xsh builtin functions.
#?
#? Usage:
#? __xsh_help_builtin [-t] [-T] [-c] [-d] [-sS SECTION,...] <BUILTIN>
#?
#? Options:
#? <BUILTIN> xsh builtin function name.
#?
#? See `xsh help help` for the rest options.
#?
function __xsh_help_builtin () {
# get the last argument
declare builtin=${!#}
# remove the last argument from argument list
declare -a options=( "${@:1:$#-1}" )
__xsh_info -f "${builtin}" "${options[@]}" "${XSH_HOME}/xsh/xsh.sh"
}
#? Description:
#? Show help for xsh utilities.
#? The dev mode is being checked.
#?
#? The util name appearing in the doc in syntax `@<UTIL>` will be replaced
#? as the full util name.
#?
#? Usage:
#? __xsh_help_lib [-t] [-T] [-c] [-d] [-sS SECTION,...] <LPUR>
#?
#? Options:
#? See `xsh help help`.
#?
function __xsh_help_lib () {
function __xsh_help_lib__ () {
# get the last argument
declare lpur=${!#}
# remove the last argument from argument list
declare -a options=( "${@:1:$#-1}" )
declare path
path=$(__xsh_get_path_by_lpur "${lpur}")
declare ln
while read -r ln; do
if [[ -n ${ln} ]]; then
declare util lpue
util=$(__xsh_get_util_by_path "${ln}")
lpue=$(__xsh_get_lpue_by_path "${ln}")
if [[ -z ${util} ]]; then
__xsh_log error "util is null: %s." "${path}"
return 255
fi
if [[ -z ${lpue} ]]; then
__xsh_log error "lpue is null: %s." "${path}"
return 255
fi
__xsh_info "${options[@]}" "${ln}" \
| sed "s|@${util}|xsh ${lpue}|g"
fi
done <<< "${path}"
}
# get the last argument
declare lpur=${!#}
if __xsh_is_dev "${lpur}"; then
XSH_LIB_HOME=${XSH_DEV_HOME} __xsh_help_lib__ "$@"
else
__xsh_help_lib__ "$@"
fi
}
#? Description:
#? Show specific info for xsh builtin functions or utilities.
#?
#? Usage:
#? __xsh_info [-f NAME,...] [-t] [-T] [-c] [-d] [-sS SECTION,...] [-i STRING] [...] <PATH>
#?
#? Options:
#? [-f NAME] Show info for the function only.
#? The name list can be delimited with comma `,`.
#? The output order of function is determined by the coding order
#? rather than the list order.
#?
#? NOTE: This option should be put before all other options if used.
#?
#? [-i STRING] Insert STRING.
#? The string is inserted without newline, use `\n` if needs.
#?
#? <PATH> Path to the scripts file.
#?
#? See `xsh help help` for the rest options.
#?
function __xsh_info () {
function __xsh_filter_section_with_title__ () {
declare section=${1:?}
awk -v sectionregex="^(${section//,/|}):" '{
if (str && substr($0, 1, 1) ~ "[[:alnum:]]") {
print str
str = ""
}
if ($0 ~ sectionregex) str = $0
else if (str) str = str RS $0
} END {if (str) print str}'
}
function __xsh_filter_section_without_title__ () {
declare section=${1:?}
awk -v sectionregex="^(${section//,/|}):" '{
if (flag && substr($0, 1, 1) ~ "[[:alnum:]]") {
print str
flag = str = ""
}
if ($0 ~ sectionregex) flag = 1
else if (flag) str = str (str ? RS : "") $0
} END {if (str) print str}'
}
# get the last argument
declare path=${!#} funcname \
OPTIND OPTARG opt
if [[ -z ${path} || ${path:1:1} == - ]]; then
__xsh_log error "LPU path is null or not set."
return 255
fi
while getopts f:tTcds:S:i: opt; do
case ${opt} in
f)
funcname=${OPTARG}
;;
t|T)
declare title
if [[ -n ${funcname} ]]; then
title=$(__xsh_get_funcname_from_file "${path}" "${funcname}")
else
title=$(__xsh_get_title_by_path "${path}")
fi
if [[ ${opt} == t ]]; then
printf "%s\n" "${title}"
else
declare hr
hr=$(__xsh_repeat '=' ${#title})
printf "%s\n%s\n%s\n" "${hr}" "${title}" "${hr}"
fi
;;
d)
if [[ -n ${funcname} ]]; then
__xsh_get_doc_from_file "${path}" "${funcname}"
else
awk '/^#\?/ {sub("^[ ]*#\\?[ ]?", ""); print}' "${path}"
fi
;;
c)
if [[ -n ${funcname} ]]; then
__xsh_get_funccode_from_file "${path}" "${funcname}"
else
sed '/^#?/d' "${path}"
fi
;;
s)
__xsh_info -f "${funcname}" -d "${path}" | __xsh_filter_section_with_title__ "${OPTARG}"
;;
S)
__xsh_info -f "${funcname}" -d "${path}" | __xsh_filter_section_without_title__ "${OPTARG}"
;;
i)
if [[ -n ${funcname} ]]; then
declare name
for name in ${funcname//,/ }; do
# shellcheck disable=SC2059
printf "${OPTARG}" # do not use `printf '%s'`
done
else
# shellcheck disable=SC2059
printf "${OPTARG}" # do not use `printf '%s'`
fi
;;
*)
return 255
;;
esac
done
}