rehash: use associative array to hold registered shims

"hyperfine pyenv-rehash" before on my bash 4.4:

Time (mean ± σ):   172.8 ms ±   8.2 ms [User: 185.0 ms, System: 24.8 ms]
Range (min … max): 164.2 ms … 198.4 ms 15 runs

After:

Time (mean ± σ):   113.8 ms ±   2.8 ms [User: 127.1 ms, System: 26.1 ms]
Range (min … max): 108.0 ms … 117.6 ms 25 runs
This commit is contained in:
Ville Skyttä 2020-12-05 14:36:52 +02:00
parent b7efafe599
commit a804887307

View file

@ -123,34 +123,62 @@ make_shims() {
done
}
registered_shims=" "
if ((${BASH_VERSINFO[0]} > 3)); then
# Registers the name of a shim to be generated.
register_shim() {
registered_shims="${registered_shims}${1} "
}
declare -A registered_shims
# Install all the shims registered via `make_shims` or `register_shim` directly.
install_registered_shims() {
local shim file
for shim in $registered_shims; do
file="${SHIM_PATH}/${shim}"
[ -e "$file" ] || cp "$PROTOTYPE_SHIM_PATH" "$file"
done
}
# Registers the name of a shim to be generated.
register_shim() {
registered_shims["$1"]=1
}
# Once the registered shims have been installed, we make a second pass
# over the contents of the shims directory. Any file that is present
# in the directory but has not been registered as a shim should be
# removed.
remove_stale_shims() {
local shim
for shim in "$SHIM_PATH"/*; do
if [[ "$registered_shims" != *" ${shim##*/} "* ]]; then
rm -f "$shim"
fi
done
}
# Install all shims registered via `make_shims` or `register_shim` directly.
install_registered_shims() {
local shim file
for shim in "${!registered_shims[@]}"; do
file="${SHIM_PATH}/${shim}"
[ -e "$file" ] || cp "$PROTOTYPE_SHIM_PATH" "$file"
done
}
# Once the registered shims have been installed, we make a second pass
# over the contents of the shims directory. Any file that is present
# in the directory but has not been registered as a shim should be
# removed.
remove_stale_shims() {
local shim
for shim in "$SHIM_PATH"/*; do
if [[ ! ${registered_shims["${shim##*/}"]} ]]; then
rm -f "$shim"
fi
done
}
else # Same for bash < 4.
registered_shims=" "
register_shim() {
registered_shims="${registered_shims}${1} "
}
install_registered_shims() {
local shim file
for shim in $registered_shims; do
file="${SHIM_PATH}/${shim}"
[ -e "$file" ] || cp "$PROTOTYPE_SHIM_PATH" "$file"
done
}
remove_stale_shims() {
local shim
for shim in "$SHIM_PATH"/*; do
if [[ "$registered_shims" != *" ${shim##*/} "* ]]; then
rm -f "$shim"
fi
done
}
fi
shopt -s nullglob