From 1168c50a23af34bf65c598d94e0956accb848498 Mon Sep 17 00:00:00 2001 From: pvincent Date: Fri, 17 Jul 2026 19:00:44 +0400 Subject: [PATCH] ansi functions library --- lib/ansi.bash | 60 +++++++++++++++++++++++++++++++++++++++++ test/stub/scenario.bash | 4 +++ 2 files changed, 64 insertions(+) create mode 100644 lib/ansi.bash diff --git a/lib/ansi.bash b/lib/ansi.bash new file mode 100644 index 0000000..4a7d502 --- /dev/null +++ b/lib/ansi.bash @@ -0,0 +1,60 @@ +# CONSTANTS + +# MARGIN=0 +PADDING=0 +ANSI_RESET='\e[0m' +declare -A FG_COLORS +FG_COLORS["RED"]='\e[31m' +FG_COLORS["GREEN"]='\e[32m' +FG_COLORS["YELLOW"]='\e[93m' +FG_COLORS["BLUE"]='\e[34m' +FG_COLORS["CYAN"]='\e[36m' +FG_COLORS["MAGENTA"]='\e[95m' +FG_COLORS["GRAY"]='\e[90m' + +# FUNCTIONS + +function ansi_length { + local clean_text + clean_text=$(echo "$1" | sed 's/\x1B\[[0-9;]*m//g') + echo "${#clean_text}" +} + +function style_padding { + local padding_left=${PADDING_LEFT:-$PADDING} + local padding_right=${PADDING_RIGHT:-$PADDING} + + for _ in $(seq 1 "${padding_left}"); do builtin echo -n ' '; done + builtin echo -n "$1" + for _ in $(seq 1 "${padding_right}"); do builtin echo -n ' '; done +} + +function _style_fg { + [[ -n $1 ]] && echo "${FG_COLORS[$1]}" || true +} + +function style_ansi { + local fg + fg=$(_style_fg "${FG:-}") + # local bg=${BG:-} + [[ -n $fg ]] && builtin echo -en "$fg" + builtin echo -en "$1" + [[ -n $fg ]] && builtin echo -en "$ANSI_RESET" +} + +function style_block { + local content length + content=$(style_padding "$1") + length=$(ansi_length "$content") + length=$((length + 2)) + + builtin echo -n "╔" + for _ in $(seq 1 "${length}"); do builtin echo -n '═'; done + builtin echo "╗" + + builtin echo "║ $content ║" + + builtin echo -n "╚" + for _ in $(seq 1 "${length}"); do builtin echo -n '═'; done + builtin echo "╝" +} diff --git a/test/stub/scenario.bash b/test/stub/scenario.bash index 98f71e2..e84155a 100755 --- a/test/stub/scenario.bash +++ b/test/stub/scenario.bash @@ -14,6 +14,10 @@ function do_success { echo -n "$*" ) echo ']' + source "${MIAOU_BASH_DIR}/lib/ansi.bash" + local content + content=$(FG=MAGENTA style_ansi "this is success") + FG=GRAY PADDING=8 style_block "$content" } function do_unbound_variable {