moovweb / gvm

Go Version Manager
http://github.com/moovweb/gvm
MIT License
10.14k stars 527 forks source link

Automatically apply a go.mod compatible version on change directory #331

Open mcandre opened 4 years ago

mcandre commented 4 years ago

When the user changes directories, automatically use a compatible Go version, or else warn the user that the Go version specified in go.mod is not installed.

gerardrubio commented 4 years ago

I'm using the script below with zsh based on the nvm script.

You have to append the contents at the end of your .zshrc file.

load-gomod() {
  local go_version="$(gvm-prompt)"
  local gomod_path="go.mod"

  if [ -f "$gomod_path" ]; then
    local gomod_go_version="$(grep -oP 'go\W+(.*)$' ${gomod_path} | sed -e 's/go /go/')"
    if [ "$gomod_go_version" = "" ]; then
      gvm use system
    elif [ "$gomod_go_version" != "$go_version" ]; then
      local gomod_go_version_installed="$(gvm list | grep ${gomod_go_version})"
      if [ "$gomod_go_version_installed" = "" ]; then
        echo "trying to install ${gomod_go_version}"
        gvm install ${gomod_go_version}
      fi
      gvm use ${gomod_go_version}
    fi
  elif [ "$go_version" != "system" ]; then
    gvm use system
  fi
}
add-zsh-hook chpwd load-gomod
load-gomod
BenKnigge commented 4 years ago

This is something that I would like to implement in the near future.