refactor: improve templater with new functionality

This commit is contained in:
Price Hiller 2023-09-15 17:01:12 -05:00
parent d17ccfc049
commit 1bc1e3d3ed
No known key found for this signature in database
2 changed files with 425 additions and 276 deletions

View File

@ -1,20 +1,128 @@
#!/usr/bin/env bash
# "Import" our needed functions from our library
LIBRARY_PATH="/usr/local/lib/Custom-Scripts"
# shellcheck source=/usr/local/lib/
if ! source "${LIBRARY_PATH}/Logging-RGB.bash"; then
echo "Unable to source Logging-RGB.bash at ${LIBRARY_PATH}"
exit 1
fi
# shellcheck source=/usr/local/lib/
if ! source "${LIBRARY_PATH}/Trim.bash"; then
log "error" "Unable to source Trim.bash at ${LIBRARY_PATH}"
exit 1
fi
echo_rgb() {
# Echo a colored string to the terminal based on rgb values
#
# Positional Arguments:
#
# message <type: string> <position: 1> <required: true>
# - The message to be printed to stdout
# red <type: int> <position: 2> <required: true>
# - The red value from 0 to 255
# green <type: int> <position: 3> <required: true>
# - The green value from 0 to 255
# blue <type: int> <position: 4> <required: true>
# - The blue value from 0 to 255
#
# Usage:
# echo_rgb "Yep" 10 8 30
#
# POSIX Compliant:
# N/A
#
# Tmp file used because most distros have this dir exist in RAM, use PID of our process to write to
TEMP_FILE="/tmp/$$"
local red
local green
local blue
local input
input="${1}"
red="${2}"
green="${3}"
blue="${4}"
if [ -t 1 ]; then
printf "\e[0;38;2;%s;%s;%sm%s\e[m\n" "${red}" "${green}" "${blue}" "${input}"
else
printf "%s\n" "${input}"
fi
}
log() {
# Print a message and send it to stdout or stderr depending upon log level, also configurable with debug etc.
#
# Arguments:
# level <type: string> <position: 1> <required: true>
# - The log level, defined within a case check in this function
# message <type: string> <position: 2> <required: true>
# - The info message
# line_number <type: int> <position: 3> <required: false>
# - The line number of the calling function (${LINNO})
#
# Usage:
# log "info" "Could not find that directory"
#
# POSIX Compliant:
# Yes
#
# Set debug status depending if a global debug variable has been set to either 1 or 0
local debug
if [ ${DEBUG} ]; then
debug=${DEBUG}
else
debug=0
fi
local FORMAT
FORMAT="[$(echo_rgb "$(date +%Y-%m-%dT%H:%M:%S)" 180 140 255)]"
# Convert the level to uppercase
local level
level=$(echo "${1}" | tr '[:lower:]' '[:upper:]')
local message
message="${2}"
case "${level}" in
INFO)
# Output all info log levels to stdout
printf "${FORMAT}[$(echo_rgb "INFO" 0 140 255)] %s\n" "${message}" >&1
return 0
;;
WARN | WARNING)
# Output all warning log levels to stdout
printf "${FORMAT}[$(echo_rgb "WARNING" 255 255 0)] %s\n" "${message}" >&1
return 0
;;
DEBUG)
# Output all debug log levels to stdout
if [ "${DEBUG}" ]; then
printf "${FORMAT}[$(echo_rgb "DEBUG" 0 160 110)] %s\n" "${message}" >&1
fi
return 0
;;
ERROR)
# Output all error log levels to stderr
printf "${FORMAT}[$(echo_rgb "ERROR" 255 0 0)] %s\n" "${message}" >&2
return 0
;;
# Further log levels can be added by extending this switch statement with more comparisons
*) # Default case, no matches
# Returns non-zero code as an improper log option was passed, this helps with using `set -e`
printf "${FORMAT}[ERROR] %s\n" "Invalid log level passed, received level \"${level}\" with message \"${message}\"" >&2
return 1
;;
esac
}
trim() {
local input="${1}"
while [[ "${input}" == " "* ]]; do
input="${input## }"
done
while [[ "${input}" == *" " ]]; do
input="${input%% }"
done
echo "${input}"
}
# Get a temp working file so we don't pollute directories
TEMP_FILE="$(mktemp)"
# Set the Contents directory to the env variable, script set, or to their .contents file in the user home
CONTENTS_DIRECTORY="${CONTENTS_DIRECTORY:=\
@ -32,6 +140,8 @@ template_handlers=(
["FILE"]="file_handler"
["WRITE-TO"]="write_to_handler"
["TEMPLATE"]="template_handler"
["VAR"]="var_handler"
["EVAL"]="eval_handler"
)
write_content() {
@ -43,7 +153,7 @@ write_content() {
local string_builder
string_builder=""
for ((i=1; i<=leading_spaces; i++)); do
for ((i = 1; i <= leading_spaces; i++)); do
string_builder="${string_builder} "
done
string_builder="${string_builder}${content}"
@ -52,11 +162,27 @@ write_content() {
_write_to_buffer() {
log "debug" "Received content to write to buffer:
${1}"
printf "%s\n" "${1}" >> "${TEMP_FILE}"
${1}"
printf "%s\n" "${1}" >>"${TEMP_FILE}"
log "debug" "Finished writing content to buffer"
}
var_handler() {
local variable="${1}"
local leading_spaces="${2}"
while IFS="\n" read -r line; do
write_content "${line}" "${leading_spaces}"
done <<<"${variable}"
}
eval_handler() {
local eval_statement="${1}"
local leading_spaces="${2}"
while IFS="\n" read -r line; do
write_content "${line}" "${leading_spaces}"
done <<<"$(eval "${eval_statement}")"
}
template_handler() {
local template_file
template_file="${1}"
@ -88,7 +214,6 @@ file_handler() {
file="${CONTENTS_DIRECTORY}/${file}"
fi
if [[ ! -f "${file}" ]]; then
log "error" "The given file \"${file}\" does not exist"
return 1
@ -96,10 +221,9 @@ file_handler() {
while IFS="\n" read -r line; do
write_content "${line}" "${leading_spaces}"
done < "${file}"
done <"${file}"
}
write_to_handler() {
local write_path
write_path=${1}
@ -128,7 +252,7 @@ parse_template_extracted() {
full_line="${2}"
local num_leading_spaces
num_leading_spaces=$(awk -F"[ ]" '{for(i=1;i<=NF && ($i=="");i++);print ""i-1""}' <<< "${full_line}")
num_leading_spaces=$(awk -F"[ ]" '{for(i=1;i<=NF && ($i=="");i++);print ""i-1""}' <<<"${full_line}")
# Basic checks to ensure template is correct, first not empty, second that an '=' was passed to give type specifier
# third is to ensure only one equals sign is passed
@ -214,7 +338,7 @@ read_template() {
# Check for non zero status code
if ! parse_template_line "${line}"; then
log "error" "Invalid template passed from \"${read_file}\", check line ${line_num}"
if (( "${EXIT_ON_ERROR}" == 0 )); then
if (("${EXIT_ON_ERROR}" == 0)); then
exit 1
fi
fi
@ -231,7 +355,7 @@ templater() {
read_template "${read_file}"
if (( "${REPEAT}" == 0 )); then
if (("${REPEAT}" == 0)); then
REPEAT=1
log "debug" "Repeat set to 0, repeating on the finished file located at ${TEMP_FILE}"
mv "${TEMP_FILE}" "${TEMP_FILE}-repeat"
@ -248,11 +372,11 @@ arg_required() {
echo_rgb "${1}" 255 183 0
}
arg_optional(){
arg_optional() {
echo_rgb "${1}" 117 255 255
}
arg_description(){
arg_description() {
echo_rgb "${@}" 220 190 255
}

View File

@ -21,3 +21,28 @@ For example
For example, say we have a primary template `main.tmpl` that uses the sub-template `sub.tmpl` then
when the parsing process begins it will also parse the contents of `sub.tmpl` and append them to the contents
parsed by `main.tmpl`
- VAR
- This is used when you want to expand a variable from your environment, say "${HOME}"
- EVAL
- This is used when you want to evaluate a statement in bash, be careful as any errors here can really nuke things and
cause security issues.
## Example
Given a template file with content like so:
```
{#% VAR=$HOME %#}
{#% EVAL="ls -alh" %#}
```
The output would be something like
```
/home/username
total 52K
drwxr-xr-x 1 sam sam 196 Sep 15 17:03 .
drwxr-xr-x 1 sam sam 94 Sep 15 16:42 ..
-rwxr-xr-x 1 sam sam 13K Sep 15 17:01 Templater.bash
-rw-r--r-- 1 sam sam 1.1K Sep 15 17:03 Templater.md
```