From bb11a8b95bb34ad49c323191f416cc98656da8d9 Mon Sep 17 00:00:00 2001 From: Piotr Findeisen Date: Tue, 11 Jun 2024 11:26:16 +0200 Subject: [PATCH] Add `jenv with` command to pick version for single command This adds new command to jenv: `jenv with `. It executes the command with the specified version being effective. It's roughly equivalent to invoking `jenv shell ` and then `` except that it doesn't change the state of running shell. Alternative could be to invoke `jenv shell` in a subshell, like ( jenv shell ; ; ) except that this actually doesn't work, because the version set by `jenv shell` becomes effective only after `_jenv_export_hook` executes, which in turn happens only when the prompt is printed. The other alternative is to set the JAVA_HOME explicitly JAVA_HOME=~/.jenv/versions/ This works, but is arguably verbose. --- libexec/jenv-with | 48 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100755 libexec/jenv-with diff --git a/libexec/jenv-with b/libexec/jenv-with new file mode 100755 index 0000000..e5a3bf6 --- /dev/null +++ b/libexec/jenv-with @@ -0,0 +1,48 @@ +#!/usr/bin/env bash +# +# Summary: Execute command with specific Java version +# +# Usage: jenv with +# +# Executes the command with specified Java version being effective. +# This is equivalent to running `jenv shell ' followed by +# the command, but without changing the shell environment. +# +# should be a string matching a Java version known to jenv. +# The special version string `system' will use your default system Java. +# Run `jenv versions' for a list of available Java versions. + +set -e +[ -n "$JENV_DEBUG" ] && set -x + +if [ "$#" -lt 2 ]; then + jenv-help --usage with >&2 + exit 1 +fi + +# Provide jenv completions +if [ "$1" = "--complete" ]; then + echo --unset + echo system + exec jenv-versions --bare +fi + +export JENV_VERSION="$1" +shift + +# reset & isolate from outer environment +export JAVA_HOME="" +export JENV_FORCEJAVAHOME=true +export JDK_HOME="" +export JENV_FORCEJDKHOME=true + +# TODO or may `jenv-javahome` should exit with 0 (printing nothing) when JENV_VERSION=system +# then we would not need to special case `system` here +if [ "$JENV_VERSION" != "system" ]; then + JAVA_HOME=$(jenv-javahome) + if [ -n "$JAVA_HOME" ] && [ -e "$JAVA_HOME/bin/javac" ]; then + JDK_HOME="$JAVA_HOME" + fi +fi + +exec "$@"