Skip to content

Commit

Permalink
build: set $GOPATH/bin as default GOBIN for Config.BinPath
Browse files Browse the repository at this point in the history
We should avoid making any changes to GOROOT whenever possible.

Fixes #361

Update internal/build/build.go

Co-authored-by: 张之阳 <[email protected]>
  • Loading branch information
aofei and luoliwoshang committed Jun 19, 2024
1 parent 1f67434 commit 1fbbf01
Showing 1 changed file with 28 additions and 1 deletion.
29 changes: 28 additions & 1 deletion internal/build/build.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ package build

import (
"archive/zip"
"errors"
"fmt"
"go/constant"
"go/token"
Expand Down Expand Up @@ -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,
Expand All @@ -80,6 +85,28 @@ func NewDefaultConf(mode Mode) *Config {
return conf
}

func envGOPATH() (string, error) {
if gopath := os.Getenv("GOPATH"); gopath != "" {
return gopath, nil
}
env := "HOME"
switch runtime.GOOS {
case "windows":
env = "USERPROFILE"
case "plan9":
env = "home"
}
home := os.Getenv(env)
if home == "" {
return "", fmt.Errorf("%s is not set", env)
}
def := filepath.Join(home, "go")
if filepath.Clean(def) == filepath.Clean(runtime.GOROOT()) {
return "", errors.New("cannot set GOROOT as GOPATH")
}
return def, nil
}

func DefaultAppExt() string {
if runtime.GOOS == "windows" {
return ".exe"
Expand Down

0 comments on commit 1fbbf01

Please sign in to comment.