diff --git a/lib/bash/str/README.md b/lib/bash/str/README.md index c9afbe0..cf628b9 100644 --- a/lib/bash/str/README.md +++ b/lib/bash/str/README.md @@ -59,7 +59,8 @@ str_join joined "|" parts - Trim helpers remove Bash character-class whitespace from the requested side. - String transformation helpers mutate the named variable in place and do not print transformed values for command substitution. -- Predicate helpers return shell status and do not print output. +- Predicate helpers require exactly two arguments, return shell status, and do + not print output. - `str_split` preserves empty fields between repeated delimiters. - `str_join` preserves empty array elements, including trailing empty elements. - Named string, result, and array arguments must be valid Bash variable names. diff --git a/lib/bash/str/lib_str.sh b/lib/bash/str/lib_str.sh index 49e5f39..3da8426 100644 --- a/lib/bash/str/lib_str.sh +++ b/lib/bash/str/lib_str.sh @@ -56,39 +56,45 @@ str_trim() { str_contains() { local value="${1-}" needle="${2-}" + + assert_arg_count "$#" 2 [[ "$value" == *"$needle"* ]] } str_starts_with() { local value="${1-}" prefix="${2-}" + + assert_arg_count "$#" 2 [[ "$value" == "$prefix"* ]] } str_ends_with() { local value="${1-}" suffix="${2-}" + + assert_arg_count "$#" 2 [[ "$value" == *"$suffix" ]] } str_split() { - local result_name="${1-}" value="${2-}" separator="${3-}" + local __str_split_result_name="${1-}" __str_split_value="${2-}" __str_split_separator="${3-}" assert_arg_count "$#" 3 - assert_variable_name "$result_name" + assert_variable_name "$__str_split_result_name" - local -a fields=() - local remainder="$value" + local -a __str_split_fields=() + local __str_split_remainder="$__str_split_value" - if [[ -z "$separator" ]]; then - fields=("$value") + if [[ -z "$__str_split_separator" ]]; then + __str_split_fields=("$__str_split_value") else - while [[ "$remainder" == *"$separator"* ]]; do - fields+=("${remainder%%"$separator"*}") - remainder="${remainder#*"$separator"}" + while [[ "$__str_split_remainder" == *"$__str_split_separator"* ]]; do + __str_split_fields+=("${__str_split_remainder%%"$__str_split_separator"*}") + __str_split_remainder="${__str_split_remainder#*"$__str_split_separator"}" done - fields+=("$remainder") + __str_split_fields+=("$__str_split_remainder") fi - eval "$result_name=(\"\${fields[@]}\")" + eval "$__str_split_result_name=(\"\${__str_split_fields[@]}\")" } str_join() { diff --git a/lib/bash/str/tests/lib_str.bats b/lib/bash/str/tests/lib_str.bats index 0c74813..c7d2214 100644 --- a/lib/bash/str/tests/lib_str.bats +++ b/lib/bash/str/tests/lib_str.bats @@ -102,6 +102,29 @@ EOF fi } +@test "string predicate helpers reject incorrect argument counts" { + local script="$TEST_TMPDIR/string-predicate-arity.sh" + + create_script "$script" <