-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbake
More file actions
executable file
·679 lines (575 loc) · 16.6 KB
/
bake
File metadata and controls
executable file
·679 lines (575 loc) · 16.6 KB
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
#!/usr/bin/env bash
# SPDX-License-Identifier: BSD-3-Clause
# SPDX-FileCopyrightText: Copyright 2023 Edwin Kofler and contributors
# @name Bake
# @brief Bake: A Bash-based Make alternative
# @description Bake is a dead-simple task runner used to quickly cobble together shell scripts
#
# In a few words, Bake lets you call the following 'print' task with './bake print'
#
# ```bash
# #!/usr/bin/env bash
# task.print() {
# printf '%s\n' 'Contrived example'
# }
# ```
#
# Learn more about it [on GitHub](https://github.com/hyperupcall/bake)
__global_bake_version='2.0.0-rc1+dev'
# Return early if only the version is needed. This improves performance
if [ "$BAKE_INTERNAL_ONLY_VERSION" = 'yes' ]; then
return 0
fi
# Source guard
if [ "$0" != "${BASH_SOURCE[0]}" ] && [ "$BAKE_INTERNAL_CAN_SOURCE" != 'yes' ]; then
printf '%s\n' 'Error: This file should not be sourced' >&2
return 1
fi
# @description Prints `$1` formatted as an error and the stacktrace to standard error,
# then exits with code 1
# @arg $1 string Text to print
bake.die() {
if [ -n "$1" ]; then
__bake_error "$1. Exiting"
else
__bake_error 'Exiting'
fi
__bake_print_big --show-time '<- ERROR'
__bake_print_stacktrace
exit 1
}
# @description Prints `$1` formatted as a warning to standard error
# @arg $1 string Text to print
bake.warn() {
if __bake_is_color; then
printf "\033[1;33m%s:\033[0m %s\n" 'Warn' "$1"
else
printf '%s: %s\n' 'Warn' "$1"
fi
} >&2
# @description Prints `$1` formatted as information to standard output
# @arg $1 string Text to print
bake.info() {
if __bake_is_color; then
printf "\033[0;34m%s:\033[0m %s\n" 'Info' "$1"
else
printf '%s: %s\n' 'Info' "$1"
fi
}
# @description Dies if any of the supplied variables are empty
# @arg $@ string Names of variables to check for emptiness
bake.assert_not_empty() {
local variable_name=
for variable_name; do
local -n ____variable="$variable_name"
if [ -z "$____variable" ]; then
bake.die "Failed because variable '$variable_name' is empty"
fi
done; unset -v variable_name
}
# @description Dies if a command cannot be found
# @arg $1 string Command name to test for existence
bake.assert_cmd() {
local cmd=$1
if [ -z "$cmd" ]; then
bake.die "Argument must not be empty"
fi
if ! command -v "$cmd" &>/dev/null; then
bake.die "Failed to find command '$cmd'. Please install it before continuing"
fi
}
# @description Determine if a flag was passed as an argument
# @arg $1 string Flag name to test for
# @arg $@ string Rest of the arguments to search through
bake.has_flag() {
local flag_name="$1"
if [ -z "$flag_name" ]; then
bake.die "Argument must not be empty"
fi
if ! shift; then
bake.die 'Failed to shift'
fi
local -a flags=("$@")
if ((${#flags[@]} == 0)); then
flags=("${__bake_args_userflags[@]}")
fi
local arg=
for arg in "${flags[@]}"; do
if [ "$arg" = "$flag_name" ]; then
return 0
fi
done; unset -v arg
return 1
}
# @description Prints stacktrace
# @internal
__bake_print_stacktrace() {
if [ "${__bake_config_map[stacktrace]}" = 'on' ]; then
if __bake_is_color; then
printf '\033[4m%s\033[0m\n' 'Stacktrace:'
else
printf '%s\n' 'Stacktrace:'
fi
local i=
for ((i=0; i<${#FUNCNAME[@]}-1; ++i)); do
local __bash_source="${BASH_SOURCE[$i]}"; __bash_source=${__bash_source##*/}
printf '%s\n' " in ${FUNCNAME[$i]} ($__bash_source:${BASH_LINENO[$i-1]})"
done; unset -v i __bash_source
fi
} >&2
# @description Function that is executed when the 'ERR' event is trapped
# @internal
__bake_trap_err() {
local error_code=$?
__bake_print_big --show-time '<- ERROR'
__bake_internal_error "Your Bakefile did not exit successfully (exit code $error_code)"
__bake_print_stacktrace
exit $error_code
} >&2
# @description Test whether color should be outputed
# @exitcode 0 if should print color
# @exitcode 1 if should not print color
# @internal
__bake_is_color() {
local fd="1"
if [ ${NO_COLOR+x} ]; then
return 1
fi
case $FORCE_COLOR in
1|2|3)
return 0 ;;
0)
return 1 ;;
esac
if [ "$TERM" = 'dumb' ]; then
return 1
fi
if [ -t "$fd" ]; then
return 0
fi
return 1
}
# @description Calls `__bake_internal_error` and terminates with code 1
# @arg $1 string Text to print
# @internal
__bake_internal_die() {
__bake_internal_error "$1. Exiting"
exit 1
}
# @description Prints `$1` formatted as an internal Bake error to standard error
# @arg $1 Text to print
# @internal
__bake_internal_error() {
if __bake_is_color; then
printf "\033[0;31m%s:\033[0m %s\n" "Error (bake)" "$1"
else
printf '%s: %s\n' 'Error (bake)' "$1"
fi
} >&2
# @description Prints `$1` formatted as an internal Bake warning to standard error
# @arg $1 Text to print
# @internal
__bake_internal_warn() {
if __bake_is_color; then
printf "\033[0;33m%s:\033[0m %s\n" "Warn (bake)" "$1"
else
printf '%s: %s\n' 'Warn (bake)' "$1"
fi
} >&2
# @description Prints `$1` formatted as an error to standard error. This is not called because
# I do not wish to surface a public 'bake.error' function. All errors should halt execution
# @arg $1 string Text to print
# @internal
__bake_error() {
if __bake_is_color; then
printf "\033[0;31m%s:\033[0m %s\n" 'Error' "$1"
else
printf '%s: %s\n' 'Error' "$1"
fi
} >&2
# @description Prepares internal variables for time setting
# @internal
__bake_time_prepare() {
if ((BASH_VERSINFO[0] >= 5)); then
__bake_global_timestart=$EPOCHREALTIME
fi
}
# @description Determines total approximate execution time of a task
# @set string REPLY
# @internal
__bake_time_get_total_pretty() {
unset -v REPLY; REPLY=
if [ -z "$__bake_global_timestart" ]; then
return 0
fi
if ((BASH_VERSINFO[0] >= 5)); then
local cur_time=$EPOCHREALTIME
local seconds_diff=$((${cur_time%.*} - ${__bake_global_timestart%.*}))
local seconds=$((seconds_diff % 60))
local useconds=$((10#${cur_time#*.} - 10#${__bake_global_timestart#*.}))
if ((useconds < 0)); then
useconds=$((useconds + 1000000))
seconds=$((seconds - 1))
fi
if ((seconds_diff < 15)); then
if ((${#useconds} > 3)); then
REPLY="${seconds}s ${useconds::-3}ms"
else
REPLY="${seconds}s ${useconds}us"
fi
return 0
fi
local minutes=$((seconds_diff / 60 % 60))
local hours=$((seconds_diff / 3600 % 60))
REPLY="${seconds}s"
if ((minutes > 0)); then
REPLY="${minutes}m $REPLY"
fi
if ((hours > 0)); then
REPLY="${hours}h $REPLY"
fi
fi
}
# @description Parses the configuration for functions embeded in comments. This properly
# parses inherited config from the 'init' function
# @set string __bake_config_docstring
# @set array __bake_config_watchexec_args
# @set object __bake_config_map
# @internal
__bake_parse_task_comments() {
local flag_all=
if [ "$1" == '--all' ]; then
flag_all='yes'
local fn="$2"
else
local task_name="$1"
fi
local tmp_docstring=
local -a tmp_watch_args=()
local -A tmp_cfg_map=()
local line=
while IFS= read -r line || [ -n "$line" ]; do
if [[ $line =~ ^[[:space:]]*#[[:space:]]*(doc|watch|config):[[:space:]]*(.*?)$ ]]; then
local comment_category="${BASH_REMATCH[1]}"
local comment_content="${BASH_REMATCH[2]}"
if [[ $comment_category == 'config' && $comment_content == *,* ]]; then
__bake_internal_warn "Use spaces as delimiters rather than commas"
fi
if [ "$comment_category" = 'doc' ]; then
tmp_docstring=$comment_content
elif [ "$comment_category" = 'watch' ]; then
readarray -td' ' tmp_watch_args <<< "$comment_content"
tmp_watch_args[-1]=${tmp_watch_args[-1]::-1}
elif [ "$comment_category" = 'config' ]; then
local -a pairs=()
readarray -td' ' pairs <<< "$comment_content"
pairs[-1]=${pairs[-1]::-1}
# shellcheck disable=SC1007
local pair= key= value=
for pair in "${pairs[@]}"; do
IFS='=' read -r key value <<< "$pair"
tmp_cfg_map[$key]=${value:-on}
done; unset -v pair
fi
fi
# function()
if [[ $line =~ ^([[:space:]]*function[[:space:]]*)?(.*?)[[:space:]]*\(\)[[:space:]]*\{ ]]; then
local function_name="${BASH_REMATCH[2]}"
if [ "$flag_all" = 'yes' ]; then
"$fn" "$function_name"
else
if [ "$function_name" == task."$task_name" ]; then
__bake_config_docstring=$tmp_docstring
__bake_config_watchexec_args+=("${tmp_watch_args[@]}")
local key=
for key in "${!tmp_cfg_map[@]}"; do
__bake_config_map[$key]=${tmp_cfg_map[$key]}
done; unset -v key
break
# TODO: only do this if not overriding (init function could be after tasks)
elif [ "$function_name" == 'init' ]; then
__bake_config_watchexec_args+=("${tmp_watch_args[@]}")
local key=
for key in "${!tmp_cfg_map[@]}"; do
__bake_config_map[$key]=${tmp_cfg_map[$key]}
done; unset -v key
fi
tmp_docstring=
tmp_watch_args=()
tmp_cfg_map=()
fi
fi
done < "$BAKE_FILE"; unset -v line
}
# @description Nicely prints all 'Bakefile.sh' tasks to standard output
# @internal
__bake_print_tasks() {
local str=$'Tasks:\n'
__bake_parse_task_comments --all '__bake_print_tasks_handler'
printf '%s' "$str"
} >&2
# @internal
__bake_print_tasks_handler() {
local fn_name="$1"
if [[ "$fn_name" =~ task.(.*) ]]; then
local task_name="${BASH_REMATCH[1]}"
str+=" -> $task_name ($tmp_docstring)"$'\n'
fi
}
# @description Prints text that takes up the whole terminal width
# @arg $1 string Text to print
# @internal
__bake_print_big() {
if [ "${__bake_config_map[big-print]}" = 'off' ]; then
return 0
fi
if [ "$1" = '--show-time' ]; then
local flag_show_time='yes'
local print_text="$2"
else
local flag_show_time='no'
local print_text="$1"
fi
__bake_time_get_total_pretty
local time_str="${REPLY:+ ($REPLY) }"
# shellcheck disable=SC1007
local output= _stty_width=
if output=$(stty size 2>&1); then
_stty_width=${output##* }
else
if [ -n "$COLUMNS" ]; then
_stty_width="$COLUMNS"
else
_stty_width='80'
fi
fi; unset -v output
local separator_text=
# shellcheck disable=SC2183
printf -v separator_text '%*s' $((_stty_width - ${#print_text} - 1))
printf -v separator_text '%s' "${separator_text// /=}"
if [[ "$flag_show_time" == 'yes' && -n "$time_str" ]]; then
separator_text="${separator_text::5}${time_str}${separator_text:5+${#time_str}:${#separator_text}}"
fi
if __bake_is_color; then
printf '\033[1m%s %s\033[0m\n' "$print_text" "$separator_text" >&2
else
printf '%s %s\n' "$print_text" "$separator_text" >&2
fi
}
# @description Parses the arguments. This also includes setting the the 'BAKE_ROOT'
# and 'BAKE_FILE' variables
# @set REPLY Number of times to shift
# @internal
__bake_parse_args() {
unset -v REPLY; REPLY=
local -i total_shifts=0
if [ "$BAKE_INTERNAL_HAS_PARSED_ARGS" = 'yes' ]; then
REPLY=$total_shifts
return
fi
# shellcheck disable=SC1007
local __bake_key= __bake_value= __bake_arg= __bake_flag_help=
for __bake_arg; do case $__bake_arg in
-f?*)
bake.die "Flag '-f' must be specified after all other flags"
;;
-*)
((total_shifts += 1))
if ! shift; then
__bake_internal_die 'Failed to shift'
fi
if [[ $__bake_arg == -*f* ]]; then
BAKE_FILE=$1
if [ -z "$BAKE_FILE" ]; then
__bake_internal_die "A value was not specified for for flag '-f'"
fi
((total_shifts += 1))
if ! shift; then
__bake_internal_die 'Failed to shift'
fi
if [ ! -e "$BAKE_FILE" ]; then
__bake_internal_die "Specified file '$BAKE_FILE' does not exist"
fi
if [ ! -f "$BAKE_FILE" ]; then
__bake_internal_die "Specified file '$BAKE_FILE' is not actually a file"
fi
fi
if [[ $__bake_arg == -*h* ]]; then
__bake_flag_help='yes'
fi
if [[ $__bake_arg == -*u* ]]; then
BAKE_INTERNAL_FLAG_UPDATE='yes'
fi
if [[ $__bake_arg == -*v* ]]; then
printf '%s\n' "Version: $__global_bake_version"
exit 0
fi
if [[ $__bake_arg == -*w* ]]; then
if [[ ! -v 'BAKE_INTERNAL_NO_WATCH_OVERRIDE' ]]; then
BAKE_INTERNAL_FLAG_WATCH='yes'
fi
fi
;;
*=*)
# Set variables à la Make
IFS='=' read -r __bake_key __bake_value <<< "$__bake_arg"
if [ "${__bake_key^^}" = "$__bake_key" ]; then
# If 'KEY=value' is passed, create global variable $KEY
declare -g "$__bake_key"
local -n __bake_variable="$__bake_key"
__bake_variable="$__bake_value"
else
# If 'key=value' is passed, create global variable $var_key
# Applies to other non-caps keys like 'Key' and 'kEy' as well
declare -g "var_$__bake_key"
local -n __bake_variable="var_$__bake_key"
__bake_variable="$__bake_value"
fi
((total_shifts += 1))
if ! shift; then
__bake_internal_die 'Failed to shift'
fi
;;
*)
break
;;
esac done; unset -v __bake_arg
unset -v __bake_key __bake_value
unset -vn __bake_variable
if [ -n "$BAKE_FILE" ]; then
BAKE_ROOT=$(
# shellcheck disable=SC1007
CDPATH= cd -- "${BAKE_FILE%/*}"
printf '%s\n' "$PWD"
)
BAKE_FILE="$BAKE_ROOT/${BAKE_FILE##*/}"
else
if BAKE_ROOT=$(
while [ ! -f './Bakefile.sh' ] && [ "$PWD" != / ]; do
if ! cd ..; then
exit 1
fi
done
if [ "$PWD" = / ]; then
exit 1
fi
printf '%s' "$PWD"
); then
BAKE_FILE="$BAKE_ROOT/Bakefile.sh"
elif [ -f "${__bake_script%/*}/Bakefile.sh" ]; then
BAKE_FILE="${__bake_script%/*}/Bakefile.sh"
BAKE_ROOT="${__bake_script%/*}"
else
__bake_internal_die "Failed to find 'Bakefile.sh'"
fi
fi
# This is at the end so 'BAKE_*' variables are set properly
if [ "$__bake_flag_help" = 'yes' ]; then
printf '%s\n' 'Usage: bake [-h|-v] [-u|-w] [-f <Bakefile>] [var=value ...] <task> [args ...]' >&2
__bake_print_tasks
exit
fi
REPLY=$total_shifts
}
# @description Main function
# @internal
__bake_main() {
declare -ga __bake_args_original=("$@")
# Parse arguments
__bake_parse_args "$@"
if ! shift $REPLY; then
__bake_internal_die 'Failed to shift'
fi
local __bake_task="$1"
if [ -z "$__bake_task" ]; then
__bake_internal_error 'No valid task supplied'
__bake_print_tasks
exit 1
fi
if ! shift; then
__bake_internal_die 'Failed to shift'
fi
declare -ga __bake_args_userflags=("$@")
declare -g __bake_config_docstring=
declare -ga __bake_config_watchexec_args=()
declare -gA __bake_config_map=(
[big-print]='on'
[stacktrace]='off'
)
# watchexec
if [ "$BAKE_INTERNAL_FLAG_WATCH" = 'yes' ]; then
if ! command -v watchexec &>/dev/null; then
__bake_internal_die "Executable not found: 'watchexec'"
fi
__bake_parse_task_comments "$__bake_task"
# shellcheck disable=SC1007
BAKE_INTERNAL_NO_WATCH_OVERRIDE= exec watchexec "${__bake_config_watchexec_args[@]}" "$BAKE_ROOT/bake" -- "${__bake_args_original[@]}"
fi
# start
if ! cd -- "$BAKE_ROOT"; then
__bake_internal_die "Failed to cd"
fi
# shellcheck disable=SC2097,SC1007,SC1090
__bake_task= source "$BAKE_FILE"
if declare -f task."$__bake_task" >/dev/null 2>&1; then
__bake_parse_task_comments "$__bake_task"
__bake_print_big "-> RUNNING TASK '$__bake_task'"
__bake_time_prepare
if declare -f init >/dev/null 2>&1; then
init "$__bake_task"
fi
# Do NOT 'if task.*; then :; else handleIt; fi'
task."$__bake_task" "${__bake_args_userflags[@]}"
__bake_print_big --show-time "<- DONE"
exit 0
else
__bake_internal_error "Task '$__bake_task' not found"
__bake_print_tasks
exit 1
fi
}
__bake_entrypoint() {
# Environment boilerplate
set -ETeo pipefail
shopt -s dotglob extglob globasciiranges globstar lastpipe shift_verbose
if ((BASH_VERSINFO[0] >= 6 || (BASH_VERSINFO[0] == 5 && BASH_VERSINFO[1] >= 2))); then
shopt -s noexpand_translation
fi
export LANG='C' LC_CTYPE='C' LC_NUMERIC='C' LC_TIME='C' LC_COLLATE='C' \
LC_MONETARY='C' LC_MESSAGES='C' LC_PAPER='C' LC_NAME='C' LC_ADDRESS='C' \
LC_TELEPHONE='C' LC_MEASUREMENT='C' LC_IDENTIFICATION='C' LC_ALL='C'
trap '__bake_trap_err' 'ERR'
trap ':' 'INT' # Ensure Ctrl-C ends up printing <- ERROR ==== etc.
local __bake_script=
# shellcheck disable=SC1007
__bake_script="$(CDPATH= cd -- "$(dirname "$0")" && printf '%s\n' "$PWD")/bake"
# Argument parsing
# shellcheck disable=SC2034
declare -g BAKE_{FILE,ROOT}= BAKE_OLDPWD="$PWD" BAKE_INTERNAL_{FLAG_UPDATE,FLAG_WATCH}=
__bake_parse_args "$@"
if ! shift $REPLY; then
__bake_internal_die 'Failed to shift'
fi
declare -g BAKE_INTERNAL_HAS_PARSED_ARGS='yes'
# If invoking like "./bake" (or "../bake").
if [ "$__bake_script" = "$BAKE_ROOT/bake" ]; then
if [ "$BAKE_INTERNAL_FLAG_UPDATE" = 'yes' ]; then
__bake_internal_die "Refusing to copy itself"
fi
__bake_main "$@"
# If invoking like "~/bin/bake".
else
if [[ "$BAKE_INTERNAL_FLAG_UPDATE" = 'yes' || ! -f "$BAKE_ROOT/bake" ]]; then
if ! cp -f "$__bake_script" "$BAKE_ROOT/bake"; then
__bake_internal_die "Failed to copy bake script"
fi
if ! chmod +x "$BAKE_ROOT/bake"; then
__bake_internal_die "Failed to 'chmod +x' bake script" >&2
fi
__bake_main "$@"
return
fi
exec "$BAKE_ROOT/bake" "$@"
fi
}
__bake_entrypoint "$@"