-
Notifications
You must be signed in to change notification settings - Fork 1
/
lib.sh
1408 lines (1258 loc) · 31 KB
/
lib.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
#!/bin/sh
if [ "${LIB_CI-}" ]; then
return 0
fi
LIB_CI=1
ci_go_lint() {
go vet --composites=false ./...
}
ci_waitjobs() {
if [ -z "${CI-}" ]; then
waitjobs
return 0
fi
capcode waitjobs
if [ "$code" -ne 0 ]; then
notify
return "$code"
fi
capcode git_assert_clean
if [ "$code" -ne 0 ]; then
notify
return "$code"
fi
capcode nofixups
notify
return "$code"
}
#!/bin/sh
if [ "${LIB_FLAG-}" ]; then
return 0
fi
LIB_FLAG=1
# flag_parse implements a robust flag parser.
#
# For a full fledge example see ../examples/date.sh
#
# It differs from getopts(1) in that long form options are supported. Currently the only
# deficiency is that short combined options are not supported like -xyzq. That would be
# interpreted as a single -xyzq flag. The other deficiency is lack of support for short
# flag syntax like -carg where the arg is not separated from the flag. This one is
# unfixable I believe unfortunately but for combined short flags I have opened
# https://github.com/terrastruct/ci/issues/6
#
# flag_parse stores state in $FLAG, $FLAGRAW, $FLAGARG and $FLAGSHIFT.
# FLAG contains the name of the flag without hyphens.
# FLAGRAW contains the name of the flag as passed in with hyphens.
# FLAGARG contains the argument for the flag if there was any.
# If there was none, it will not be set.
# FLAGSHIFT contains the number by which the arguments should be shifted to
# start at the next flag/argument
#
# flag_parse exits with a non zero code when there are no more flags
# to be parsed. Still, call shift "$FLAGSHIFT" in case there was a --
#
# If the argument for the flag is optional, then use ${FLAGARG-} to access
# the argument if one was passed. Use ${FLAGARG+x} = x to check if it was set.
# You only need to explicitly check if the flag was set if you care whether the user
# explicitly passed the empty string as the argument.
#
# Otherwise, call one of the flag_*arg functions:
#
# If a flag requires an argument, call flag_reqarg
# - $FLAGARG is guaranteed to be set after.
# If a flag requires a non empty argument, call flag_nonemptyarg
# - $FLAGARG is guaranteed to be set to a non empty string after.
# If a flag should not be passed an argument, call flag_noarg
# - $FLAGARG is guaranteed to be unset after.
#
# And then shift "$FLAGSHIFT"
flag_parse() {
case "${1-}" in
-*=*)
# Remove everything after first equal sign.
FLAG="${1%%=*}"
# Remove leading hyphens.
FLAG="${FLAG#-}"; FLAG="${FLAG#-}"
FLAGRAW="$(flag_fmt)"
# Remove everything before first equal sign.
FLAGARG="${1#*=}"
FLAGSHIFT=1
return 0
;;
-)
FLAGSHIFT=0
return 1
;;
--)
FLAGSHIFT=1
return 1
;;
-*)
# Remove leading hyphens.
FLAG="${1#-}"; FLAG="${FLAG#-}"
FLAGRAW=$(flag_fmt)
unset FLAGARG
FLAGSHIFT=1
if [ $# -gt 1 ]; then
case "$2" in
-)
FLAGARG="$2"
FLAGSHIFT=2
;;
-*)
;;
*)
FLAGARG="$2"
FLAGSHIFT=2
;;
esac
fi
return 0
;;
*)
FLAGSHIFT=0
return 1
;;
esac
}
flag_reqarg() {
if [ "${FLAGARG+x}" != x ]; then
flag_errusage "flag $FLAGRAW requires an argument"
fi
}
flag_nonemptyarg() {
flag_reqarg
if [ -z "$FLAGARG" ]; then
flag_errusage "flag $FLAGRAW requires a non-empty argument"
fi
}
flag_noarg() {
if [ "$FLAGSHIFT" -eq 2 ]; then
unset FLAGARG
FLAGSHIFT=1
elif [ "${FLAGARG+x}" = x ]; then
# Means an argument was passed via equal sign as in -$FLAG=$FLAGARG
flag_errusage "flag $FLAGRAW does not accept an argument"
fi
}
flag_errusage() {
caterr <<EOF
$1
Run with --help for usage.
EOF
return 1
}
flag_fmt() {
if [ "$(printf %s "$FLAG" | wc -c)" -eq 1 ]; then
echo "-$FLAG"
else
echo "--$FLAG"
fi
}
#!/bin/sh
if [ "${LIB_GIT-}" ]; then
return 0
fi
LIB_GIT=1
ensure_git_base() {
if [ "${GIT_BASE+x}" = x ]; then
return
fi
if [ -n "${CI_FORCE-}" ] || [ "$(git_commit_count)" -lt 1 ]; then
export GIT_BASE=
FGCOLOR=4 echop "GIT_BASE="
return
fi
if git show --no-patch --format=%s%n%b | grep -qF '[ci-force]'; then
export CI_FORCE=1
export GIT_BASE=
FGCOLOR=4 echop "GIT_BASE="
return
fi
if [ "$(git rev-parse --is-shallow-repository)" = true ]; then
# Without --recurse-submodules, git fetch will sometimes throw errors like
# fatal: remote error: upload-pack: not our ref a1eddf1ed342a9d9fb1942c0d03bf375ba7f6496
# when fetching submodules.
git fetch --recurse-submodules=no --unshallow
fi
if [ "$(git_commit_count)" -lt 2 ]; then
export GIT_BASE=
FGCOLOR=4 echop "GIT_BASE="
return
fi
GIT_BASE="$(git log --grep="Merge pull request" --grep="\[ci-base\]" --grep="\[ci-force\]" --format=%h HEAD | head -n1)"
if [ "$GIT_BASE" = "$(git rev-parse --short HEAD)" ]; then
if [ -z "$(git status -s)" ]; then
GIT_BASE="$(git log --grep="Merge pull request" --grep="\[ci-base\]" --grep="\[ci-force\]" --format=%h HEAD~1 | head -n1)"
else
GIT_BASE=HEAD
fi
fi
export GIT_BASE
if [ -n "$GIT_BASE" ]; then
FGCOLOR=4 echop "GIT_BASE=$GIT_BASE"
fi
}
is_changed() {
ensure_git_base
if [ -z "${GIT_BASE-}" ]; then
return
fi
if [ "$(git_commit_count)" -lt 2 ]; then
return
fi
! git diff --quiet "$GIT_BASE" -- "$@" ||
[ -n "$(git ls-files --other --exclude-standard -- "$@")" ]
}
ensure_changed_files() {
ensure_git_base
if [ -n "${CHANGED_FILES-}" ]; then
return
fi
CHANGED_FILES=$(mktempd)/changed-files
(
git ls-files --other --exclude-standard > "$CHANGED_FILES"
if [ -n "${GIT_BASE-}" ]; then
git diff --relative --name-only "$GIT_BASE" | filter_exists >> "$CHANGED_FILES"
else
git ls-files >> "$CHANGED_FILES"
fi
)
if [ -z "${CI_FORCE-}" ]; then
logpcat changed <"$CHANGED_FILES"
fi
}
gitc() {
if should_color; then
command git -c color.diff=always "$@"
else
command git -c color.diff=never "$@"
fi
}
git_assert_clean() {
diff=$(mktempd)/diff
if should_color; then
capcode git -c color.diff=always diff --exit-code "$@" >"$diff"
else
capcode git -c color.diff=never diff --exit-code "$@" >"$diff"
fi
if [ "$code" -ne 0 ]; then
echoerr "some files need to be formatted or regenerated"
cat "$diff" >&2
return "$code"
fi
}
filter_exists() {
while read -r p; do
if [ -e "$p" ]; then
printf '%s\n' "$p"
fi
done
}
git_describe_ref() {
TAG="$(git describe --exact-match 2> /dev/null || true)"
if [ -n "$TAG" ]; then
_echo "$TAG"
else
git rev-parse --short HEAD
fi
}
# subshell for cd ..
search_up() {(
file="$1"
git_root="$(git rev-parse --show-toplevel)"
while true; do
if [ -e "$file" ]; then
_echo "$file"
return
fi
if [ "$PWD" = "$git_root" ]; then
break
fi
cd ..
done
return 1
)}
xargs() {
ensure_os
if [ "$OS" = linux ]; then
r_flag=1
fi
command xargs ${r_flag:+-r} -t -n"${XARGS_N:-256}" -- "$@"
}
xargsd() {
ensure_changed_files
pattern="$1"
shift
<"$CHANGED_FILES" grep "$pattern" | xargs "$@"
}
nofixups() {
ensure_git_base
if [ "$(git_commit_count)" -lt 1 ]; then
return
fi
commits="$(git log --grep='fixup!' --format=%h ${GIT_BASE:+"$GIT_BASE..HEAD"})"
if [ -n "$commits" ]; then
echo "$commits" | FGCOLOR=1 logpcat 'fixup detected'
return 1
fi
}
ensure_signed() {
ensure_git_base
if [ "$(git_commit_count)" -lt 1 ]; then
return
fi
setup_allowed_signers
# look for signature status N: no signature (verification done by github)
if [ ! "$(git log --format="%G?" ${GIT_BASE:+"$GIT_BASE..HEAD"} | grep "N")" ]; then
return
fi
# print the hash and summary of the unsigned commits
echo "$(git log --format="%G? %h %s" ${GIT_BASE:+"$GIT_BASE..HEAD"} | grep "^N " | cut -d " " -f 2- )" | FGCOLOR=1 logpcat 'found unsigned commit'
return 1
}
setup_allowed_signers() {
# we only care if a signature is present (github will verify) so we don't need any entries,
# but "gpg.ssh.allowedSignersFile needs to be configured and exist for ssh signature verification"
if git config --get gpg.ssh.allowedSignersFile >/dev/null; then
return
fi
allowed_signers=".emptyAllowedSigners"
touch $allowed_signers
git config --local gpg.ssh.allowedSignersFile "$allowed_signers"
}
git_commit_count() {
# macOS sh is buggy and requires the subshell here.
(git rev-list HEAD --count 2>/dev/null) || echo 0
}
configure_github_token() {
git config --global credential.helper store
cat > ~/.git-credentials <<EOF
https://cyborg-ts:$GITHUB_TOKEN@github.com
EOF
}
git_pure() {
if [ -z "${GIT_CONFIG_PURE-}" ]; then
GIT_CONFIG_PURE="$(mktempd)/gitconfig-pure"
export GIT_CONFIG_PURE
fi
if [ -z "${_GIT_CONFIG_PURE-}" ]; then
if command -v diff-highlight >/dev/null; then
GIT_CONFIG_GLOBAL=$GIT_CONFIG_PURE command git config --global pager.log 'diff-highlight | less'
GIT_CONFIG_GLOBAL=$GIT_CONFIG_PURE command git config --global pager.show 'diff-highlight | less'
GIT_CONFIG_GLOBAL=$GIT_CONFIG_PURE command git config --global pager.diff 'diff-highlight | less'
fi
GIT_CONFIG_GLOBAL=$GIT_CONFIG_PURE command git config --global init.defaultBranch master
GIT_CONFIG_GLOBAL=$GIT_CONFIG_PURE command git config --global user.name "Cyborg Tstruct"
GIT_CONFIG_GLOBAL=$GIT_CONFIG_PURE command git config --global user.email "info+cyborg@terrastruct.com"
export _GIT_CONFIG_PURE=1
fi
GIT_CONFIG_GLOBAL=$GIT_CONFIG_PURE gitc "$@"
}
gitsync() {(
REMOTE_HOST=$1
to=$2
ssh "$REMOTE_HOST" sh <<EOF
set -eu
mkdir -p "$to"
cd "$to"
git init
EOF
sh_c git push -f "$REMOTE_HOST:$to" HEAD:_gitsync
ssh "$REMOTE_HOST" sh <<EOF
set -eu
mkdir -p "$to"
cd "$to"
git init
git checkout -qf "$(git rev-parse --short HEAD)"
git add --all
git reset --hard HEAD
git reset
git submodule update --init
EOF
localfiles="$(mktempd)/local_files"
sh_c git ls-files --exclude-standard --cached --other >"$localfiles"
sh_c rsync --archive --human-readable --delete --delete-missing-args \
--files-from="$localfiles" ./ "$REMOTE_HOST:$to/"
)}
#!/bin/sh
if [ "${LIB_GITHUB-}" ]; then
return 0
fi
LIB_GITHUB=1
ensure_github_user() {
if [ -n "${GITHUB_USER-}" ]; then
return
fi
GITHUB_USER=$(git remote get-url origin | sed 's#.*github.com/\([^/]*\)/.*#\1#')
}
#!/bin/sh
if [ "${LIB_JOB-}" ]; then
return 0
fi
LIB_JOB=1
# This runs in a subshell so that we get output from the job even if it's shutting
# down due to a ctrl+c. Without the subshell, sed would be a job of the parent
# shell and so waitjobs would send SIGTERM to it.
#
# note: Unfortunately this leaks subprocesses when killed via a signal. Not sure how to
# remedy. I believe the code is 100% correct. Shell's seem quite buggy in their handling
# and propogating of signals. Not sure how to debug even without something like gdb and
# going through the source code of the shell too.
runjob() {(
jobname=$1
export JOBNAME=${JOBNAME+$JOBNAME/}$jobname
shift
if [ $# -eq 0 ]; then
set "$jobname"
fi
if ! _runjob_filter; then
return 0
fi
should_color || true
export COLOR=$__COLOR
FGCOLOR="$(get_rand_color "$jobname")"
echop "$jobname^" "$*"
# We need to make sure we return with a non zero code if the command fails.
# /bin/sh does not support -o pipefail unfortunately.
job_tmpdir="$(mktempd)"
stdout="$job_tmpdir/stdout"
stderr="$job_tmpdir/stderr"
mkfifo "$stdout"
mkfifo "$stderr"
# We add the prefix to all lines and remove any warning lines about recursive make.
# We cannot silence these with -s which is unfortunate.
(sed -e "s#^#$(echop "$jobname"): #" -e "/make\[.\]: warning: -j/d" "$stdout" || true) &
# This intentionally does not output to our stderr, it becomes our stdout.
(sed -e "s#^#$(echop "$jobname"): #" -e "/make\[.\]: warning: -j/d" "$stderr" || true) &
start="$(awk 'BEGIN{srand(); print srand()}')"
trap runjob_exittrap EXIT
# For some reason without wrapping this in a subshell, the waitjobs in subjob
# case_notequal_sign of ./lib/flags_test.sh freezes.
( eval "$*" >"$stdout" 2>"$stderr" )
)}
_runjob_filter() {
if [ -z "${JOBFILTER-}" ]; then
return 0
fi
tmpdir="$(mktempd)"
# For each slash separated element of $JOBNAME, $JOBFILTER must match at its
# corresponding element. In order to facilitate this, we split $JOBFILTER on / and then
# reconstruct the regex up to the point of each / and match it against $JOBNAME.
# If the constructed regex matches $JOBNAME every iteration until we run out of
# elements in $JOBNAME to match against, then the job is not skipped.
echo "$JOBNAME" | tr / '\n' > "$tmpdir/jobname"
echo "$JOBFILTER" | tr / '\n' > "$tmpdir/jobfilter"
jobname_count=$(<"$tmpdir/jobname" wc -l)
jobfilter_count=$(<"$tmpdir/jobfilter" wc -l)
if [ "$jobname_count" -lt "$jobfilter_count" ]; then
min=$jobname_count
else
min=$jobfilter_count
fi
for i in $(seq "$min"); do
job_el=$(sed -n "${i}p" "$tmpdir/jobname")
regex_el=$(sed -n "${i}p" "$tmpdir/jobfilter")
if ! printf %s "$job_el" | grep -Eq "$regex_el"; then
return 1
fi
done
return 0
}
runjob_filter() {
if ! _runjob_filter; then
return
fi
eval "$*"
}
runjob_exittrap() {
code="$?"
end="$(awk 'BEGIN{srand(); print srand()}')"
dur="$((end - start))"
waitjobs_sigtrap
if [ "$code" -eq 0 ]; then
echop "$jobname\$" "$(setaf 2 success)" "($(echo_dur "$dur"))"
else
echop "$jobname\$" "$(setaf 1 failure)" "($(echo_dur "$dur"))"
fi
}
waitjobs() {
wait_tmpdir="$(mktempd)"
jobs -l > "$wait_tmpdir/jobsl"
trap waitjobs_sigtrap INT TERM
jobs -p > "$wait_tmpdir/jobsp"
for pid in $(cat "$wait_tmpdir/jobsp"); do
if ! wait "$pid"; then
caterr <<EOF
failed to wait on $pid:
$(<"$wait_tmpdir/jobsl" grep "$pid")
EOF
FAILURE=1
fi
done
if [ -n "${FAILURE-}" ]; then
return 1
fi
}
waitjobs_sigtrap() {
for pid in $(jobs -p); do
kill "$pid" 2> /dev/null || true
done
waitjobs
}
job_parseflags() {
while flag_parse "$@"; do
case "$FLAG" in
h|help)
cat <<EOF
usage: $0 [-xd] jobregex
-x
Equivalent to TRACE=1
-d
Equivalent to DRY_RUN=1
EOF
return 1
;;
x)
flag_noarg && shift "$FLAGSHIFT"
set -x
export TRACE=1
;;
d)
flag_noarg && shift "$FLAGSHIFT"
export DRY_RUN=1
;;
*)
flag_errusage "unrecognized flag $FLAGRAW"
;;
esac
done
shift "$FLAGSHIFT"
if [ $# -gt 0 ]; then
JOBFILTER=$(strjoin / "$@")
export JOBFILTER
fi
}
# See https://unix.stackexchange.com/questions/22044/correct-locking-in-shell-scripts
lockfile() {
LOCKFILE=$1
LOCKFILE_PID=$(mktempd)/pid
echo "pid $$" > $LOCKFILE_PID
if [ -n "${LOCKFILE_FORCE-}" ]; then
unlockfile_ssh
fi
if ln "$LOCKFILE_PID" "$LOCKFILE"; then
return 0
else
echoerr "$LOCKFILE locked by $(cat "$LOCKFILE")"
rm "$LOCKFILE_PID"
return 1
fi
trap unlockfile EXIT
}
unlockfile() {
rm -f "$LOCKFILE_PID" "$LOCKFILE"
}
lockfile_ssh() {
LOCKHOST=$1
LOCKFILE=$2
LOCKFILE_PID=$(ssh "$LOCKHOST" mktemp)
if [ -n "${LOCKFILE_FORCE-}" ]; then
unlockfile_ssh
fi
ssh "$LOCKHOST" sh <<EOF
echo "ssh $USER@$(hostname)" > "$LOCKFILE_PID"
EOF
capcode ssh "$LOCKHOST" ln "$LOCKFILE_PID" "$LOCKFILE"
if [ $code -ne 0 ]; then
echoerr "$LOCKFILE locked by $(ssh "$LOCKHOST" cat "$LOCKFILE")"
ssh "$LOCKHOST" rm "$LOCKFILE_PID"
return 1
fi
trap unlockfile_ssh EXIT
}
unlockfile_ssh() {
ssh "$LOCKHOST" sh -s -- <<EOF
rm -f "$LOCKFILE_PID" "$LOCKFILE"
EOF
}
#!/bin/sh
if [ "${LIB_LOG-}" ]; then
return 0
fi
LIB_LOG=1
if [ -n "${TRACE-}" ]; then
set -x
fi
tput() {
if should_color; then
TERM=${TERM:-xterm-256color} command tput "$@"
fi
}
should_color() {
if [ -n "${COLOR-}" ]; then
if [ "$COLOR" = 1 -o "$COLOR" = true ]; then
_COLOR=1
__COLOR=1
return 0
elif [ "$COLOR" = 0 -o "$COLOR" = false ]; then
_COLOR=
__COLOR=0
return 1
else
printf '$COLOR must be 0, 1, false or true but got %s\n' "$COLOR" >&2
fi
fi
if [ -t 1 -a "${TERM-}" != dumb ]; then
_COLOR=1
__COLOR=1
return 0
else
_COLOR=
__COLOR=0
return 1
fi
}
setaf() {
fg=$1
shift
printf '%s\n' "$*" | while IFS= read -r line; do
tput setaf "$fg"
printf '%s' "$line"
tput sgr0
printf '\n'
done
}
_echo() {
printf '%s\n' "$*"
}
get_rand_color() {
if [ "${TERM_COLORS+x}" != x ]; then
TERM_COLORS=""
export TERM_COLORS
ncolors=$(TERM=${TERM:-xterm-256color} command tput colors)
if [ "$ncolors" -ge 8 ]; then
# 1-6 are regular
TERM_COLORS="$TERM_COLORS 1 2 3 4 5 6"
elif [ "$ncolors" -ge 16 ]; then
# 9-14 are bright.
TERM_COLORS="$TERM_COLORS 9 10 11 12 13 14"
fi
fi
pick "$*" $TERM_COLORS
}
echop() {
prefix="$1"
shift
if [ "$#" -gt 0 ]; then
printfp "$prefix" "%s\n" "$*"
else
printfp "$prefix"
printf '\n'
fi
}
printfp() {(
prefix="$1"
shift
_FGCOLOR=${FGCOLOR:-$(get_rand_color "$prefix")}
should_color || true
if [ $# -eq 0 ]; then
printf '%s' "$(COLOR=$__COLOR setaf "$_FGCOLOR" "$prefix")"
else
printf '%s: %s\n' "$(COLOR=$__COLOR setaf "$_FGCOLOR" "$prefix")" "$(printf "$@")"
fi
)}
catp() {
prefix="$1"
shift
should_color || true
sed "s/^/$(COLOR=$__COLOR printfp "$prefix" '')/"
}
repeat() {
char="$1"
times="$2"
seq -s "$char" "$times" | tr -d '[:digit:]'
}
strlen() {
printf %s "$1" | wc -c
}
echoerr() {
FGCOLOR=1 logp err "$*"
}
caterr() {
FGCOLOR=1 logpcat err "$@"
}
printferr() {
FGCOLOR=1 logfp err "$@"
}
logp() {
should_color >&2 || true
COLOR=$__COLOR echop "$@" | humanpath >&2
}
logfp() {
should_color >&2 || true
COLOR=$__COLOR printfp "$@" | humanpath >&2
}
logpcat() {
should_color >&2 || true
COLOR=$__COLOR catp "$@" | humanpath >&2
}
log() {
FGCOLOR=5 logp log "$@"
}
logf() {
FGCOLOR=5 logfp log "$@"
}
logcat() {
FGCOLOR=5 logpcat log "$@"
}
warn() {
FGCOLOR=3 logp warn "$@"
}
warnf() {
FGCOLOR=3 logfp warn "$@"
}
warncat() {
FGCOLOR=3 logpcat warn "$@"
}
sh_c() {
FGCOLOR=3 logp exec "$*"
if [ -z "${DRY_RUN-}" ]; then
eval "$@"
fi
}
sudo_sh_c() {
if [ "$(id -u)" -eq 0 ]; then
sh_c "$@"
elif command -v doas >/dev/null; then
sh_c "doas $*"
elif command -v sudo >/dev/null; then
sh_c "sudo $*"
elif command -v su >/dev/null; then
sh_c "su root -c '$*'"
else
caterr <<EOF
Unable to run the following command as root:
$*
Please install doas, sudo, or su.
EOF
return 1
fi
}
header() {
FGCOLOR=${FGCOLOR:-4} logp "/* $1 */"
}
bigheader() {
set -- "$(echo "$*" | sed "s/^/ * /")"
FGCOLOR=${FGCOLOR:-6} logp "/****************************************************************
$*
****************************************************************/"
}
# humanpath replaces all occurrences of " $HOME" with " ~"
# and all occurrences of '$HOME' with the literal '$HOME'.
humanpath() {
if [ -z "${HOME-}" ]; then
cat
else
sed -e "s# $HOME# ~#g" -e "s#$HOME#\$HOME#g"
fi
}
hide() {
out="$(mktempd)/hideout"
capcode "$@" >"$out" 2>&1
if [ "$code" -eq 0 ]; then
return
fi
cat "$out" >&2
return "$code"
}
hide_stderr() {
out="$(mktempd)/hideout"
capcode "$@" 2>"$out"
if [ "$code" -eq 0 ]; then
return
fi
cat "$out" >&2
return "$code"
}
echo_dur() {
local dur=$1
local h=$((dur/60/60))
local m=$((dur/60%60))
local s=$((dur%60))
printf '%dh%dm%ds' "$h" "$m" "$s"
}
sponge() {
dst="$1"
tmp="$(mktempd)/sponge"
cat > "$tmp"
cat "$tmp" > "$dst"
}
stripansi() {
# First regex gets rid of standard xterm escape sequences for controlling
# visual attributes.
# The second regex I'm not 100% sure, the reference says it selects the US
# encoding but I'm not sure why that's necessary or why it always occurs
# in tput sgr0 before the standard escape sequence.
# See tput sgr0 | xxd
sed -e $'s/\x1b\[[0-9;]*m//g' -e $'s/\x1b(.//g'
}
runtty() {
case "$(uname)" in
Darwin)
script -q /dev/null "$@"
;;
Linux)
script -eqc "$*"
;;
*)
echoerr "runtty: unsupported OS $(uname)"
return 1
esac
}
capcode() {
set +e
"$@"
code=$?
set -e
}
strjoin() {
(IFS="$1"; shift; echo "$*")
}
#!/bin/sh
if [ "${LIB_MAKE-}" ]; then
return 0
fi
LIB_MAKE=1
_make() {
if [ -n "${CI-}" ] && ! is_changed .; then
return
fi
if [ -z "${CI_MAKE_ROOT-}" ]; then
export CI_MAKE_ROOT=1
else
export CI_MAKE_ROOT=0
fi
ensure_git_base
capcode make -sj8 "$@"
if [ "$code" != 0 ]; then
notify
return "$code"
fi
ci_waitjobs
}
#!/bin/sh
if [ "${LIB_MISC-}" ]; then
return 0
fi
LIB_MISC=1
docker_run() {
sh_c docker run --rm \
-v "$HOME:$HOME" \
-w "$HOME" \
-e HOME \
-e TERM \
-e COLOR \
-u "$(id -u):$(id -g)" \
"$@"
}
pandoc_toc() {
pandoc --wrap=none -s --toc --from gfm --to gfm | awk '/-/{f=1} {if (!NF) exit; print}'
}
mdtocsubst_help() {
cat <<EOF
usage: mdtocsubst [--skip n] README.md ...
EOF
}
mdtocsubst() {
while flag_parse "$@"; do
case "$FLAG" in
h|help)
mdtocsubst_help
return 1
;;
skip)
flag_nonemptyarg && shift "$FLAGSHIFT"
SKIP=$FLAGARG
;;
*)
flag_errusage "unrecognized flag $FLAGRAW"
;;
esac
done
shift "$FLAGSHIFT"
SKIP=${SKIP:-1}
if [ $# -eq 0 ]; then
flag_errusage "At least one input file is required."
return 1
fi
while [ $# -gt 0 ]; do