Skip to content

Commit

Permalink
Refactor _lp_get_home_tilde_collapsed() to not echo
Browse files Browse the repository at this point in the history
Rename _lp_get_home_tilde_collapsed() to __lp_pwd_tilde().
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.

Change the function to return with a variable instead of an echo with
subshell. This is one of the first functions to get this treatment. Any
function run in a subshell will add slowdowns, so refactor the function
to return its data in a variable instead. This means refactoring how it
is used as well.

Add a bit of testing for the function while we are at it.
  • Loading branch information
Rycieos committed Nov 25, 2020
1 parent 26dfaff commit 28c13f2
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 5 deletions.
17 changes: 12 additions & 5 deletions liquidprompt
Original file line number Diff line number Diff line change
Expand Up @@ -696,10 +696,11 @@ _lp_hostname() {
fi
}

_lp_get_home_tilde_collapsed()
{
__lp_pwd_tilde() {
# Needs to be in a variable, as different versions of Bash treat '~' in a
# substitution differently
local tilde="~"
echo "${PWD/#$HOME/$tilde}"
lp_pwd_tilde="${PWD/#$HOME/$tilde}"
}

# Shorten the path of the current working directory
Expand All @@ -719,7 +720,10 @@ _lp_shorten_path()

local ret=

local p="$(_lp_get_home_tilde_collapsed)"
local lp_pwd_tilde p
__lp_pwd_tilde
p="$lp_pwd_tilde"

local mask="${LP_MARK_SHORTEN_PATH}"
local -i max_len=$(( ${COLUMNS:-80} * LP_PATH_LENGTH / 100 ))

Expand Down Expand Up @@ -773,7 +777,10 @@ _lp_shorten_path()
# Liquid Prompt can calculate this number under two conditions, path shortening
# must be disabled and PROMPT_DIRTRIM must be already set.
_lp_set_dirtrim() {
local p="$(_lp_get_home_tilde_collapsed)"
local lp_pwd_tilde p
__lp_pwd_tilde
p="$lp_pwd_tilde"

local -i max_len="${COLUMNS:-80}*$LP_PATH_LENGTH/100"
local -i dt=0

Expand Down
11 changes: 11 additions & 0 deletions tests/test_utils.sh
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,17 @@ function test_line_count {
assertEquals "null string" $(printf %s "$test_string" | wc -l) $count
}

function test_pwd_tilde {
typeset HOME="/home/user"
typeset PWD="/a/test/path"
__lp_pwd_tilde
assertEquals "unchanged path" "$PWD" "$lp_pwd_tilde"

PWD="/home/user/a/test/path"
__lp_pwd_tilde
assertEquals "shorted home path" "~/a/test/path" "$lp_pwd_tilde"
}

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

0 comments on commit 28c13f2

Please sign in to comment.