zsh: add function to prepend to PATH without duplicates

With this function, I can use the same logic in other configuration
files (e.g. `~/.local/etc/zsh/config.zsh`). This avoids duplication in
tmux sessions when prepending naively.
This commit is contained in:
Fernando Schauenburg 2024-07-15 21:37:28 +02:00
parent 154e9bf1b0
commit a70e2801af

View file

@ -31,12 +31,30 @@ have() {
# #
[ "$(uname -s)" = "Darwin" ] && { PATH=""; source /etc/profile; } [ "$(uname -s)" = "Darwin" ] && { PATH=""; source /etc/profile; }
# Prepend $2 to variable $1 using $3 as separator, but only if $2 is not already
# contained in $1. This is useful for prepending to PATH while avoiding
# duplicates.
prepend_unique() {
local var="$1"
local new="$2"
local sep="${3-:}" # Default separator is colon.
local old="${(P)var}"
case "${sep}${old}${sep}" in
*"${sep}${new}${sep}"*) # Skip duplicate.
;;
"${sep}${sep}") # Variable was empty, set without separator.
typeset -g $var="${new}"
;;
*) # Prepend with separator.
typeset -g $var="${new}${sep}${old}"
;;
esac
}
# Add custom bin dirs to PATH if they exist and are not already in PATH. # Add custom bin dirs to PATH if they exist and are not already in PATH.
while read -r dir; do while read -r dir; do
[ -d "$dir" ] && case ":${PATH:=$dir}:" in [ -d "$dir" ] && prepend_unique PATH "${dir}"
*:"$dir":*) ;; # already in PATH -> ignore
*) PATH="$dir:$PATH" ;; # not yet in PATH -> prepend it
esac
done <<EOL done <<EOL
$LOCAL_PREFIX/bin $LOCAL_PREFIX/bin
$LOCAL_PREFIX/opt/curl/bin $LOCAL_PREFIX/opt/curl/bin
@ -56,10 +74,7 @@ export PATH
# available. # available.
have manpath && MANPATH="$(unset MANPATH; manpath)" have manpath && MANPATH="$(unset MANPATH; manpath)"
while read -r dir; do while read -r dir; do
[ -d "$dir" ] && case ":${MANPATH:=$dir}:" in [ -d "$dir" ] && prepend_unique MANPATH "${dir}"
*:"$dir":*) ;; # already in MANPATH -> ignore
*) MANPATH="$dir:$MANPATH" ;; # not yet in MANPATH -> prepend it
esac
done <<EOL done <<EOL
$LOCAL_PREFIX/share/man $LOCAL_PREFIX/share/man
$LOCAL_PREFIX/opt/curl/share/man $LOCAL_PREFIX/opt/curl/share/man