From c46e4453c72eade5006936b4a9c4772a09977f16 Mon Sep 17 00:00:00 2001 From: Aofei Sheng Date: Wed, 19 Jun 2024 18:37:29 +0800 Subject: [PATCH] build: set $GOPATH/bin as default GOBIN for Config.BinPath MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit We should avoid making any changes to GOROOT whenever possible. Fixes #361 Update internal/build/build.go Co-authored-by: 张之阳 <51194195+luoliwoshang@users.noreply.github.com> --- internal/build/build.go | 22 +++++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) diff --git a/internal/build/build.go b/internal/build/build.go index e7174e3e..fe610c32 100644 --- a/internal/build/build.go +++ b/internal/build/build.go @@ -18,6 +18,7 @@ package build import ( "archive/zip" + "errors" "fmt" "go/constant" "go/token" @@ -70,7 +71,11 @@ type Config struct { func NewDefaultConf(mode Mode) *Config { bin := os.Getenv("GOBIN") if bin == "" { - bin = filepath.Join(runtime.GOROOT(), "bin") + gopath, err := envGOPATH() + if err != nil { + panic(fmt.Errorf("cannot get GOPATH: %v", err)) + } + bin = filepath.Join(gopath, "bin") } conf := &Config{ BinPath: bin, @@ -80,6 +85,21 @@ func NewDefaultConf(mode Mode) *Config { return conf } +func envGOPATH() (string, error) { + if gopath := os.Getenv("GOPATH"); gopath != "" { + return gopath, nil + } + home, err := os.UserHomeDir() + if err != nil { + return "", err + } + gopath := filepath.Join(home, "go") + if filepath.Clean(gopath) == filepath.Clean(runtime.GOROOT()) { + return "", errors.New("cannot set GOROOT as GOPATH") + } + return gopath, nil +} + func DefaultAppExt() string { if runtime.GOOS == "windows" { return ".exe"