Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Suggestion: env command to use in scripts #179

Open
lebdron opened this issue Jul 26, 2023 · 1 comment
Open

Suggestion: env command to use in scripts #179

lebdron opened this issue Jul 26, 2023 · 1 comment

Comments

@lebdron
Copy link

lebdron commented Jul 26, 2023

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.

@jfly
Copy link
Contributor

jfly commented Aug 19, 2023

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Development

No branches or pull requests

2 participants