From 1124356ee9f4d6065953d8aecf6e06c617e930c1 Mon Sep 17 00:00:00 2001 From: Kerin Millar Date: Mon, 3 Jun 2024 02:39:20 +0100 Subject: Add the hr() function to print a horizontal rule As based on the implementation in Maarten Billemont's bashlib library. Signed-off-by: Kerin Millar --- functions.sh | 28 ++++++++++++++++++++++++++++ test-functions | 24 ++++++++++++++++++++++++ 2 files changed, 52 insertions(+) diff --git a/functions.sh b/functions.sh index 30c2447..c077290 100644 --- a/functions.sh +++ b/functions.sh @@ -363,6 +363,34 @@ has_systemd() test -d /run/systemd } +# +# Prints a horizontal rule. If specified, the first parameter shall be taken as +# a string to be repeated in the course of composing the rule. Otherwise, it +# shall default to the . If specified, the second parameter shall +# define the length of the rule in characters. Otherwise, it shall default to +# the width of the terminal if such can be determined, or 80 if it cannot be. +# +hr() +{ + local length + + if is_int "$2"; then + length=$2 + elif _update_tty_level <&1; [ "${genfun_tty}" -eq 2 ]; then + length=${genfun_cols} + else + length=80 + fi + PATTERN=${1:--} awk -v "width=${length}" -f - <<-'EOF' + BEGIN { + while (length(rule) < width) { + rule = rule substr(ENVIRON["PATTERN"], 1, width - length(rule)) + } + print rule + } + EOF +} + # # Determines whether the first parameter is a valid identifier (variable name). # diff --git a/test-functions b/test-functions index bbb74f1..d90462e 100755 --- a/test-functions +++ b/test-functions @@ -484,6 +484,29 @@ test_trim() { iterate_tests 4 "$@" } +test_hr() { + # shellcheck disable=2183 + set -- \ + eq 0 "$(printf '%80s' | tr ' ' -)" N/A N/A \ + eq 0 "$(printf '%80s' | tr ' ' -)" - N/A \ + eq 0 '' - 0 \ + eq 0 - - 1 \ + eq 0 ----- - 5 \ + eq 0 '' xyz 0 \ + eq 0 x xyz 1 \ + eq 0 xyzxy xyz 5 + + callback() { + shift + expected=$1 + shift + test_description="hr $(_print_args "$@")" + test "$(hr "$@")" = "${expected}" + } + + iterate_tests 5 "$@" +} + iterate_tests() { slice_width=$1 shift @@ -547,6 +570,7 @@ test_edo || rc=1 test_srandom || rc=1 test_newest || rc=1 test_trim || rc=1 +test_hr || rc=1 cleanup_tmpdir -- cgit v1.2.3-65-gdbad