/
bash-tpl
executable file
·1298 lines (1192 loc) · 33.2 KB
/
bash-tpl
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
#######################################################################
# SPDX-License-Identifier: MIT
# Copyright (c) 2021 TekWizely & co-authors
#
# Use of this source code is governed by the MIT license.
# See the accompanying LICENSE file, if present, or visit:
# https://opensource.org/licenses/MIT
#######################################################################
VERSION="v0.7.1"
#######################################################################
# Bash-TPL: A Smart, Lightweight shell script templating engine
#
# Lets you mark up textual files with shell commands and variable
# replacements, while minimally impacting your original file layout.
#
# Templates are compiled into shell scripts that you can invoke
# (along with variables, arguments, etc.) to generate complete and
# well-formatted output text files.
#
# Smart
#
# Encourages you to use extra indentation to write clean, well-
# formatted templates, and smartly removes the indentations from the
# generated template scripts.
#
# This results in both templates that are easily readable and
# maintainable, and generated text files that look as good as if they
# were written by hand.
#
# NOTE: Consistent Formatting
#
# The key to success with Bash-TPL indentation fix-up logic is
# Consistent Formatting; using consistent indentation throughout your
# template will yield best results.
#
# Learn More:
# https://github.com/TekWizely/bash-tpl
#######################################################################
function usage() {
cat << USAGE
Bash-TPL is a smart, lightweight shell script templating engine
usage: bash-tpl [flags] [--] file
bash-tpl [flags] -
cat file | bash-tpl [flags]
options:
-h, --help
show help screen
--version
show version
-o, --output-file <filename>
write to specified file (default: stdout)
-- treat remaining options as positional arguments
- read from stdin
customize delimiters:
--tag-delims 'xx xx'
set tag delimiters (default: '<% %>')
--tag-stmt-delim 'x'
set tag statement delimiter (default: '%')
--stmt-delim 'x+'
set statement delimiter (default: '%')
--stmt-block-delims 'x+ x+'
set statement block delimiters
defaults to statement delimiter if not explicitly set
--txt-delim
--text-delim 'x+[ ]?' (single trailing space allowed)
set text delimiter (default: '% ')
--dir-delim
--directive-delim 'x+'
set directive delimiter (default: '.')
--cmt-delim
--comment-delim 'x+'
set template comment delimiter
defaults to directive delimiter + '#' if not explicitly set
--reset-delims
reset all delimiters to defaults
delim options provided after this option are honored
supported environment variables:
BASH_TPL_TAG_DELIMS
BASH_TPL_TAG_STMT_DELIM
BASH_TPL_STMT_DELIM
BASH_TPL_STMT_BLOCK_DELIMS
BASH_TPL_TEXT_DELIM
BASH_TPL_DIR_DELIM
BASH_TPL_CMT_DELIM
example:
$ echo 'Hello <% \$NAME %>' > test.tpl
$ NAME="Chuck Norris" source <( bash-tpl test.tpl )
Hello Chuck Norris
learn more: https://github.com/TekWizely/bash-tpl
USAGE
}
#######################################################################
# Delim Functions
#######################################################################
TAG_DELIM_REGEX='^([^[:blank:]])([^[:blank:]]) ([^[:blank:]])([^[:blank:]])$'
TAG_STMT_DELIM_REGEX='^([^[:blank:]])$'
STMT_DELIM_REGEX='^([^[:blank:]]+)$'
STMT_BLOCK_DELIM_REGEX='^([^[:blank:]]+) ([^[:blank:]]+)$'
STMT_BLOCK_TEXT_REGEX='^([^[:blank:]]+\ ?)$' # Optional trailing ' '
##
# reset_delims
#
function reset_delims() {
TAG_START_DELIM1='<'
TAG_START_DELIM2='%'
TAG_STOP_DELIM1='%'
TAG_STOP_DELIM2='>'
TAG_STMT_DELIM='%'
STMT_DELIM='%'
TEXT_DELIM_UNDEFINED=1
TEXT_DELIM=''
STMT_BLOCK_DELIM_UNDEFINED=1
STMT_BLOCK_START_DELIM=''
STMT_BLOCK_STOP_DELIM=''
DIRECTIVE_DELIM='.'
COMMENT_DELIM_UNDEFINED=1
COMMENT_DELIM=''
}
##
# parse_tag_delims
# $1 = delims
# $2 = src (for error msg)
#
function parse_tag_delims() {
if [[ "${1}" =~ $TAG_DELIM_REGEX ]]; then
TAG_START_DELIM1="${BASH_REMATCH[1]}"
TAG_START_DELIM2="${BASH_REMATCH[2]}"
TAG_STOP_DELIM1="${BASH_REMATCH[3]}"
TAG_STOP_DELIM2="${BASH_REMATCH[4]}"
else
echo "Error: Invalid or missing tag delimiter values for ${2-tag delims}: '${1}'" >&2
exit 1
fi
}
##
# parse_tag_stmt_delims
# $1 = delim
# $2 = src (for error msg)
#
function parse_tag_stmt_delim() {
if [[ "${1}" =~ $TAG_STMT_DELIM_REGEX ]]; then
TAG_STMT_DELIM="${BASH_REMATCH[1]}"
else
echo "Error: Invalid or missing tag stmt delimiter value for ${2-tag stmt delim}: '${1}'" >&2
exit 1
fi
}
##
# parse_stmt_delim
# $1 = delim
# $2 = src (for error msg)
#
function parse_stmt_delim() {
if [[ "${1}" =~ $STMT_DELIM_REGEX ]]; then
STMT_DELIM="${BASH_REMATCH[1]}"
else
echo "Error: Invalid or missing stmt delimiter value for ${2:-stmt delim}: '${1}'" >&2
exit 1
fi
}
##
# parse_stmt_block_delims
# $1 = delims
# $2 = src (for error msg)
#
function parse_stmt_block_delims() {
if [[ "${1}" =~ $STMT_BLOCK_DELIM_REGEX ]]; then
STMT_BLOCK_START_DELIM="${BASH_REMATCH[1]}"
STMT_BLOCK_STOP_DELIM="${BASH_REMATCH[2]}"
STMT_BLOCK_DELIM_UNDEFINED=''
else
echo "Error: Invalid or missing stmt-block delimiter values for ${2:-stmt-block delims}: '${1}'" >&2
exit 1
fi
}
##
# parse_text_delim - Uses STMT delim regex
# $1 = delim
# $2 = src (for error msg)
#
function parse_text_delim() {
if [[ "${1}" =~ $STMT_BLOCK_TEXT_REGEX ]]; then
TEXT_DELIM="${1}"
TEXT_DELIM_UNDEFINED=''
else
echo "Error: Invalid or missing text delimiter value for ${2:-txt delim}: '${1}'" >&2
exit 1
fi
}
##
# parse_directive_delim - Uses STMT delim regex
# $1 = delim
# $2 = src (for error msg)
#
function parse_directive_delim() {
if [[ "${1}" =~ $STMT_DELIM_REGEX ]]; then
DIRECTIVE_DELIM="${1}"
else
echo "Error: Invalid or missing directive delimiter value for ${2:-dir delim}: '${1}'" >&2
exit 1
fi
}
##
# parse_comment_delim - Uses STMT delim regex
# $1 = delim
# $2 = src (for error msg)
#
function parse_comment_delim() {
if [[ "${1}" =~ $STMT_DELIM_REGEX ]]; then
COMMENT_DELIM="${1}"
COMMENT_DELIM_UNDEFINED=''
else
echo "Error: Invalid or missing comment delimiter value for ${2:-cmt delim}: '${1}'" >&2
exit 1
fi
}
##
# reset_template_regexes
#
function reset_template_regexes() {
# Fixup STMT_BLOCK delims - Default to STMT_DELIM if not set
#
if [[ -n "${STMT_BLOCK_DELIM_UNDEFINED}" ]]; then
STMT_BLOCK_START_DELIM="${STMT_DELIM}"
STMT_BLOCK_STOP_DELIM="${STMT_DELIM}"
fi
# Fixup TEXT delim - Default to STMT_DELIM followed by ' ' if not set
#
if [[ -n "${TEXT_DELIM_UNDEFINED}" ]]; then
TEXT_DELIM="${STMT_DELIM} " # Note trailing space (' ')
fi
# Fixup COMMENT delim - Default to STMT_DELIM followed by '#' if not set
#
if [[ -n "${COMMENT_DELIM_UNDEFINED}" ]]; then
COMMENT_DELIM="${STMT_DELIM}#"
fi
#
# Create regexes
#
local d ds d1 d2 d3 d4
d="${DIRECTIVE_DELIM}"
escape_regex d
DIRECTIVE_REGEX="^([[:blank:]]*)${d}([a-zA-Z_-]+)(.*)\$"
d="${COMMENT_DELIM}"
escape_regex d
COMMENT_REGEX="^([[:blank:]]*)${d}"
d="${STMT_DELIM}"
escape_regex d
STATEMENT_REGEX="^([[:blank:]]*)${d}[[:blank:]]+(.+)\$"
d="${STMT_BLOCK_START_DELIM}"
escape_regex d
STATEMENT_BLOCK_START_REGEX="^([[:blank:]]*)${d}[[:blank:]]*\$"
d="${STMT_BLOCK_STOP_DELIM}"
escape_regex d
STATEMENT_BLOCK_STOP_REGEX="^([[:blank:]]*)${d}[[:blank:]]*\$"
d="${TEXT_DELIM}"
escape_regex d
STATEMENT_BLOCK_TEXT_REGEX="^([[:blank:]]*)${d}([[:blank:]]*[^[:blank:]](.*))\$"
TEXT_REGEX='^([[:blank:]]*)([^[:blank:]](.*))?$'
d1="${TAG_START_DELIM1}"
escape_regex d1
d2="${TAG_START_DELIM2}"
escape_regex d2
d3="${TAG_STOP_DELIM1}"
escape_regex d3
d4="${TAG_STOP_DELIM2}"
escape_regex d4
ds="${TAG_STMT_DELIM}"
escape_regex ds
TAG_TEXT_REGEX="^([^${d1}]+|${d1}$|${d1}[^${d1}${d2}]+)(.*)"
TAG_STD_REGEX="^${d1}${d2}((([^${d3}])|(${d3}[^${d4}]))*)${d3}${d4}(.*)"
TAG_QUOTE_REGEX="^${d1}${d2}\"((([^\"])|(\"[^${d3}])|(\"${d3}[^${d4}]))*)\"${d3}${d4}(.*)"
TAG_STATEMENT_REGEX="^${d1}${d2}${ds}((([^${d3}])|(${d3}[^${d4}]))*)${d3}${d4}(.*)"
# printf "# ---> delim regexes:"
# printf "# STATEMENT_BLOCK_START_REGEX: '%s'\n" "${STATEMENT_BLOCK_START_REGEX}"
# printf "# STATEMENT_BLOCK_STOP_REGEX: '%s'\n" "${STATEMENT_BLOCK_STOP_REGEX}"
# printf "# COMMENT_REGEX: '%s'\n" "${COMMENT_REGEX}"
# printf "# DIRECTIVE_REGEX: '%s'\n" "${DIRECTIVE_REGEX}"
# printf "# STATEMENT_REGEX: '%s'\n" "${STATEMENT_REGEX}"
# printf "# TAG_TEXT_REGEX: '%s'\n" "${TAG_TEXT_REGEX}"
# printf "# TAG_STD_REGEX: '%s'\n" "${TAG_STD_REGEX}"
# printf "# TAG_QUOTE_REGEX: '%s'\n" "${TAG_QUOTE_REGEX}"
# printf "# TAG_STATEMENT_REGEX: '%s'\n" "${TAG_STATEMENT_REGEX}"
}
#######################################################################
# Misc Functions
#######################################################################
##
# trim
# usage: trim varname
# NOTE: Expects value to NOT contain '\n'
#
function trim() {
read -r "$1" <<< "${!1}"$'\n'
}
##
# escape_regex
# usage: escape_regex varname
#
function escape_regex() {
local result
# shellcheck disable=SC2001 # Too complex for ${variable//search/replace}
# shellcheck disable=SC2016 # Not using expansion, prefer single quotes
# shellcheck disable=SC2034 # ref is used
result=$(sed 's/[][\.|$(){}?+*^]/\\&/g' <<< "${!1}")
printf -v "${1}" "%s" "${result}"
}
##
# normalize_directive
# usage: normalize_directive varname
#
function normalize_directive() {
local result
# shellcheck disable=SC2034 # ref is used
result=$(tr 'a-z_' 'A-Z-' <<< "${!1}")
printf -v "${1}" "%s" "${result}"
}
#######################################################################
# STATES
#######################################################################
STATES=() # empty => DEFAULT
STATE="DEFAULT" # [ DEFAULT, MAYBE_TXT_BLOCK, TXT_BLOCK, START_STMT_BLOCK, STMT_BLOCK ]
##
# push_state
#
function push_state() {
STATES+=("${STATE}")
STATE="${1}"
}
##
# pop_state
#
function pop_state() {
if [[ ${#STATES[@]} -gt 0 ]]; then
STATE="${STATES[${#STATES[@]} - 1]}"
unset "STATES[${#STATES[@]}-1]"
else
STATE="DEFAULT"
fi
}
#######################################################################
# TEXT_INDENTS
#######################################################################
TEXT_INDENTS=() # empty => ""
TEXT_INDENT=""
##
# push_text_indent
#
function push_text_indent() {
TEXT_INDENTS+=("${TEXT_INDENT}")
TEXT_INDENT="${1}"
}
##
# pop_text_indent
#
function pop_text_indent() {
if [[ ${#TEXT_INDENTS[@]} -gt 0 ]]; then
TEXT_INDENT="${TEXT_INDENTS[${#TEXT_INDENTS[@]} - 1]}"
unset "TEXT_INDENTS[${#TEXT_INDENTS[@]} - 1]"
else
TEXT_INDENT=""
fi
}
#######################################################################
# STATEMENT_INDENTS
#######################################################################
STATEMENT_INDENTS=() # empty => ""
STATEMENT_INDENT=""
##
# push_statement_indent
#
function push_statement_indent() {
STATEMENT_INDENTS+=("${STATEMENT_INDENT}")
STATEMENT_INDENT="${1}"
}
##
# pop_statement_indent
#
function pop_statement_indent() {
if [[ ${#STATEMENT_INDENTS[@]} -gt 0 ]]; then
STATEMENT_INDENT="${STATEMENT_INDENTS[${#STATEMENT_INDENTS[@]} - 1]}"
unset "STATEMENT_INDENTS[${#STATEMENT_INDENTS[@]} - 1]"
else
STATEMENT_INDENT=""
fi
}
#######################################################################
# BLOCK_INDENTS
#######################################################################
BLOCK_INDENTS=() # empty => ""
BLOCK_INDENT=""
##
# push_block_indent
#
function push_block_indent() {
BLOCK_INDENTS+=("${BLOCK_INDENT}")
BLOCK_INDENT="${1}"
}
##
# pop_block_indent
#
function pop_block_indent() {
if [[ ${#BLOCK_INDENTS[@]} -gt 0 ]]; then
BLOCK_INDENT="${BLOCK_INDENTS[${#BLOCK_INDENTS[@]} - 1]}"
unset "BLOCK_INDENTS[${#BLOCK_INDENTS[@]} - 1]"
else
BLOCK_INDENT=""
fi
}
#######################################################################
# Print Functions
#######################################################################
##
# print_statement
# $1 = leading indentation
# $2 = statement
#
function print_statement() {
local indent="${1}"
if [[ "${indent}" == "${BLOCK_INDENT}"* ]]; then
indent="${indent/#$BLOCK_INDENT/}"
fi
printf "%s\n" "${BASE_STMT_INDENT}${STATEMENT_INDENT}${indent}${2}"
}
##
# print_text - generates a printf statement for template text
# $1 = leading text indentation
# $2 = text
# $3 = leading stmt indentation [OPTIONAL]
#
function print_text() {
local indent="${1}"
if [[ "${indent}" == "${BLOCK_INDENT}"* ]]; then
indent="${indent/#$BLOCK_INDENT/}"
fi
process_tags "${3-${BLOCK_INDENT}}" "${BASE_TEXT_INDENT}${TEXT_INDENT}${indent}${2}"
}
#######################################################################
# Process Functions
#######################################################################
##
# process_tags
# $1 = statement indentation
# $2 = full line of text to process
#
function process_tags() {
local stmt_indent line args arg quoted
stmt_indent="${1}"
line="${2}"
args=""
while [ -n "${line}" ]; do
# echo "# LINE @ START: $(declare -p line)" >&2
if [[ "${line}" =~ $TAG_TEXT_REGEX ]]; then
# echo "# TEXT TAG MATCH: $(declare -p BASH_REMATCH)" >&2
printf -v quoted "%q" "${BASH_REMATCH[1]}"
args="${args}${quoted}"
line="${BASH_REMATCH[2]}"
elif [[ "${line}" =~ $TAG_QUOTE_REGEX ]]; then
# echo "# QUOTE TAG MATCH: $(declare -p BASH_REMATCH)" >&2
args="${args}\"${BASH_REMATCH[1]}\""
line="${BASH_REMATCH[6]}"
elif [[ "${line}" =~ $TAG_STATEMENT_REGEX ]]; then
# echo "# STMT TAG MATCH: $(declare -p BASH_REMATCH)" >&2
arg="${BASH_REMATCH[1]}"
trim arg
args="${args}\"\$(${arg})\""
line="${BASH_REMATCH[5]}"
# Check standard regex last as it's a super-set of quote and stmt regex
#
elif [[ "${line}" =~ $TAG_STD_REGEX ]]; then
# echo "# STD TAG MATCH: $(declare -p BASH_REMATCH)" >&2
arg="${BASH_REMATCH[1]}"
trim arg
args="${args}\"${arg}\""
line="${BASH_REMATCH[5]}"
# Assume next character is TEXT - extract and process remainder
#
elif [[ "${line}" =~ (.)(.*) ]]; then
# echo "# DEFAULT: Assuming first char is TEXT: $(declare -p line)"
printf -v quoted "%q" "${BASH_REMATCH[1]}"
args="${args}${quoted}"
line="${BASH_REMATCH[2]}"
fi
# echo "# LINE @ END: $(declare -p line)" >&2
done
local stmt
if [ -n "${args}" ]; then
printf -v stmt "printf \"%%s\\\\n\" %s" "${args}"
else
printf -v stmt "printf \"\\\\n\""
fi
print_statement "${stmt_indent}" "${stmt}"
}
DELIM_DIR_TAG_REGEX='[Tt][Aa][Gg]\s*=\s*"([^"]*)"'
DELIM_DIR_TAG_STMT_REGEX='[Tt][Aa][Gg][_-]?[Ss][Tt][Mm][Tt]\s*=\s*"([^"]*)"'
DELIM_DIR_STMT_REGEX='[Ss][Tt][Mm][Tt]\s*=\s*"([^"]*)"'
DELIM_DIR_STMT_BLOCK_REGEX='[Ss][Tt][Mm][Tt][_-]?[Bb][Ll][Oo][Cc][Kk]\s*=\s*"([^"]*)"'
DELIM_DIR_TXT_REGEX='[Tt][Xx][Tt]\s*=\s*"([^"]*)"'
DELIM_DIR_TEXT_REGEX='[Tt][Ee][Xx][Tt]\s*=\s*"([^"]*)"'
DELIM_DIR_DIR_REGEX='[Dd][Ii][Rr]\s*=\s*"([^"]*)"'
DELIM_DIR_DIRECTIVE_REGEX='[Dd][Ii][Rr][Ee][Cc][Tt][Ii][Vv][Ee]\s*=\s*"([^"]*)"'
DELIM_DIR_CMT_REGEX='[Cc][Mm][Tt]\s*=\s*"([^"]*)"'
DELIM_DIR_COMMENT_REGEX='[Cc][Oo][Mm][Mm][Ee][Nn][Tt]\s*=\s*"([^"]*)"'
##
# process_directive
# $1 = leading_indent
# $2 = directive
# $3 = directive arg(s)
#
function process_directive() {
local directive
directive="${2}"
normalize_directive directive
case "${directive}" in
INCLUDE)
local indent="${1}"
if [[ "${indent}" == "${BLOCK_INDENT}"* ]]; then
indent="${indent/#$BLOCK_INDENT/}"
fi
local args args_arr
args="${3}"
trim args
declare -a args_arr="(${args})"
# shellcheck disable=SC2128 # We choose BASH_SOURCE vs BASH_SOURCE[0] for compatability
"${BASH_SOURCE}" \
--text-indent "${BASE_TEXT_INDENT}${TEXT_INDENT}${indent}" \
--stmt-indent "${BASE_STMT_INDENT}${STATEMENT_INDENT}${indent}" \
--block-indent "${BASE_BLOCK_INDENT}${BLOCK_INDENT}" \
--tag-delims "${TAG_START_DELIM1}${TAG_START_DELIM2} ${TAG_STOP_DELIM1}${TAG_STOP_DELIM2}" \
--tag-stmt-delim "${TAG_STMT_DELIM}" \
--stmt-delim "${STMT_DELIM}" \
--stmt-block-delims "${STMT_BLOCK_START_DELIM} ${STMT_BLOCK_STOP_DELIM}" \
--txt-delim "${TEXT_DELIM}" \
--dir-delim "${DIRECTIVE_DELIM}" \
--cmt-delim "${COMMENT_DELIM}" \
"${args_arr[@]}"
;;
DELIMS)
# TAG
#
if [[ "${3}" =~ $DELIM_DIR_TAG_REGEX ]]; then
parse_tag_delims "${BASH_REMATCH[1]}" 'DELIMS TAG directive'
fi
# TAG-STMT
#
if [[ "${3}" =~ $DELIM_DIR_TAG_STMT_REGEX ]]; then
parse_tag_stmt_delim "${BASH_REMATCH[1]}" 'DELIMS TAG-STMT directive'
fi
# STMT
#
if [[ "${3}" =~ $DELIM_DIR_STMT_REGEX ]]; then
parse_stmt_delim "${BASH_REMATCH[1]}" 'DELIMS STMT directive'
fi
# STMT-BLOCK
#
if [[ "${3}" =~ $DELIM_DIR_STMT_BLOCK_REGEX ]]; then
parse_stmt_block_delims "${BASH_REMATCH[1]}" '"DELIMS STMT-BLOCK directive'
fi
# TEXT
#
if [[ "${3}" =~ $DELIM_DIR_TXT_REGEX || "${3}" =~ $DELIM_DIR_TEXT_REGEX ]]; then
parse_text_delim "${BASH_REMATCH[1]}" 'DELIMS TEXT directive'
fi
# DIRECTIVE
#
if [[ "${3}" =~ $DELIM_DIR_DIR_REGEX || "${3}" =~ $DELIM_DIR_DIRECTIVE_REGEX ]]; then
parse_directive_delim "${BASH_REMATCH[1]}" 'DELIMS DIR directive'
fi
# COMMENT
#
if [[ "${3}" =~ $DELIM_DIR_CMT_REGEX || "${3}" =~ $DELIM_DIR_COMMENT_REGEX ]]; then
parse_comment_delim "${BASH_REMATCH[1]}" 'DELIMS CMT directive'
fi
# Apply changes
#
reset_template_regexes
;;
RESET-DELIMS)
reset_delims
reset_template_regexes
;;
*) # unsupported directive
echo "Error: Unknown directive: '${directive}' - Skipping" >&2
;;
esac
}
function debug_array() {
printf "["
local need_comma=""
while [[ ${#@} -gt 0 ]]; do
if [ -n "${need_comma:-}" ]; then
printf ", "
fi
if [ -n "${1:-}" ]; then
printf "'%q'" "${1}"
else
printf "''"
fi
need_comma=1
shift
done
printf "]"
}
##
# debug_state logs the state of the global variables.
# To use this set the BASH_TPL_DEBUG variable to a non-empty value
# when invoking the script.
# TODO Track source input file+line numbers
# $1 = template line | EOF
#
function debug_state() {
printf "#<< ---------------\n"
printf "#LINE TEXT : '%s'\n" "${1-<EOF>}"
printf "#STATE : %s\n" "${STATE:-}"
printf "#STATES : %s\n" "$(debug_array "${STATES[@]}")"
printf "#TEXT_INDENT : %q\n" "${TEXT_INDENT:-}"
printf "#TEXT_INDENTS : %s\n" "$(debug_array "${TEXT_INDENTS[@]}")"
printf "#STATEMENT_INDENT : %q\n" "${STATEMENT_INDENT:-}"
printf "#STATEMENT_INDENTS: %s\n" "$(debug_array "${STATEMENT_INDENTS[@]}")"
printf "#BLOCK_INDENT : %q\n" "${BLOCK_INDENT:-}"
printf "#BLOCK_INDENTS : %s\n" "$(debug_array "${BLOCK_INDENTS[@]}")"
printf "#TEXT_BLOCK_LINES_INDENT : %q\n" "${TEXT_BLOCK_LINES_INDENT}"
printf "#TEXT_BLOCK_LINES_INDENT_SET : %q\n" "${TEXT_BLOCK_LINES_INDENT_SET}"
printf "#STATEMENT_BLOCK_LINES_INDENT : %q\n" "${STATEMENT_BLOCK_LINES_INDENT}"
printf "#STATEMENT_BLOCK_LINES_INDENT_STATE : %q\n" "${STATEMENT_BLOCK_LINES_INDENT_STATE}"
printf "#>> ---------------\n"
}
function process_line() {
[ -n "${BASH_TPL_DEBUG:-}" ] && debug_state ${@+"$@"}
state_"${STATE}" ${@+"$@"}
}
function process_stdin() {
local line
while IFS="" read -r line || [ -n "${line}" ]; do
process_line "${line}"
done
# EOF - Notify states
# Call with no args
#
while [[ "${STATE}" != "DEFAULT" ]]; do
process_line
done
process_line # DEFAULT
}
#######################################################################
# State Handler Functions
#######################################################################
##
# state_DEFAULT
# Not inside any blocks
# Assumes *_INDENT and STATE arrays are empty
#
function state_DEFAULT() {
[[ ${#@} -gt 0 ]] || return # Exit early on EOF
# Line is a statement
#
if [[ "${1}" =~ $STATEMENT_REGEX ]]; then
print_statement "${BASH_REMATCH[1]}" "${BASH_REMATCH[2]}"
push_statement_indent "${BASH_REMATCH[1]}"
push_state "MAYBE_TXT_BLOCK"
# Line is a statement block start
#
elif [[ "${1}" =~ $STATEMENT_BLOCK_START_REGEX ]]; then
push_statement_indent "${BASH_REMATCH[1]}"
push_state "START_STMT_BLOCK"
# Line is a directive
#
elif [[ "${1}" =~ $DIRECTIVE_REGEX ]]; then
process_directive "${BASH_REMATCH[1]}" "${BASH_REMATCH[2]}" "${BASH_REMATCH[3]}"
# Line is a comment
#
elif [[ "${1}" =~ $COMMENT_REGEX ]]; then
: # Comments do not generate output
# Line is text
# NOTE : Check LAST because regex always matches
#
elif [[ "${1}" =~ $TEXT_REGEX ]]; then
print_text "${BASH_REMATCH[1]}" "${BASH_REMATCH[2]}"
fi
}
TEXT_BLOCK_LINES=()
TEXT_BLOCK_LINES_INDENT=""
TEXT_BLOCK_LINES_INDENT_SET=""
##
# state_MAYBE_TXT_BLOCK
# Previous line was a statement
# We might be starting a text block
# NOTE: Assumes
# push_state "MAYBE_TXT_BLOCK"
# push_statement_indent
#
function state_MAYBE_TXT_BLOCK() {
# If there's a line to process (i.e. not EOF)
#
if [[ ${#@} -gt 0 ]]; then
# Current line is empty
# Considered text block content,
# but doesn't contribute to indentation tracking
#
if [[ "${1}" == "" ]]; then
TEXT_BLOCK_LINES+=("${1}") # Save line
return
# Current line is a block-end statement,
# i.e. it's a statement at the same indentation as the start statement
#
elif [[ "${1}" =~ $STATEMENT_REGEX && "${BASH_REMATCH[1]}" == "${STATEMENT_INDENT}" ]]; then
# We've saved a FULL text block !
# Use computed indentation
#
push_text_indent "${TEXT_INDENT}${STATEMENT_INDENT/#$BLOCK_INDENT/}" # Additive
push_statement_indent "${TEXT_BLOCK_LINES_INDENT}"
push_block_indent "${TEXT_BLOCK_LINES_INDENT}"
local state_marker=${#STATES[@]} # Save for cleanup
push_state "TXT_BLOCK"
# Text blocks can be nested, so save lines and cleanup *before* processing
#
local lines=("${TEXT_BLOCK_LINES[@]}")
TEXT_BLOCK_LINES=()
TEXT_BLOCK_LINES_INDENT=""
TEXT_BLOCK_LINES_INDENT_SET=""
# Process saved lines now in new state
#
local line
for line in "${lines[@]}"; do
process_line "${line}"
done
# Clean up our TXT_BLOCK state and any other danglers
#
while [[ ${#STATES[@]} -gt $state_marker ]]; do
process_line # EOF
done
# Clean up our MAYBE_TXT_BLOCK state
#
pop_statement_indent
pop_state
# Process close block in parent context
#
process_line "${1}"
return
# Capture line indentation for tracking
# TEXT_REGEX is perfect for this, so just re-use it
# NOTE: Regex always matches
#
elif [[ "${1}" =~ $TEXT_REGEX ]]; then
TEXT_BLOCK_LINES+=("${1}") # Save line
# If current line is indented
#
if [[ "${BASH_REMATCH[1]}" != "${STATEMENT_INDENT}" && "${BASH_REMATCH[1]}" == "${STATEMENT_INDENT}"* ]]; then
# If first time through
#
if [[ "${TEXT_BLOCK_LINES_INDENT_SET}" == "" ]]; then
# Track current indentation
#
TEXT_BLOCK_LINES_INDENT="${BASH_REMATCH[1]}"
TEXT_BLOCK_LINES_INDENT_SET="1"
return
# If current line is indented SAME OR LESS than tracked
#
elif [[ "${TEXT_BLOCK_LINES_INDENT}" == "${BASH_REMATCH[1]}"* ]]; then
# Update tracked indentation (may set to same value)
#
TEXT_BLOCK_LINES_INDENT="${BASH_REMATCH[1]}"
return
# If current line is indented MORE than tracked
#
elif [[ "${BASH_REMATCH[1]}" == "${TEXT_BLOCK_LINES_INDENT}"* ]]; then
# No change
#
return
# Neither line is a subset of the other
#
else
: # Here for completeness
fi
# Current line is NOT indented
#
else
: # Here for completeness
fi
fi
# EOF
#
else
: # Fall through
fi
# If we haven't returned by now, then we're not in a text block
# Discard saved state and process saved lines
#
pop_statement_indent
pop_state
# Text blocks can be nested, so save lines and cleanup *before* processing
#
local lines=("${TEXT_BLOCK_LINES[@]}")
# Clean up
#
TEXT_BLOCK_LINES=()
TEXT_BLOCK_LINES_INDENT=""
TEXT_BLOCK_LINES_INDENT_SET=""
# Process saved lines now in parent context
# TODO "push" these back onto primary line-processing stream?
#
local line
for line in "${lines[@]}"; do
process_line "${line}"
done
}
##
# state_TXT_BLOCK
# NOTE: Assumes
# Called within MAYBE_TXT_BLOCK with a complete block to process
# Will NOT be called with TXT Block Close
# Every line has a minimum indentation of BLOCK_INDENT
# push_state TXT_BLOCK
# push_text_indent
# push_statement_indent
# push_block_indent
#
function state_TXT_BLOCK() {
# EOF
#
if [[ ${#@} -eq 0 ]]; then
# End of text block
# Discard saved state
#
pop_text_indent
pop_statement_indent
pop_block_indent
pop_state
# Current line is empty
#
elif [[ "${1}" == "" ]]; then
process_tags "${BLOCK_INDENT}" ""
# Current line is a statement
#
elif [[ "${1}" =~ $STATEMENT_REGEX ]]; then
print_statement "${BASH_REMATCH[1]}" "${BASH_REMATCH[2]}"
push_statement_indent "${BASH_REMATCH[1]}"
push_state "MAYBE_TXT_BLOCK"
# Current line is a statement Start Block
#
elif [[ "${1}" =~ $STATEMENT_BLOCK_START_REGEX ]]; then
push_statement_indent "${BASH_REMATCH[1]}"
push_state "START_STMT_BLOCK"
# Current line is a directive
#
elif [[ "${1}" =~ $DIRECTIVE_REGEX ]]; then
process_directive "${BASH_REMATCH[1]}" "${BASH_REMATCH[2]}" "${BASH_REMATCH[3]}"
# Line is a comment
#
elif [[ "${1}" =~ $COMMENT_REGEX ]]; then
: # Comments do not generate output
# Line is text
# NOTE: Regex always matches
#
elif [[ "${1}" =~ $TEXT_REGEX ]]; then
print_text "${BASH_REMATCH[1]}" "${BASH_REMATCH[2]}"
fi
}
STATEMENT_BLOCK_LINES=()
STATEMENT_BLOCK_LINES_INDENT=""
STATEMENT_BLOCK_LINES_INDENT_STATE=""
##
# state_START_STMT_BLOCK
# NOTE: Assumes
# push_state "START_STMT_BLOCK"
# push_statement_indent
#
function state_START_STMT_BLOCK() {
# If there's a line to process (i.e. not EOF)
#
if [[ ${#@} -gt 0 ]]; then
# Current line is empty
# Considered statement block content,
# but doesn't contribute to indentation tracking
#
if [[ "${1}" == "" ]]; then
STATEMENT_BLOCK_LINES+=("${1}") # Save line
return
# Current line is a statement block end
#
elif [[ "${1}" =~ $STATEMENT_BLOCK_STOP_REGEX ]]; then
# If indentation does not match block-open, then error
# TODO Track line numbers for better reporting
#
if [[ "${BASH_REMATCH[1]}" != "${STATEMENT_INDENT}" ]]; then
echo "Error: stmt-block close indentation does not match open" >&2
exit 1
fi
# We've saved a FULL statement block !
# Is it fully indented?
#
if [[ "${STATEMENT_BLOCK_LINES_INDENT_STATE}" == "1" ]]; then
# Use computed indentation
#
push_text_indent "${TEXT_INDENT}${STATEMENT_INDENT/#$BLOCK_INDENT/}" # Additive
push_block_indent "${STATEMENT_BLOCK_LINES_INDENT}"
else
# If not consistently indented, default to no indent
# TODO Print warning?
#
push_text_indent ""
pop_statement_indent
push_statement_indent ""
push_block_indent ""
fi
# Process the saved lines
# NOTE: Statement block end (+ cleanup) will be processed by STMT_BLOCK handler
#
pop_state
push_state "STMT_BLOCK"
# Process saved lines now in new state
# Statement blocks do not nest, so we use global and cleanup *after*
#
local line
for line in "${STATEMENT_BLOCK_LINES[@]}"; do