diff options
author | 2024-06-03 02:39:20 +0100 | |
---|---|---|
committer | 2024-06-12 08:06:42 +0100 | |
commit | 1124356ee9f4d6065953d8aecf6e06c617e930c1 (patch) | |
tree | dca719183926b9adfce4247696f9a9c713aadb1d | |
parent | Add the trim() function (diff) | |
download | gentoo-functions-1124356ee9f4d6065953d8aecf6e06c617e930c1.tar.gz gentoo-functions-1124356ee9f4d6065953d8aecf6e06c617e930c1.tar.bz2 gentoo-functions-1124356ee9f4d6065953d8aecf6e06c617e930c1.zip |
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 <kfm@plushkava.net>
-rw-r--r-- | functions.sh | 28 | ||||
-rwxr-xr-x | test-functions | 24 |
2 files changed, 52 insertions, 0 deletions
diff --git a/functions.sh b/functions.sh index 30c2447..c077290 100644 --- a/functions.sh +++ b/functions.sh @@ -364,6 +364,34 @@ has_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 <hyphen-minus>. 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). # is_identifier() 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 |