Skip to content

Commit 6c11e80

Browse files
committed
perf: optimize *_HOME export & PATH prepend to speed up init in popular shells
1 parent dda90bc commit 6c11e80

File tree

1 file changed

+25
-15
lines changed

1 file changed

+25
-15
lines changed

src/main/bash/sdkman-path-helpers.sh

Lines changed: 25 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -50,28 +50,38 @@ function __sdkman_set_candidate_home() {
5050
}
5151

5252
function __sdkman_export_candidate_home() {
53-
local candidate_name="$1"
54-
local candidate_dir="$2"
55-
local candidate_home_var="$(echo ${candidate_name} | tr '[:lower:]' '[:upper:]')_HOME"
56-
export $(echo "$candidate_home_var")="$candidate_dir"
57-
}
53+
local candidate_name="$1" candidate_dir="$2" upcase_name
5854

59-
function __sdkman_determine_candidate_bin_dir() {
60-
local candidate_dir="$1"
61-
if [[ -d "${candidate_dir}/bin" ]]; then
62-
echo "${candidate_dir}/bin"
55+
# Generate home variable name using shell-specific methods
56+
# to avoid heavy-weight fork/exec system calls.
57+
58+
if [ -n "${ZSH_VERSION-}" ]; then
59+
# zsh: uppercase via ${value:u}
60+
upcase_name="${candidate_name:u}"
61+
elif [ -n "${BASH_VERSION-}" ] && [ "${BASH_VERSINFO[0]:-0}" -ge 4 ] 2>/dev/null; then
62+
# bash 4.0+: uppercase via ${value^^}
63+
upcase_name="${candidate_name^^}"
6364
else
64-
echo "$candidate_dir"
65+
# POSIX fallback: call external tool for conversion
66+
upcase_name="$(printf %s "$candidate_name" | tr '[:lower:]' '[:upper:]')"
6567
fi
68+
69+
export "${upcase_name}_HOME=$candidate_dir"
6670
}
6771

6872
function __sdkman_prepend_candidate_to_path() {
69-
local candidate_dir candidate_bin_dir
73+
local candidate_dir="$1"
74+
75+
# Caution: external commands are costly here
76+
# since this function runs inside a loop.
7077

71-
candidate_dir="$1"
72-
candidate_bin_dir=$(__sdkman_determine_candidate_bin_dir "$candidate_dir")
73-
echo "$PATH" | grep -q "$candidate_dir" || PATH="${candidate_bin_dir}:${PATH}"
74-
unset CANDIDATE_BIN_DIR
78+
# replace the original candidate_dir with the 'bin' subfolder if it exists
79+
if [ -d "${candidate_dir}/bin" ]; then
80+
candidate_dir="${candidate_dir}/bin"
81+
fi
82+
# prepend PATH with the candidate_dir if it is not already there,
83+
# assuming the dir doesn't contain meta-characters like ? * []
84+
[[ ":$PATH:" == *":$candidate_dir:"* ]] || PATH="${candidate_dir}:${PATH}"
7585
}
7686

7787
function __sdkman_link_candidate_version() {

0 commit comments

Comments
 (0)