diff options
-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 |