forked from tests-always-included/mo
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmo
More file actions
executable file
·1997 lines (1663 loc) · 56.9 KB
/
mo
File metadata and controls
executable file
·1997 lines (1663 loc) · 56.9 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
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
#
#/ Mo is a mustache template rendering software written in bash. It inserts
#/ environment variables into templates.
#/
#/ Simply put, mo will change {{VARIABLE}} into the value of that
#/ environment variable. You can use {{#VARIABLE}}content{{/VARIABLE}} to
#/ conditionally display content or iterate over the values of an array.
#/
#/ Learn more about mustache templates at https://mustache.github.io/
#/
#/ Simple usage:
#/
#/ mo [OPTIONS] filenames...
#/
#/ Options:
#/
#/ --allow-function-arguments
#/ Permit functions to be called with additional arguments. Otherwise,
#/ the only way to get access to the arguments is to use the
#/ MO_FUNCTION_ARGS environment variable.
#/ -d, --debug
#/ Enable debug logging to stderr.
#/ -u, --fail-not-set
#/ Fail upon expansion of an unset variable. Will silently ignore by
#/ default. Alternately, set MO_FAIL_ON_UNSET to a non-empty value.
#/ -x, --fail-on-function
#/ Fail when a function returns a non-zero status code instead of
#/ silently ignoring it. Alternately, set MO_FAIL_ON_FUNCTION to a
#/ non-empty value.
#/ -f, --fail-on-file
#/ Fail when a file (from command-line or partial) does not exist.
#/ Alternately, set MO_FAIL_ON_FILE to a non-empty value.
#/ -e, --false
#/ Treat the string "false" as empty for conditionals. Alternately,
#/ set MO_FALSE_IS_EMPTY to a non-empty value.
#/ -h, --help
#/ This message.
#/ -s=FILE, --source=FILE
#/ Load FILE into the environment before processing templates.
#/ Can be used multiple times. The file must be a valid shell script
#/ and should only contain variable assignments.
#/ -o=DELIM, --open=DELIM
#/ Set the opening delimiter. Default is "{{".
#/ -c=DELIM, --close=DELIM
#/ Set the closing delimiter. Default is "}}".
#/ -- Indicate the end of options. All arguments after this will be
#/ treated as filenames only. Use when filenames may start with
#/ hyphens.
#/
#/ Mo uses the following environment variables:
#/
#/ MO_ALLOW_FUNCTION_ARGUMENTS - When set to a non-empty value, this allows
#/ functions referenced in templates to receive additional options and
#/ arguments.
#/ MO_CLOSE_DELIMITER - The string used when closing a tag. Defaults to "}}".
#/ Used internally.
#/ MO_CLOSE_DELIMITER_DEFAULT - The default value of MO_CLOSE_DELIMITER. Used
#/ when resetting the close delimiter, such as when parsing a partial.
#/ MO_CURRENT - Variable name to use for ".".
#/ MO_DEBUG - When set to a non-empty value, additional debug information is
#/ written to stderr.
#/ MO_FUNCTION_ARGS - Arguments passed to the function.
#/ MO_FAIL_ON_FILE - If a filename from the command-line is missing or a
#/ partial does not exist, abort with an error.
#/ MO_FAIL_ON_FUNCTION - If a function returns a non-zero status code, abort
#/ with an error.
#/ MO_FAIL_ON_UNSET - When set to a non-empty value, expansion of an unset env
#/ variable will be aborted with an error.
#/ MO_FALSE_IS_EMPTY - When set to a non-empty value, the string "false" will
#/ be treated as an empty value for the purposes of conditionals.
#/ MO_OPEN_DELIMITER - The string used when opening a tag. Defaults to "{{".
#/ Used internally.
#/ MO_OPEN_DELIMITER_DEFAULT - The default value of MO_OPEN_DELIMITER. Used
#/ when resetting the open delimiter, such as when parsing a partial.
#/ MO_ORIGINAL_COMMAND - Used to find the `mo` program in order to generate a
#/ help message.
#/ MO_PARSED - Content that has made it through the template engine.
#/ MO_STANDALONE_CONTENT - The unparsed content that preceeded the current tag.
#/ When a standalone tag is encountered, this is checked to see if it only
#/ contains whitespace. If this and the whitespace condition after a tag is
#/ met, then this will be reset to $'\n'.
#/ MO_UNPARSED - Template content yet to make it through the parser.
#/
#/ Mo is under a MIT style licence with an additional non-advertising clause.
#/ See LICENSE.md for the full text.
#/
#/ This is open source! Please feel free to contribute.
#/
#/ https://github.com/tests-always-included/mo
#: Disable these warnings for the entire file
#:
#: VAR_NAME was modified in a subshell. That change might be lost.
# shellcheck disable=SC2031
#:
#: Modification of VAR_NAME is local (to subshell caused by (..) group).
# shellcheck disable=SC2030
# Public: Template parser function. Writes templates to stdout.
#
# $0 - Name of the mo file, used for getting the help message.
# $@ - Filenames to parse.
#
# Returns nothing.
mo() (
local moSource moFiles moDoubleHyphens moParsed moContent
#: This function executes in a subshell; IFS is reset at the end.
IFS=$' \n\t'
#: Enable a strict mode. This is also reset at the end.
set -eEu -o pipefail
moFiles=()
moDoubleHyphens=false
MO_OPEN_DELIMITER_DEFAULT="{{"
MO_CLOSE_DELIMITER_DEFAULT="}}"
MO_FUNCTION_CACHE_HIT=()
MO_FUNCTION_CACHE_MISS=()
if [[ $# -gt 0 ]]; then
for arg in "$@"; do
if $moDoubleHyphens; then
#: After we encounter two hyphens together, all the rest
#: of the arguments are files.
moFiles=(${moFiles[@]+"${moFiles[@]}"} "$arg")
else
case "$arg" in
-h|--h|--he|--hel|--help|-\?)
mo::usage "$0"
exit 0
;;
--allow-function-arguments)
MO_ALLOW_FUNCTION_ARGUMENTS=true
;;
-u | --fail-not-set)
MO_FAIL_ON_UNSET=true
;;
-x | --fail-on-function)
MO_FAIL_ON_FUNCTION=true
;;
-p | --fail-on-file)
MO_FAIL_ON_FILE=true
;;
-e | --false)
MO_FALSE_IS_EMPTY=true
;;
-s=* | --source=*)
if [[ "$arg" == --source=* ]]; then
moSource="${arg#--source=}"
else
moSource="${arg#-s=}"
fi
if [[ -e "$moSource" ]]; then
# shellcheck disable=SC1090
. "$moSource"
else
echo "No such file: $moSource" >&2
exit 1
fi
;;
-o=* | --open=*)
if [[ "$arg" == --open=* ]]; then
MO_OPEN_DELIMITER_DEFAULT="${arg#--open=}"
else
MO_OPEN_DELIMITER_DEFAULT="${arg#-o=}"
fi
;;
-c=* | --close=*)
if [[ "$arg" == --close=* ]]; then
MO_CLOSE_DELIMITER_DEFAULT="${arg#--close=}"
else
MO_CLOSE_DELIMITER_DEFAULT="${arg#-c=}"
fi
;;
-d | --debug)
MO_DEBUG=true
;;
--)
#: Set a flag indicating we've encountered double hyphens
moDoubleHyphens=true
;;
-*)
mo::error "Unknown option: $arg (See --help for options)"
;;
*)
#: Every arg that is not a flag or a option should be a file
moFiles=(${moFiles[@]+"${moFiles[@]}"} "$arg")
;;
esac
fi
done
fi
mo::debug "Debug enabled"
MO_OPEN_DELIMITER="$MO_OPEN_DELIMITER_DEFAULT"
MO_CLOSE_DELIMITER="$MO_CLOSE_DELIMITER_DEFAULT"
mo::content moContent ${moFiles[@]+"${moFiles[@]}"} || return 1
mo::parse moParsed "$moContent"
echo -n "$moParsed"
)
# Internal: Show a debug message
#
# $1 - The debug message to show
#
# Returns nothing.
mo::debug() {
if [[ -n "${MO_DEBUG:-}" ]]; then
echo "DEBUG ${FUNCNAME[1]:-?} - $1" >&2
fi
}
# Internal: Show a debug message and internal state information
#
# No arguments
#
# Returns nothing.
mo::debugShowState() {
if [[ -z "${MO_DEBUG:-}" ]]; then
return
fi
local moState moTemp moIndex moDots
mo::escape moTemp "$MO_OPEN_DELIMITER"
moState="open: $moTemp"
mo::escape moTemp "$MO_CLOSE_DELIMITER"
moState="$moState close: $moTemp"
mo::escape moTemp "$MO_STANDALONE_CONTENT"
moState="$moState standalone: $moTemp"
mo::escape moTemp "$MO_CURRENT"
moState="$moState current: $moTemp"
moIndex=$((${#MO_PARSED} - 20))
moDots=...
if [[ "$moIndex" -lt 0 ]]; then
moIndex=0
moDots=
fi
mo::escape moTemp "${MO_PARSED:$moIndex}"
moState="$moState parsed: $moDots$moTemp"
moDots=...
if [[ "${#MO_UNPARSED}" -le 20 ]]; then
moDots=
fi
mo::escape moTemp "${MO_UNPARSED:0:20}$moDots"
moState="$moState unparsed: $moTemp"
echo "DEBUG ${FUNCNAME[1]:-?} - $moState" >&2
}
# Internal: Show an error message and exit
#
# $1 - The error message to show
# $2 - Error code
#
# Returns nothing. Exits the program.
mo::error() {
echo "ERROR: $1" >&2
exit "${2:-1}"
}
# Internal: Show an error message with a snippet of context and exit
#
# $1 - The error message to show
# $2 - The starting point
# $3 - Error code
#
# Returns nothing. Exits the program.
mo::errorNear() {
local moEscaped
mo::escape moEscaped "${2:0:40}"
echo "ERROR: $1" >&2
echo "ERROR STARTS NEAR: $moEscaped"
exit "${3:-1}"
}
# Internal: Displays the usage for mo. Pulls this from the file that
# contained the `mo` function. Can only work when the right filename
# comes is the one argument, and that only happens when `mo` is called
# with `$0` set to this file.
#
# $1 - Filename that has the help message
#
# Returns nothing.
mo::usage() {
while read -r line; do
if [[ "${line:0:2}" == "#/" ]]; then
echo "${line:3}"
fi
done < "$MO_ORIGINAL_COMMAND"
echo ""
echo "MO_VERSION=$MO_VERSION"
}
# Internal: Fetches the content to parse into MO_UNPARSED. Can be a list of
# partials for files or the content from stdin.
#
# $1 - Destination variable name
# $2-@ - File names (optional), read from stdin otherwise
#
# Returns nothing.
mo::content() {
local moTarget moContent moFilename
moTarget=$1
shift
moContent=""
if [[ "${#@}" -gt 0 ]]; then
for moFilename in "$@"; do
mo::debug "Using template to load content from file: $moFilename"
#: This is so relative paths work from inside template files
moContent="$moContent$MO_OPEN_DELIMITER>$moFilename$MO_CLOSE_DELIMITER"
done
else
mo::debug "Will read content from stdin"
mo::contentFile moContent || return 1
fi
local "$moTarget" && mo::indirect "$moTarget" "$moContent"
}
# Internal: Read a file into MO_UNPARSED.
#
# $1 - Destination variable name.
# $2 - Filename to load - if empty, defaults to /dev/stdin
#
# Returns nothing.
mo::contentFile() {
local moFile moResult moContent
#: The subshell removes any trailing newlines. We forcibly add
#: a dot to the content to preserve all newlines. Reading from
#: stdin with a `read` loop does not work as expected, so `cat`
#: needs to stay.
moFile=${2:-/dev/stdin}
if [[ -e "$moFile" ]]; then
mo::debug "Loading content: $moFile"
moContent=$(
set +Ee
cat -- "$moFile"
moResult=$?
echo -n '.'
exit "$moResult"
) || return 1
moContent=${moContent%.} #: Remove last dot
elif [[ -n "${MO_FAIL_ON_FILE-}" ]]; then
mo::error "No such file: $moFile"
else
mo::debug "File does not exist: $moFile"
moContent=""
fi
local "$1" && mo::indirect "$1" "$moContent"
}
# Internal: Send a variable up to the parent of the caller of this function.
#
# $1 - Variable name
# $2 - Value
#
# Examples
#
# callFunc () {
# local "$1" && mo::indirect "$1" "the value"
# }
# callFunc dest
# echo "$dest" # writes "the value"
#
# Returns nothing.
mo::indirect() {
unset -v "$1"
printf -v "$1" '%s' "$2"
}
# Internal: Send an array as a variable up to caller of a function
#
# $1 - Variable name
# $2-@ - Array elements
#
# Examples
#
# callFunc () {
# local myArray=(one two three)
# local "$1" && mo::indirectArray "$1" "${myArray[@]}"
# }
# callFunc dest
# echo "${dest[@]}" # writes "one two three"
#
# Returns nothing.
mo::indirectArray() {
unset -v "$1"
#: IFS must be set to a string containing space or unset in order for
#: the array slicing to work regardless of the current IFS setting on
#: bash 3. This is detailed further at
#: https://github.com/fidian/gg-core/pull/7
eval "$(printf "IFS= %s=(\"\${@:2}\") IFS=%q" "$1" "$IFS")"
}
# Internal: Trim leading characters from MO_UNPARSED
#
# Returns nothing.
mo::trimUnparsed() {
local moI moC
moI=0
moC=${MO_UNPARSED:0:1}
while [[ "$moC" == " " || "$moC" == $'\r' || "$moC" == $'\n' || "$moC" == $'\t' ]]; do
moI=$((moI + 1))
moC=${MO_UNPARSED:$moI:1}
done
if [[ "$moI" != 0 ]]; then
MO_UNPARSED=${MO_UNPARSED:$moI}
fi
}
# Internal: Remove whitespace and content after whitespace
#
# $1 - Name of the destination variable
# $2 - The string to chomp
#
# Returns nothing.
mo::chomp() {
local moTemp moR moN moT
moR=$'\r'
moN=$'\n'
moT=$'\t'
moTemp=${2%% *}
moTemp=${moTemp%%"$moR"*}
moTemp=${moTemp%%"$moN"*}
moTemp=${moTemp%%"$moT"*}
local "$1" && mo::indirect "$1" "$moTemp"
}
# Public: Parses text, interpolates mustache tags. Utilizes the current value
# of MO_OPEN_DELIMITER, MO_CLOSE_DELIMITER, and MO_STANDALONE_CONTENT. Those
# three variables shouldn't be changed by user-defined functions.
#
# $1 - Destination variable name - where to store the finished content
# $2 - Content to parse
# $3 - Preserve standalone status/content - truthy if not empty. When set to a
# value, that becomes the standalone content value
#
# Returns nothing.
mo::parse() {
local moOldParsed moOldStandaloneContent moOldUnparsed moResult
#: The standalone content is a trick to make the standalone tag detection
#: possible. When it's set to content with a newline and if the tag supports
#: it, the standalone content check happens. This check ensures only
#: whitespace is after the last newline up to the tag, and only whitespace
#: is after the tag up to the next newline. If that is the case, remove
#: whitespace and the trailing newline. By setting this to $'\n', we're
#: saying we are at the beginning of content.
mo::debug "Starting parse of ${#2} bytes"
moOldParsed=${MO_PARSED:-}
moOldUnparsed=${MO_UNPARSED:-}
MO_PARSED=""
MO_UNPARSED="$2"
if [[ -z "${3:-}" ]]; then
moOldStandaloneContent=${MO_STANDALONE_CONTENT:-}
MO_STANDALONE_CONTENT=$'\n'
else
MO_STANDALONE_CONTENT=$3
fi
MO_CURRENT=${MO_CURRENT:-}
mo::parseInternal
moResult="$MO_PARSED$MO_UNPARSED"
MO_PARSED=$moOldParsed
MO_UNPARSED=$moOldUnparsed
if [[ -z "${3:-}" ]]; then
MO_STANDALONE_CONTENT=$moOldStandaloneContent
fi
local "$1" && mo::indirect "$1" "$moResult"
}
# Internal: Parse MO_UNPARSED, writing content to MO_PARSED. Interpolates
# mustache tags.
#
# No arguments
#
# Returns nothing.
mo::parseInternal() {
local moChunk
mo::debug "Starting parse"
while [[ -n "$MO_UNPARSED" ]]; do
mo::debugShowState
moChunk=${MO_UNPARSED%%"$MO_OPEN_DELIMITER"*}
MO_PARSED="$MO_PARSED$moChunk"
MO_STANDALONE_CONTENT="$MO_STANDALONE_CONTENT$moChunk"
MO_UNPARSED=${MO_UNPARSED:${#moChunk}}
if [[ -n "$MO_UNPARSED" ]]; then
MO_UNPARSED=${MO_UNPARSED:${#MO_OPEN_DELIMITER}}
mo::trimUnparsed
case "$MO_UNPARSED" in
'#'*)
#: Loop, if/then, or pass content through function
mo::parseBlock false
;;
'^'*)
#: Display section if named thing does not exist
mo::parseBlock true
;;
'>'*)
#: Load partial - get name of file relative to cwd
mo::parsePartial
;;
'/'*)
#: Closing tag
mo::errorNear "Unbalanced close tag" "$MO_UNPARSED"
;;
'!'*)
#: Comment - ignore the tag content entirely
mo::parseComment
;;
'='*)
#: Change delimiters
#: Any two non-whitespace sequences separated by whitespace.
mo::parseDelimiter
;;
'&'*)
#: Unescaped - mo doesn't escape/unescape
MO_UNPARSED=${MO_UNPARSED#&}
mo::trimUnparsed
mo::parseValue
;;
*)
#: Normal environment variable, string, subexpression,
#: current value, key, or function call
mo::parseValue
;;
esac
fi
done
}
# Internal: Handle parsing a block
#
# $1 - Invert condition ("true" or "false")
#
# Returns nothing
mo::parseBlock() {
local moInvertBlock moTokens moTokensString
moInvertBlock=$1
MO_UNPARSED=${MO_UNPARSED:1}
mo::tokenizeTagContents moTokens "$MO_CLOSE_DELIMITER"
MO_UNPARSED=${MO_UNPARSED#"$MO_CLOSE_DELIMITER"}
mo::tokensToString moTokensString "${moTokens[@]:1}"
mo::debug "Parsing block: $moTokensString"
if mo::standaloneCheck; then
mo::standaloneProcess
fi
if [[ "${moTokens[1]}" == "NAME" ]] && mo::isFunction "${moTokens[2]}"; then
mo::parseBlockFunction "$moInvertBlock" "$moTokensString" "${moTokens[@]:1}"
elif [[ "${moTokens[1]}" == "NAME" ]] && mo::isArray "${moTokens[2]}"; then
mo::parseBlockArray "$moInvertBlock" "$moTokensString" "${moTokens[@]:1}"
else
mo::parseBlockValue "$moInvertBlock" "$moTokensString" "${moTokens[@]:1}"
fi
}
# Internal: Handle parsing a block whose first argument is a function
#
# $1 - Invert condition ("true" or "false")
# $2-@ - The parsed tokens from inside the block tags
#
# Returns nothing
mo::parseBlockFunction() {
local moTarget moInvertBlock moTokens moTemp moUnparsed moTokensString
moInvertBlock=$1
moTokensString=$2
shift 2
moTokens=(${@+"$@"})
mo::debug "Parsing block function: $moTokensString"
mo::getContentUntilClose moTemp "$moTokensString"
#: Pass unparsed content to the function.
#: Keep the updated delimiters if they changed.
if [[ "$moInvertBlock" != "true" ]]; then
mo::evaluateFunction moResult "$moTemp" "${moTokens[@]:1}"
MO_PARSED="$MO_PARSED$moResult"
fi
mo::debug "Done parsing block function: $moTokensString"
}
# Internal: Handle parsing a block whose first argument is an array
#
# $1 - Invert condition ("true" or "false")
# $2-@ - The parsed tokens from inside the block tags
#
# Returns nothing
mo::parseBlockArray() {
local moInvertBlock moTokens moResult moArrayName moArrayIndexes moArrayIndex moTemp moUnparsed moOpenDelimiterBefore moCloseDelimiterBefore moOpenDelimiterAfter moCloseDelimiterAfter moParsed moTokensString moCurrent
moInvertBlock=$1
moTokensString=$2
shift 2
moTokens=(${@+"$@"})
mo::debug "Parsing block array: $moTokensString"
moOpenDelimiterBefore=$MO_OPEN_DELIMITER
moCloseDelimiterBefore=$MO_CLOSE_DELIMITER
mo::getContentUntilClose moTemp "$moTokensString"
moOpenDelimiterAfter=$MO_OPEN_DELIMITER
moCloseDelimiterAfter=$MO_CLOSE_DELIMITER
moArrayName=${moTokens[1]}
eval "moArrayIndexes=(\"\${!${moArrayName}[@]}\")"
if [[ "${#moArrayIndexes[@]}" -lt 1 ]]; then
#: No elements
if [[ "$moInvertBlock" == "true" ]]; then
#: Restore the delimiter before parsing
MO_OPEN_DELIMITER=$moOpenDelimiterBefore
MO_CLOSE_DELIMITER=$moCloseDelimiterBefore
moCurrent=$MO_CURRENT
MO_CURRENT=$moArrayName
mo::parse moParsed "$moTemp" "blockArrayInvert$MO_STANDALONE_CONTENT"
MO_CURRENT=$moCurrent
MO_PARSED="$MO_PARSED$moParsed"
fi
else
if [[ "$moInvertBlock" != "true" ]]; then
#: Process for each element in the array
moUnparsed=$MO_UNPARSED
for moArrayIndex in "${moArrayIndexes[@]}"; do
#: Restore the delimiter before parsing
MO_OPEN_DELIMITER=$moOpenDelimiterBefore
MO_CLOSE_DELIMITER=$moCloseDelimiterBefore
moCurrent=$MO_CURRENT
MO_CURRENT=$moArrayName.$moArrayIndex
mo::debug "Iterate over array using element: $MO_CURRENT"
mo::parse moParsed "$moTemp" "blockArray$MO_STANDALONE_CONTENT"
MO_CURRENT=$moCurrent
MO_PARSED="$MO_PARSED$moParsed"
done
MO_UNPARSED=$moUnparsed
fi
fi
MO_OPEN_DELIMITER=$moOpenDelimiterAfter
MO_CLOSE_DELIMITER=$moCloseDelimiterAfter
mo::debug "Done parsing block array: $moTokensString"
}
# Internal: Handle parsing a block whose first argument is a value
#
# $1 - Invert condition ("true" or "false")
# $2-@ - The parsed tokens from inside the block tags
#
# Returns nothing
mo::parseBlockValue() {
local moInvertBlock moTokens moResult moUnparsed moOpenDelimiterBefore moOpenDelimiterAfter moCloseDelimiterBefore moCloseDelimiterAfter moParsed moTemp moTokensString moCurrent
moInvertBlock=$1
moTokensString=$2
shift 2
moTokens=(${@+"$@"})
mo::debug "Parsing block value: $moTokensString"
moOpenDelimiterBefore=$MO_OPEN_DELIMITER
moCloseDelimiterBefore=$MO_CLOSE_DELIMITER
mo::getContentUntilClose moTemp "$moTokensString"
moOpenDelimiterAfter=$MO_OPEN_DELIMITER
moCloseDelimiterAfter=$MO_CLOSE_DELIMITER
#: Variable, value, or list of mixed things
mo::evaluateListOfSingles moResult "${moTokens[@]}"
if mo::isTruthy "$moResult" "$moInvertBlock"; then
mo::debug "Block is truthy: $moResult"
#: Restore the delimiter before parsing
MO_OPEN_DELIMITER=$moOpenDelimiterBefore
MO_CLOSE_DELIMITER=$moCloseDelimiterBefore
moCurrent=$MO_CURRENT
MO_CURRENT=${moTokens[1]}
mo::parse moParsed "$moTemp" "blockValue$MO_STANDALONE_CONTENT"
MO_PARSED="$MO_PARSED$moParsed"
MO_CURRENT=$moCurrent
fi
MO_OPEN_DELIMITER=$moOpenDelimiterAfter
MO_CLOSE_DELIMITER=$moCloseDelimiterAfter
mo::debug "Done parsing block value: $moTokensString"
}
# Internal: Handle parsing a partial
#
# No arguments.
#
# Indentation will be applied to the entire partial's contents before parsing.
# This indentation is based on the whitespace that ends the previously parsed
# content.
#
# Returns nothing
mo::parsePartial() {
local moFilename moResult moIndentation moN moR moTemp moT
MO_UNPARSED=${MO_UNPARSED:1}
mo::trimUnparsed
mo::chomp moFilename "${MO_UNPARSED%%"$MO_CLOSE_DELIMITER"*}"
MO_UNPARSED="${MO_UNPARSED#*"$MO_CLOSE_DELIMITER"}"
moIndentation=""
if mo::standaloneCheck; then
moN=$'\n'
moR=$'\r'
moT=$'\t'
moIndentation="$moN${MO_PARSED//"$moR"/"$moN"}"
moIndentation=${moIndentation##*"$moN"}
moTemp=${moIndentation// }
moTemp=${moTemp//"$moT"}
if [[ -n "$moTemp" ]]; then
moIndentation=
fi
mo::debug "Adding indentation to partial: '$moIndentation'"
mo::standaloneProcess
fi
mo::debug "Parsing partial: $moFilename"
#: Execute in subshell to preserve current cwd and environment
moResult=$(
#: It would be nice to remove `dirname` and use a function instead,
#: but that is difficult when only given filenames.
cd "$(dirname -- "$moFilename")" || exit 1
echo "$(
local moPartialContent moPartialParsed
if ! mo::contentFile moPartialContent "${moFilename##*/}"; then
exit 1
fi
#: Reset delimiters before parsing
mo::indentLines moPartialContent "$moIndentation" "$moPartialContent"
MO_OPEN_DELIMITER="$MO_OPEN_DELIMITER_DEFAULT"
MO_CLOSE_DELIMITER="$MO_CLOSE_DELIMITER_DEFAULT"
mo::parse moPartialParsed "$moPartialContent"
#: Fix bash handling of subshells and keep trailing whitespace.
echo -n "$moPartialParsed."
)" || exit 1
) || exit 1
if [[ -z "$moResult" ]]; then
mo::debug "Error detected when trying to read the file"
exit 1
fi
MO_PARSED="$MO_PARSED${moResult%.}"
}
# Internal: Handle parsing a comment
#
# No arguments.
#
# Returns nothing
mo::parseComment() {
local moContent moContent
MO_UNPARSED=${MO_UNPARSED#*"$MO_CLOSE_DELIMITER"}
mo::debug "Parsing comment"
if mo::standaloneCheck; then
mo::standaloneProcess
fi
}
# Internal: Handle parsing the change of delimiters
#
# No arguments.
#
# Returns nothing
mo::parseDelimiter() {
local moContent moOpen moClose
MO_UNPARSED=${MO_UNPARSED:1}
mo::trimUnparsed
mo::chomp moOpen "$MO_UNPARSED"
MO_UNPARSED=${MO_UNPARSED:${#moOpen}}
mo::trimUnparsed
mo::chomp moClose "${MO_UNPARSED%%="$MO_CLOSE_DELIMITER"*}"
MO_UNPARSED=${MO_UNPARSED#*="$MO_CLOSE_DELIMITER"}
mo::debug "Parsing delimiters: $moOpen $moClose"
if mo::standaloneCheck; then
mo::standaloneProcess
fi
MO_OPEN_DELIMITER="$moOpen"
MO_CLOSE_DELIMITER="$moClose"
}
# Internal: Handle parsing value or function call
#
# No arguments.
#
# Returns nothing
mo::parseValue() {
local moUnparsedOriginal moTokens
moUnparsedOriginal=$MO_UNPARSED
mo::tokenizeTagContents moTokens "$MO_CLOSE_DELIMITER"
mo::evaluate moResult "${moTokens[@]:1}"
MO_PARSED="$MO_PARSED$moResult"
if [[ "${MO_UNPARSED:0:${#MO_CLOSE_DELIMITER}}" != "$MO_CLOSE_DELIMITER" ]]; then
mo::errorNear "Did not find closing tag" "$moUnparsedOriginal"
fi
if mo::standaloneCheck; then
mo::standaloneProcess
fi
MO_UNPARSED=${MO_UNPARSED:${#MO_CLOSE_DELIMITER}}
}
# Internal: Determine if the given name is a defined function.
#
# $1 - Function name to check
#
# Be extremely careful. Even if strict mode is enabled, it is not honored
# in newer versions of Bash. Any errors that crop up here will not be
# caught automatically.
#
# Examples
#
# moo () {
# echo "This is a function"
# }
# if mo::isFunction moo; then
# echo "moo is a defined function"
# fi
#
# Returns 0 if the name is a function, 1 otherwise.
mo::isFunction() {
local moFunctionName
for moFunctionName in "${MO_FUNCTION_CACHE_HIT[@]}"; do
if [[ "$moFunctionName" == "$1" ]]; then
return 0
fi
done
for moFunctionName in "${MO_FUNCTION_CACHE_MISS[@]}"; do
if [[ "$moFunctionName" == "$1" ]]; then
return 1
fi
done
if declare -F "$1" &> /dev/null; then
MO_FUNCTION_CACHE_HIT=( ${MO_FUNCTION_CACHE_HIT[@]+"${MO_FUNCTION_CACHE_HIT[@]}"} "$1" )
return 0
fi
MO_FUNCTION_CACHE_MISS=( ${MO_FUNCTION_CACHE_MISS[@]+"${MO_FUNCTION_CACHE_MISS[@]}"} "$1" )
return 1
}
# Internal: Determine if a given environment variable exists and if it is
# an array.
#
# $1 - Name of environment variable
#
# Be extremely careful. Even if strict mode is enabled, it is not honored
# in newer versions of Bash. Any errors that crop up here will not be
# caught automatically.
#
# Examples
#
# var=(abc)
# if moIsArray var; then
# echo "This is an array"
# echo "Make sure you don't accidentally use \$var"
# fi
#
# Returns 0 if the name is not empty, 1 otherwise.
mo::isArray() {
#: Namespace this variable so we don't conflict with what we're testing.
local moTestResult
moTestResult=$(declare -p "$1" 2>/dev/null) || return 1
[[ "${moTestResult:0:10}" == "declare -a" ]] && return 0
[[ "${moTestResult:0:10}" == "declare -A" ]] && return 0
return 1
}
# Internal: Determine if an array index exists.
#
# $1 - Variable name to check
# $2 - The index to check
#
# Has to check if the variable is an array and if the index is valid for that
# type of array.
#
# Returns true (0) if everything was ok, 1 if there's any condition that fails.
mo::isArrayIndexValid() {
local moDeclare moTest
moDeclare=$(declare -p "$1")
moTest=""
if [[ "${moDeclare:0:10}" == "declare -a" ]]; then
#: Numerically indexed array - must check if the index looks like a
#: number because using a string to index a numerically indexed array
#: will appear like it worked.
if [[ "$2" == "0" ]] || [[ "$2" =~ ^[1-9][0-9]*$ ]]; then
#: Index looks like a number
eval "moTest=\"\${$1[$2]+ok}\""
fi
elif [[ "${moDeclare:0:10}" == "declare -A" ]]; then
#: Associative array
eval "moTest=\"\${$1[$2]+ok}\""
fi
if [[ -n "$moTest" ]]; then
return 0;
fi
return 1
}
# Internal: Determine if a variable is assigned, even if it is assigned an empty
# value.
#
# $1 - Variable name to check.