Skip to content

Commit

Permalink
Add __lp_line_count() function and tests
Browse files Browse the repository at this point in the history
This functions as a "poor man's" "wc -l". It's faster, but due to shell
quirks, it can be more difficult to use. The trick is that, like
'wc -l', this function counts newline characters, which means if the
input string has none, it will return 0.

The double underscore ("__") marks the function as "private" or
Liquidprompt only. Themes and users should not use it, as it should only
be run when the current directory changes, and Liquidprompt will control
that.
  • Loading branch information
Rycieos committed Nov 25, 2020
1 parent e122d21 commit a314677
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 0 deletions.
7 changes: 7 additions & 0 deletions liquidprompt
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,13 @@ else
return
fi

# Count the number of lines in the input string. A faster subsitute for 'wc -l'.
# input: $1; a single string of input.
# return: $count; the number of newline characters in the string.
__lp_line_count() {
local var="${1//[!$'\n']}"
count=${#var}
}

# Store $2 (or $?) as a true/false value in variable named $1
# $? is propagated
Expand Down
38 changes: 38 additions & 0 deletions tests/test_utils.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@

. ../liquidprompt --no-activate

function test_line_count {
typeset test_string="a normal string"
__lp_line_count "$test_string"
assertEquals "normal 1 line string" $(printf %s "$test_string" | wc -l) $count

test_string="\
a
longer
string"
__lp_line_count "$test_string"
assertEquals "3 line string" $(printf %s "$test_string" | wc -l) $count

test_string="\
a
longer
string
with many consecutive breaks"
__lp_line_count "$test_string"
assertEquals "consecutive blank lines string" $(printf %s "$test_string" | wc -l) $count

test_string=""
__lp_line_count "$test_string"
assertEquals "null string" $(printf %s "$test_string" | wc -l) $count
}

if [ -n "${ZSH_VERSION-}" ]; then
SHUNIT_PARENT="$0"
setopt shwordsplit
fi

. ./shunit2

0 comments on commit a314677

Please sign in to comment.