Skip to content

Instantly share code, notes, and snippets.

@tekener
Last active December 12, 2019 20:00
Show Gist options
  • Save tekener/ebec43834d106ad7f5688f5ae4ba4213 to your computer and use it in GitHub Desktop.
Save tekener/ebec43834d106ad7f5688f5ae4ba4213 to your computer and use it in GitHub Desktop.
Automatically choose sdkman java version as defined in .sdkmanjavarc file when entering directory (oh-my-zshell, .nvmrc)
sdkman_find_sdkmanjavarc () {
local dir
dir="$(sdkman_find_up '.sdkmanjavarc')"
if [ -e "${dir}/.sdkmanjavarc" ]
then
echo "${dir}/.sdkmanjavarc"
fi
}
sdkman_find_up () {
local path_
path_="${PWD}"
while [ "${path_}" != "" ] && [ ! -f "${path_}/${1-}" ]
do
path_=${path_%/*}
done
echo "${path_}"
}
load-sdkjavarc() {
local sdkjava_use_output
local java_home_dir
local sdkjava_default_version=${SDKMAN_JAVA_DEFAULT_VERSION:-11.0.5.j9-adpt}
local sdkjavarc_path="$(sdkman_find_sdkmanjavarc)"
if [[ -L "$JAVA_HOME" ]]; then
java_home_dir="$(readlink $JAVA_HOME)"
else
java_home_dir="$JAVA_HOME"
fi
local sdkjava_version_output="$(basename $java_home_dir)"
local sdkjava_version="${sdkjava_version_output##* }"
if test -f "$sdkjavarc_path"; then
# read version from ".sdkmanjavarc stipping comments
local sdkjavarc_version=`sed '/^[[:blank:]]*#/d;s/#.*//' $sdkjavarc_path`
local validationPattern=" |'"
if [[ $sdkjavarc_version =~ $validationPattern ]]
then
echo "invalid $sdkjavarc_path containing whitespaces"
fi
if [ "$sdkjavarc_version" != "$sdkjava_version" ]; then
echo "Found $sdkjavarc_path with version $sdkjavarc_version"
sdk use java $sdkjavarc_version
fi
elif [ "$sdkjava_version" != "$sdkjava_default_version" ]; then
echo "Reverting to sdkman java default version"
sdk use java $sdkjava_default_version
fi
}
autoload -U add-sdkjavarc-hook
add-zsh-hook chpwd load-sdkjavarc
load-sdkjavarc
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment