Direnv: Integrate with SDKMAN!

Created on 30 Nov 2018  路  6Comments  路  Source: direnv/direnv

Could we include SDKMAN! alongside rvm and friends, so that direnv works with SDKMAN out of the box?

Most helpful comment

This way it works:

  1. add to ~/.direnvrc the function
# iterate on pairs of [candidate] [version] and invoke `sdk use` on each of them 
use_sdk() {
  [[ -s "${SDKMAN_DIR}/bin/sdkman-init.sh" ]] && source "${SDKMAN_DIR}/bin/sdkman-init.sh"

  while (( "$#" >= 2 )); do
    local candidate=$1
    local candidate_version=$2
    sdk use $candidate $candidate_version

    shift 2
  done
}
  1. use it with pairs of candidates and versions within any .envrc
use sdk java 8.0.222.j9-adpt groovy 2.5.7

i.e. this sets both java and groovy to their specific versions.

All 6 comments

First write a function if your ~/.config/direnv/direnvrc and then document it in
https://github.com/direnv/direnv/wiki/Ruby

This way it works:

  1. add to ~/.direnvrc the function
# iterate on pairs of [candidate] [version] and invoke `sdk use` on each of them 
use_sdk() {
  [[ -s "${SDKMAN_DIR}/bin/sdkman-init.sh" ]] && source "${SDKMAN_DIR}/bin/sdkman-init.sh"

  while (( "$#" >= 2 )); do
    local candidate=$1
    local candidate_version=$2
    sdk use $candidate $candidate_version

    shift 2
  done
}
  1. use it with pairs of candidates and versions within any .envrc
use sdk java 8.0.222.j9-adpt groovy 2.5.7

i.e. this sets both java and groovy to their specific versions.

Normally SDKMAN checks for updates on each sdk call, so going into offline mode in the above snippet speeds things up considerably:

SDK_OFFLINE_MODE=true sdk use $candidate $candidate_version

In latest versions, environment variable is called SDKMAN_OFFLINE_MODE

Check sdkman-availability.sh

A challenge here is that sdkman's main entry point (sdk) is a bash function, and direnv doesn't let you define functions via envrc. So the above works, but it doesn't allow you to actually use sdk unless you add the sdkman-init.sh to your global shell dotfiles... in which case you might as well just use the sdkman_auto_env feature instead of direnv for this anyway.

I take that back: direnv is way less janky than sdkman_auto_env (it knows you might be in a subdirectory of the envrc dir, it reloads when the file changes, etc). So this code above is good, though you still have to also load sdkman-init.sh in your global shell dotfiles if you want to interact with sdk yourself.

Was this page helpful?
0 / 5 - 0 ratings