asdf-direnv icon indicating copy to clipboard operation
asdf-direnv copied to clipboard

Suggestion: `env` command to use in scripts

Open lebdron opened this issue 2 years ago • 1 comments

asdf shell command sets an environment variable so that the same prompt can be used to call the right toolchain, while asdf direnv shell spawns a new shell or executes a command. This behavior makes it less convenient to use asdf direnv in scripts. The following is a workaround I currently use:

. "$HOME/.asdf/asdf.sh"
. "$HOME/.asdf/lib/utils.bash"
. "$HOME/.asdf/plugins/direnv/lib/tools-environment-lib.bash"

run_with_plugins() {
  while [ $# -gt 0 ]; do
    if [ "--" = "$1" ]; then
      shift
      break
    fi

    local plugin version

    plugin="$1"
    shift

    if [ $# -eq 0 ]; then
      log_error "Please specify a version for $plugin."
      exit 1
    fi
    version="$1"
    shift

    # log call removed

    # Set the appropriate ASDF_*_VERSION environment variable. This isn't
    # strictly necessary because we're not using shims, but it's nice because
    # it'll get `asdf current` to print out useful information, and if folks
    # have a special prompt configured (such as powerlevel10k), it'll know
    # about the newly activated tools.
    #
    # (this logic was copied from lib/commands/command-export-shell-version.bash)
    local upcase_name
    upcase_name=$(tr '[:lower:]-' '[:upper:]_' <<<"$plugin")
    local version_env_var="ASDF_${upcase_name}_VERSION"
    export "$version_env_var"="$version"

    # note that there is no `eval`
    _plugin_env_bash "$plugin" "$version" "$plugin $version not installed. Run 'asdf install $plugin $version' and try again."
  done
}

# example usage
eval "$(run_with_plugins rust 1.69.0)"
# `cargo` now available in the script, with the `bin` directory in PATH

The suggestion is to separate the logic with _plugin_env_bash from the current asdf direnv shell command so that it can be used separately, and reuse it in the current asdf direnv shell command.

lebdron avatar Jul 26 '23 02:07 lebdron

This sounds like a great idea! I'd accept a PR implementing this.

jfly avatar Aug 19 '23 02:08 jfly