-
Notifications
You must be signed in to change notification settings - Fork 4
/
setver.sh
executable file
·1279 lines (1163 loc) · 38.8 KB
/
setver.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
#!/usr/bin/env bash
### Created by Peter Forret ( pforret ) on 2021-04-11
### Based on https://github.com/pforret/bashew 1.15.4
script_version="0.0.1" # if there is a VERSION.md in this script's folder, it will take priority for version number
readonly script_author="[email protected]"
readonly script_created="2021-04-11"
readonly run_as_root=-1 # run_as_root: 0 = don't check anything / 1 = script MUST run as root / -1 = script MAY NOT run as root
list_options() {
echo -n "
flag|h|help|show usage
flag|q|quiet|no output
flag|v|verbose|output more
flag|f|force|do not ask for confirmation
flag|r|root|do not check if in root folder of repo
flag|C|SKIP_COMPOSER|do not modify composer.json
flag|N|SKIP_NPM|do not modify package.json (for npm)
option|l|log_dir|folder for log files |$HOME/log/$script_prefix
option|t|tmp_dir|folder for temp files|/tmp/$script_prefix
option|p|prefix|prefix to use for git tags|v
param|1|action|action to perform: get/check/push/set/new/md/message/auto/autopatch/ap/skip/changelog/history
param|?|input|input text
" | grep -v '^#' | grep -v '^\s*$'
}
#####################################################################
## Put your main script here
#####################################################################
main() {
log_to_file "[$script_basename] $script_version started"
uses_composer=0
[[ -f "composer.json" ]] && [[ -n $(command -v composer) ]] && uses_composer=1
(( SKIP_COMPOSER )) && uses_composer=0
uses_npm=0
[[ -f "package.json" ]] && [[ -n $(command -v npm) ]] && uses_npm=1
(( SKIP_NPM )) && uses_npm=0
uses_env=0
env_example=".env.example"
[[ -f "$env_example" ]] && uses_env=1
uses_sh=0
local dirname
dirname="$(dirname "$0")"
[[ -f "./$dirname.sh" ]] && uses_sh=1
# shellcheck disable=SC2154
case "${action,,}" in
#TIP: use «$script_prefix get» to get the version (returns 1 line with the version nr)
get)
get_any_version ;;
#TIP: use «$script_prefix check» to get all versions available in this repo
check)
check_versions ;;
#TIP: use «$script_prefix message» to get the current auto-generated commit message
message)
def_commit_message ;;
#TIP: use «$script_prefix auto» to do commit/push with auto-generated commit message
auto)
commit_and_push auto ;;
#TIP: use «$script_prefix autopatch» or «$script_prefix ap» to do commit/push with auto-generated commit message & bump patch version
autopatch|ap)
commit_and_push auto
set_versions patch
;;
#TIP: use «$script_prefix autominor» to do commit/push with auto-generated commit message & bump minor version
autominor)
commit_and_push auto
set_versions minor
;;
#TIP: use «$script_prefix skip» to do commit/push with auto-generated commit message and skip GH actions
skip | skip-ci | skipci)
commit_and_push skipci ;;
#TIP: use «$script_prefix md» to generate a correct VERSION.md file, if it does not yet exist
md)
create_version_md ;;
#TIP: use «$script_prefix new major/minor/patch» to bump version number with 1
#TIP: use «$script_prefix set x.y.z» to set new version number
set | new | bump | version)
# shellcheck disable=SC2154
set_versions "$input" ;;
#TIP: use «$script_prefix push» to do commit/push with auto-generated commit message
push | commit | github)
commit_and_push ;;
#TIP: use «$script_prefix history» to show the git history in a compact format
history)
show_history ;;
#TIP: use «$script_prefix history» to show the git history in a compact format
changelog)
add_to_changelog "$(get_any_version)";;
env)
## leave this default action, it will make it easier to test your script
#TIP: use «$script_prefix check» to check if this script is ready to execute and what values the options/flags are
#TIP:> $script_prefix check
#TIP: use «$script_prefix env» to generate an example .env file
#TIP:> $script_prefix env > .env
check_script_settings
;;
update)
## leave this default action, it will make it easier to test your script
#TIP: use «$script_prefix update» to update to the latest version
#TIP:> $script_prefix check
update_script_to_latest
;;
*)
die "action [$action] not recognized"
;;
esac
log_to_file "[$script_basename] ended after $SECONDS secs"
#TIP: >>> bash script created with «pforret/bashew»
#TIP: >>> for bash development, also check out «pforret/setver» and «pforret/progressbar»
}
#####################################################################
## Put your helper scripts here
#####################################################################
check_requirements() {
git --version >/dev/null 2>&1 || die "ERROR: git is not installed on this machine"
git status >/dev/null 2>&1 || die "ERROR: this folder [] is not a git repository"
# shellcheck disable=SC2154
if [[ $root -gt 0 ]] ; then
[[ -d .git ]] || die "ERROR: $script_fname should be run from the git repo root"
fi
[[ -f "$script_install_folder/VERSION.md" ]] && script_version=$(cat "$script_install_folder/VERSION.md")
}
get_any_version() {
local version="0.0.0"
if [[ -n "$(get_version_md)" ]]; then
debug "Version from VERSION.md"
get_version_md
return 0
fi
if [[ -n $(get_version_tag) ]]; then
debug "Version from git tag"
get_version_tag
return 0
fi
if [[ -n "$(get_version_composer)" ]]; then
debug "Version from composer"
get_version_composer
return 0
fi
if [[ -n "$(get_version_npm)" ]]; then
debug "Version from npm"
get_version_npm
return
fi
if [[ -n "$(get_version_sh)" ]]; then
debug "Version from sh"
get_version_sh
return
fi
echo "$version"
}
get_version_tag() {
# git tag gives sorted list, which means that 1.10.4 < 1.6.0
if [[ -n $(git tag) ]] ; then
git tag \
| sed 's/[^0-9\.]//' \
| awk -F. '{printf("%04d.%04d.%04d\n",$1,$2,$3);}' \
| sort \
| tail -1 \
| awk -F. '{printf ("%d.%d.%d",$1 + 0 ,$2 + 0,$3 + 0);}'
else
debug "No git tag yet in this repo"
echo ""
fi
}
create_version_md(){
local git_version_md="$git_repo_root/VERSION.md"
local repo_version
if [[ ! -f "$git_version_md" ]] ; then
repo_version=$(get_any_version)
echo "$repo_version" > "$git_version_md"
git add "$git_version_md"
out "VERSION.md was created (version $repo_version)"
else
alert "VERSION.md already exists for this repo $git_repo_root"
fi
}
get_version_md() {
if [[ -f VERSION.md ]]; then
cat VERSION.md
else
debug "No 'VERSION.md' in this folder"
echo ""
fi
}
get_version_composer() {
local version
if [[ $uses_composer -gt 0 ]]; then
# composer.json exists
if grep -q '"version"' composer.json ; then
# shellcheck disable=SC2230
if [[ -n $(which composer) ]] ; then
version=$(composer config version 2> /dev/null)
echo "$version"
else
# composer not installed on this machine
debug "Composer not installed"
echo ""
fi
else
# no "version" field in composer.json
debug "No 'version' field in composer.json"
echo ""
fi
else
# no composer.json in this folder
debug "No 'composer.json' in this folder"
echo ""
fi
}
get_version_npm() {
if [[ $uses_npm -gt 0 ]] ; then
#package.json exists
if grep -q '"version"' package.json ; then
if npm version >/dev/null 2>&1; then
npm ls 2>/dev/null \
| head -1 \
| cut -d' ' -f1 \
| cut -d@ -f2
else
debug "npm not installed"
fi
else
# no "version" field in package.json
debug "No 'version' field in package.json"
echo ""
fi
else
# no package.json in this folder
debug "No 'package.json' in this folder"
echo ""
fi
}
get_version_env() {
if [[ $uses_env -gt 0 ]]; then
awk -F= '
{
if($1 == "VERSION" || $1 == "APP_VERSION"){
print $2
}
}
' < "$env_example" | head -1
else
debug "no $env_example in this folder"
echo ""
fi
}
get_version_sh() {
local sh
sh="./$(dirname "$0").sh"
if [[ -f "$sh" ]]; then
grep -m 1 -iPo '\b\s*=\s*"\K.*?(?=")' "$sh"
else
debug "No 'sh' script in this folder"
echo ""
fi
}
add_to_changelog() {
local version="$1"
local changelog=CHANGELOG.md
if [[ -f "$changelog" ]]; then
today=$(date '+%Y-%m-%d')
temp_file=.CHANGELOG.tmp
(
echo "## [$version] - $today"
echo "### Added/changed"
# take last 3 commits that were not version-related
git log -3 --pretty=format:"%s" --grep '\.[0-9]' --invert-grep |
sed 's/^/- /'
echo " "
) >$temp_file
\
awk <"$changelog" \
'
BEGIN {
inserted=0
}
function copyfile(filename){
while ((getline line < filename) > 0) print line;
close(filename);
}
{
if($0 ~ /^## \[[0-9]/ && inserted==0) {
copyfile(".CHANGELOG.tmp");
inserted=1;
}
print $0
}
END {
if(inserted==0) {
copyfile(".CHANGELOG.tmp");
}
}
' \
>$changelog.tmp
if [[ -s "$changelog.tmp" ]]; then
success "added to $changelog:"
cat $temp_file
rm $temp_file
rm $changelog
mv $changelog.tmp $changelog
git add $changelog
else
rm $changelog.tmp
fi
fi
}
show_version(){
local version="$1"
local location="$2"
if [[ -z "$first_version" ]] ; then
first_version="$version"
printf "$col_grn$char_succ Version in %14s: %s$col_reset\n" "$location" "$version"
else
if [[ "$version" == "$first_version" ]] ; then
printf "$col_grn$char_succ Version in %14s: %s$col_reset\n" "$location" "$version"
else
printf "$col_red$char_fail Version in %14s: [%s] != [$first_version]$col_reset\n" "$location" "$version"
fi
fi
}
check_versions() {
first_version=""
local version_tag
local version_composer
local version_md
local version_npm
local version_env
local version_sh
success "$script_prefix check versions:"
version_tag=$(get_version_tag)
[[ -n $version_tag ]] && show_version "$version_tag" "git tag"
version_composer=$(get_version_composer)
[[ -n $version_composer ]] && show_version "$version_composer" "composer.json"
version_md=$(get_version_md)
[[ -n $version_md ]] && show_version "$version_md" "VERSION.md"
version_npm=$(get_version_npm)
[[ -n $version_npm ]] && show_version "$version_npm" "package.json"
version_env=$(get_version_env)
[[ -n $version_env ]] && show_version "$version_env" ".env.example"
version_sh=$(get_version_sh)
[[ -n $version_sh ]] && show_version "$version_sh" "$sh"
}
set_versions() {
git_status=$(git status -s)
if [[ -n "$git_status" ]]; then
die "ERROR: Git working directory not clean (check 'git status') "
fi
remote_url=$(git config remote.origin.url)
new_version="$1"
do_git_push=0
current_semver=$(get_any_version)
semver_major=$(echo "$current_semver" | cut -d. -f1)
semver_minor=$(echo "$current_semver" | cut -d. -f2)
semver_patch=$(echo "$current_semver" | cut -d. -f3)
case "$new_version" in
major|MAJOR)
new_version="$((semver_major + 1)).0.0"
success "version $current_semver -> $new_version (bump major)"
;;
minor)
new_version="$semver_major.$((semver_minor + 1)).0"
success "version $current_semver -> $new_version (bump minor)"
;;
patch|bug|bugfix)
# supports auto|patch|fix
new_version="$semver_major.$semver_minor.$((semver_patch + 1))"
success "version $current_semver -> $new_version (bump patch)"
;;
*)
new_version="$1"
success "version $current_semver -> $new_version (manual override)"
esac
# TODO: fully support [<newversion> | major | minor | patch | premajor | preminor | prepatch | prerelease [--preid=<prerelease-id>] | from-git]
### composer.json
if [[ $uses_composer -gt 0 ]]; then
# for PHP repos
# first change composer.json
debug "set version in composer.json: $new_version"
# shellcheck disable=SC2154
outfile="$tmp_dir/set_version.composer.log"
composer config version "$new_version" &> "$outfile" ||
alert "'composer version' failed - check $outfile for details"
git add composer.json
do_git_push=1
fi
### .env
if [[ $uses_env -gt 0 ]]; then
# for Ruby/PHP/bash/...
debug "set version in $env_example: $new_version"
env_temp="$env_example.tmp"
awk -F= -v version="$new_version" '
{
if($1 == "VERSION" || $1 == "APP_VERSION"){
print $1 "=" version
}
else {
print
}
}
' < "$env_example" > "$env_temp"
if [[ -n $(diff "$env_example" "$env_temp") ]] ; then
rm "$env_example"
mv "$env_temp" "$env_example"
git add "$env_example"
do_git_push=1
else
rm "$env_temp"
fi
fi
### VERSION.md
if [[ -f VERSION.md ]]; then
# for bash repos
debug "set version in VERSION.md: $new_version"
echo "$new_version" >VERSION.md
git add VERSION.md
do_git_push=1
fi
### shellscript.sh
if [[ $uses_sh -gt 0 ]]; then
sh_temp="$sh.tmp"
debug "set version in $sh: $new_version"
awk -F= -v version="\"$new_version\"" '
{
if($1 == "VERSION" || $1 == "version"){
print $1 "=" version
}
else {
print
}
}
' < "$sh" > "$sh_temp"
if [[ -n $(diff "$sh" "$sh_temp") ]] ; then
rm "$sh"
mv "$sh_temp" "$sh"
git add "$sh"
do_git_push=1
else
rm "$sh_temp"
fi
fi
### package.json
if [[ $uses_npm -gt 0 ]]; then
# for NPM/node repos
# first change package.json
debug "set version in package.json: $new_version"
outfile="$tmp_dir/set_version.npm.log"
npm version --no-git-tag-version "$new_version" &> "$outfile" ||
alert "'npm version' failed - check $outfile for details"
git add package.json
[[ -f package-lock.json ]] && git add package-lock.json
do_git_push=1
fi
if [[ $do_git_push -gt 0 ]]; then
debug "commit changes"
outfile="$tmp_dir/set_version.commit.log"
git commit -m "setver: set version to $new_version" -m "[skip ci]" &> "$outfile" ||
alert "'git commit' failed - check $outfile for details"
# push all files changes
push_if_possible "N"
outfile="$tmp_dir/set_version.tag.log"
# shellcheck disable=SC2154
success "set git version tag: $prefix$new_version"
git tag "$prefix$new_version" &> "$outfile" || alert "'git tag' failed - check $outfile for details"
# push tags
push_if_possible "Y"
fi
local web_url
local git_host
local username
local reponame
web_url=$(echo "$remote_url" | cut -d: -f2)
# should be like <username>/<repo>.git
git_host=$(echo "$remote_url" | cut -d: -f1)
# should be like [email protected]
if [[ -n "$web_url" ]]; then
username=$(dirname "$web_url")
reponame=$(basename "$web_url" .git)
case "$git_host" in
[email protected]) web_url="https://github.com/$username/$reponame" ;;
[email protected]) web_url="https://bitbucket.org/$username/$reponame" ;;
[email protected]) web_url="https://gitlab.com/$username/$reponame" ;;
esac
success "Repo online on $web_url"
fi
}
def_commit_message(){
git status --short \
| sed 's/^ //' \
| awk '
function basename(file) {
sub(".*/", "", file)
return file
}
BEGIN {add=""; mod=""; del=""; ren=""}
/^A/ {add=add " " basename($2);}
/^R/ {ren=ren " " basename($2);}
/^M/ {mod=mod " " basename($2);}
/^D/ {del=del " " basename($2);}
END {
if(length(add)>0){printf "ADD:" add ", "}
if(length(del)>0){printf "DEL:" del ", "}
if(length(ren)>0){printf "MOV:" ren ", "}
if(length(mod)>0){printf "MOD:" mod}
print "\n";
}
'
}
commit_and_push() {
set +e
trap - INT TERM EXIT
local mode=${1:-}
local default_message=""
default_message="$(def_commit_message)"
debug "Commit message = [$default_message]"
case "$mode" in
skip-ci|skipci)
success "Commit: $default_message [skip ci]"
git commit -a -m "$default_message" -m "[skip ci]" && push_if_possible
;;
auto | fast)
success "Commit: $default_message"
git commit -a -m "$default_message" && push_if_possible
;;
*)
# interactive commit
git commit -a && push_if_possible
esac
}
show_history() {
trap - INT TERM EXIT
git log --pretty=format:"%ci ; %ce ; %s" \
| more
}
push_if_possible(){
local check_remote=""
local flags=${1:-}
outfile="$tmp_dir/${script_prefix}_push.log"
check_remote=$(git remote -v | awk '/\(push\)/ {print $2}')
if [[ -n "$check_remote" ]] ; then
echo "push to remote [$check_remote]" &> "$outfile"
if [[ "$flags" == "Y" ]] ; then
success "push tags to [$check_remote]"
git push --tags &>> "$outfile" || die "'git push --tags' failed - check $outfile for details"
else
success "push changes [$check_remote]"
git push &>> "$outfile" || die "'git push' failed - check $outfile for details"
fi
else
debug "No remote set - skip git push"
fi
}
#####################################################################
################### DO NOT MODIFY BELOW THIS LINE ###################
#####################################################################
# set strict mode - via http://redsymbol.net/articles/unofficial-bash-strict-mode/
# removed -e because it made basic [[ testing ]] difficult
set -uo pipefail
IFS=$'\n\t'
hash() {
length=${1:-6}
if [[ -n $(command -v md5sum) ]]; then
# regular linux
md5sum | cut -c1-"$length"
else
# macos
md5 | cut -c1-"$length"
fi
}
force=0
help=0
verbose=0
#to enable verbose even before option parsing
[[ $# -gt 0 ]] && [[ $1 == "-v" ]] && verbose=1
quiet=0
#to enable quiet even before option parsing
[[ $# -gt 0 ]] && [[ $1 == "-q" ]] && quiet=1
### stdout/stderr output
initialise_output() {
[[ "${BASH_SOURCE[0]:-}" != "${0}" ]] && sourced=1 || sourced=0
[[ -t 1 ]] && piped=0 || piped=1 # detect if output is piped
if [[ $piped -eq 0 ]]; then
col_reset="\033[0m"
col_red="\033[1;31m"
col_grn="\033[1;32m"
col_ylw="\033[1;33m"
else
col_reset=""
col_red=""
col_grn=""
col_ylw=""
fi
[[ $(echo -e '\xe2\x82\xac') == '€' ]] && unicode=1 || unicode=0 # detect if unicode is supported
if [[ $unicode -gt 0 ]]; then
char_succ="√"
char_fail="×"
char_alrt="⊗️"
char_wait="…"
info_icon="🌼"
config_icon="🌱"
clean_icon="🧽"
require_icon="🔌"
else
char_succ="OK "
char_fail="!! "
char_alrt="?? "
char_wait="..."
info_icon="(i)"
config_icon="[c]"
clean_icon="[c]"
require_icon="[r]"
fi
error_prefix="${col_red}>${col_reset}"
}
out() { ((quiet)) && true || printf '%b\n' "$*"; }
debug() { if ((verbose)); then out "${col_ylw}# $* ${col_reset}" >&2; else true; fi; }
die() { out "${col_red}${char_fail} $script_basename${col_reset}: $*" >&2 ; tput bel ; safe_exit ; }
alert() { out "${col_red}${char_alrt}${col_reset}: $*" >&2 ; }
success() { out "${col_grn}${char_succ}${col_reset} $*"; }
announce() { out "${col_grn}${char_wait}${col_reset} $*"; sleep 1 ; }
progress() {
((quiet)) || (
local screen_width
screen_width=$(tput cols 2>/dev/null || echo 80)
local rest_of_line
rest_of_line=$((screen_width - 5))
if ((piped)); then
out "$*" >&2
else
printf "... %-${rest_of_line}b\r" "$* " >&2
fi
)
}
log_to_file() { [[ -n ${log_file:-} ]] && echo "$(date '+%H:%M:%S') | $*" >>"$log_file"; }
### string processing
lower_case() { echo "$*" | tr '[:upper:]' '[:lower:]'; }
upper_case() { echo "$*" | tr '[:lower:]' '[:upper:]'; }
slugify() {
# slugify <input> <separator>
# slugify "Jack, Jill & Clémence LTD" => jack-jill-clemence-ltd
# slugify "Jack, Jill & Clémence LTD" "_" => jack_jill_clemence_ltd
separator="${2:-}"
[[ -z "$separator" ]] && separator="-"
# shellcheck disable=SC2020
echo "$1" |
tr '[:upper:]' '[:lower:]' |
tr 'àáâäæãåāçćčèéêëēėęîïííīįìłñńôöòóœøōõßśšûüùúūÿžźż' 'aaaaaaaaccceeeeeeeiiiiiiilnnoooooooosssuuuuuyzzz' |
awk '{
gsub(/[\[\]@#$%^&*;,.:()<>!?\/+=_]/," ",$0);
gsub(/^ */,"",$0);
gsub(/ *$/,"",$0);
gsub(/ */,"-",$0);
gsub(/[^a-z0-9\-]/,"");
print;
}' |
sed "s/-/$separator/g"
}
title_case() {
# title_case <input> <separator>
# title_case "Jack, Jill & Clémence LTD" => JackJillClemenceLtd
# title_case "Jack, Jill & Clémence LTD" "_" => Jack_Jill_Clemence_Ltd
separator="${2:-}"
# shellcheck disable=SC2020
echo "$1" |
tr '[:upper:]' '[:lower:]' |
tr 'àáâäæãåāçćčèéêëēėęîïííīįìłñńôöòóœøōõßśšûüùúūÿžźż' 'aaaaaaaaccceeeeeeeiiiiiiilnnoooooooosssuuuuuyzzz' |
awk '{ gsub(/[\[\]@#$%^&*;,.:()<>!?\/+=_-]/," ",$0); print $0; }' |
awk '{
for (i=1; i<=NF; ++i) {
$i = toupper(substr($i,1,1)) tolower(substr($i,2))
};
print $0;
}' |
sed "s/ /$separator/g" |
cut -c1-50
}
### interactive
confirm() {
# $1 = question
flag_set $force && return 0
read -r -p "$1 [y/N] " -n 1
echo " "
[[ $REPLY =~ ^[Yy]$ ]]
}
ask() {
# $1 = variable name
# $2 = question
# $3 = default value
# not using read -i because that doesn't work on MacOS
local ANSWER
read -r -p "$2 ($3) > " ANSWER
if [[ -z "$ANSWER" ]]; then
eval "$1=\"$3\""
else
eval "$1=\"$ANSWER\""
fi
}
trap "die \"ERROR \$? after \$SECONDS seconds \n\
\${error_prefix} last command : '\$BASH_COMMAND' \" \
\$(< \$script_install_path awk -v lineno=\$LINENO \
'NR == lineno {print \"\${error_prefix} from line \" lineno \" : \" \$0}')" INT TERM EXIT
# cf https://askubuntu.com/questions/513932/what-is-the-bash-command-variable-good-for
safe_exit() {
[[ -n "${tmp_file:-}" ]] && [[ -f "$tmp_file" ]] && rm "$tmp_file"
trap - INT TERM EXIT
debug "$script_basename finished after $SECONDS seconds"
exit 0
}
flag_set() { [[ "$1" -gt 0 ]]; }
show_usage() {
out "Program: ${col_grn}$script_basename $script_version${col_reset} by ${col_ylw}$script_author${col_reset}"
out "Updated: ${col_grn}$script_modified${col_reset}"
out "Description: setver but based on bashew"
echo -n "Usage: $script_basename"
list_options |
awk '
BEGIN { FS="|"; OFS=" "; oneline="" ; fulltext="Flags, options and parameters:"}
$1 ~ /flag/ {
fulltext = fulltext sprintf("\n -%1s|--%-12s: [flag] %s [default: off]",$2,$3,$4) ;
oneline = oneline " [-" $2 "]"
}
$1 ~ /option/ {
fulltext = fulltext sprintf("\n -%1s|--%-12s: [option] %s",$2,$3 " <?>",$4) ;
if($5!=""){fulltext = fulltext " [default: " $5 "]"; }
oneline = oneline " [-" $2 " <" $3 ">]"
}
$1 ~ /list/ {
fulltext = fulltext sprintf("\n -%1s|--%-12s: [list] %s (array)",$2,$3 " <?>",$4) ;
fulltext = fulltext " [default empty]";
oneline = oneline " [-" $2 " <" $3 ">]"
}
$1 ~ /secret/ {
fulltext = fulltext sprintf("\n -%1s|--%s <%s>: [secret] %s",$2,$3,"?",$4) ;
oneline = oneline " [-" $2 " <" $3 ">]"
}
$1 ~ /param/ {
if($2 == "1"){
fulltext = fulltext sprintf("\n %-17s: [parameter] %s","<"$3">",$4);
oneline = oneline " <" $3 ">"
}
if($2 == "?"){
fulltext = fulltext sprintf("\n %-17s: [parameter] %s (optional)","<"$3">",$4);
oneline = oneline " <" $3 "?>"
}
if($2 == "n"){
fulltext = fulltext sprintf("\n %-17s: [parameters] %s (1 or more)","<"$3">",$4);
oneline = oneline " <" $3 " …>"
}
}
END {print oneline; print fulltext}
'
}
check_last_version(){
(
# shellcheck disable=SC2164
pushd "$script_install_folder" &> /dev/null
if [[ -d .git ]] ; then
local remote
remote="$(git remote -v | grep fetch | awk 'NR == 1 {print $2}')"
progress "Check for latest version - $remote"
git remote update &> /dev/null
if [[ $(git rev-list --count "HEAD...HEAD@{upstream}" 2>/dev/null) -gt 0 ]] ; then
out "There is a more recent update of this script - run <<$script_prefix update>> to update"
else
out " "
fi
fi
# shellcheck disable=SC2164
popd &> /dev/null
)
}
update_script_to_latest(){
# run in background to avoid problems with modifying a running interpreted script
(
sleep 1
cd "$script_install_folder" && git pull
) &
}
show_tips() {
((sourced)) && return 0
# shellcheck disable=SC2016
grep <"${BASH_SOURCE[0]}" -v '$0' \
| awk \
-v green="$col_grn" \
-v yellow="$col_ylw" \
-v reset="$col_reset" \
'
/TIP: / {$1=""; gsub(/«/,green); gsub(/»/,reset); print "*" $0}
/TIP:> / {$1=""; print " " yellow $0 reset}
' \
| awk \
-v script_basename="$script_basename" \
-v script_prefix="$script_prefix" \
'{
gsub(/\$script_basename/,script_basename);
gsub(/\$script_prefix/,script_prefix);
print ;
}'
}
check_script_settings() {
if [[ -n $(filter_option_type flag) ]]; then
out "## ${col_grn}boolean flags${col_reset}:"
filter_option_type flag |
while read -r name; do
if ((piped)); then
eval "echo \"$name=\$${name:-}\""
else
eval "echo -n \"$name=\$${name:-} \""
fi
done
out " "
out " "
fi
if [[ -n $(filter_option_type option) ]]; then
out "## ${col_grn}option defaults${col_reset}:"
filter_option_type option |
while read -r name; do
if ((piped)); then
eval "echo \"$name=\$${name:-}\""
else
eval "echo -n \"$name=\$${name:-} \""
fi
done
out " "
out " "
fi
if [[ -n $(filter_option_type list) ]]; then
out "## ${col_grn}list options${col_reset}:"
filter_option_type list |
while read -r name; do
if ((piped)); then
eval "echo \"$name=(\${${name}[@]})\""
else
eval "echo -n \"$name=(\${${name}[@]}) \""
fi
done
out " "
out " "
fi
if [[ -n $(filter_option_type param) ]]; then
if ((piped)); then
debug "Skip parameters for .env files"
else
out "## ${col_grn}parameters${col_reset}:"
filter_option_type param |
while read -r name; do
# shellcheck disable=SC2015
((piped)) && eval "echo \"$name=\\\"\${$name:-}\\\"\"" || eval "echo -n \"$name=\\\"\${$name:-}\\\" \""
done
echo " "
fi
fi
}
filter_option_type() {
list_options | grep "$1|" | cut -d'|' -f3 | sort | grep -v '^\s*$'
}
init_options() {
local init_command
init_command=$(list_options |
grep -v "verbose|" |
awk '
BEGIN { FS="|"; OFS=" ";}
$1 ~ /flag/ && $5 == "" {print $3 "=0; "}
$1 ~ /flag/ && $5 != "" {print $3 "=\"" $5 "\"; "}
$1 ~ /option/ && $5 == "" {print $3 "=\"\"; "}
$1 ~ /option/ && $5 != "" {print $3 "=\"" $5 "\"; "}
$1 ~ /list/ {print $3 "=(); "}
$1 ~ /secret/ {print $3 "=\"\"; "}
')
if [[ -n "$init_command" ]]; then
eval "$init_command"
fi
}
expects_single_params() { list_options | grep 'param|1|' >/dev/null; }
expects_optional_params() { list_options | grep 'param|?|' >/dev/null; }
expects_multi_param() { list_options | grep 'param|n|' >/dev/null; }
parse_options() {
if [[ $# -eq 0 ]]; then
show_usage >&2
safe_exit
fi
## first process all the -x --xxxx flags and options
while true; do
# flag <flag> is saved as $flag = 0/1
# option <option> is saved as $option
if [[ $# -eq 0 ]]; then
## all parameters processed
break
fi
if [[ ! $1 == -?* ]]; then
## all flags/options processed
break
fi
local save_option
save_option=$(list_options |
awk -v opt="$1" '
BEGIN { FS="|"; OFS=" ";}
$1 ~ /flag/ && "-"$2 == opt {print $3"=1"}
$1 ~ /flag/ && "--"$3 == opt {print $3"=1"}
$1 ~ /option/ && "-"$2 == opt {print $3"=$2; shift"}
$1 ~ /option/ && "--"$3 == opt {print $3"=$2; shift"}
$1 ~ /list/ && "-"$2 == opt {print $3"+=($2); shift"}
$1 ~ /list/ && "--"$3 == opt {print $3"=($2); shift"}
$1 ~ /secret/ && "-"$2 == opt {print $3"=$2; shift #noshow"}
$1 ~ /secret/ && "--"$3 == opt {print $3"=$2; shift #noshow"}
')
if [[ -n "$save_option" ]]; then
if echo "$save_option" | grep shift >>/dev/null; then
local save_var
save_var=$(echo "$save_option" | cut -d= -f1)
debug "$config_icon parameter: ${save_var}=$2"
else
debug "$config_icon flag: $save_option"
fi