build: set $GOPATH/bin as default GOBIN for Config.BinPath

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>
This commit is contained in:
Aofei Sheng
2024-06-19 18:37:29 +08:00
parent 1f67434c8c
commit c46e4453c7

View File

@@ -18,6 +18,7 @@ package build
import ( import (
"archive/zip" "archive/zip"
"errors"
"fmt" "fmt"
"go/constant" "go/constant"
"go/token" "go/token"
@@ -70,7 +71,11 @@ type Config struct {
func NewDefaultConf(mode Mode) *Config { func NewDefaultConf(mode Mode) *Config {
bin := os.Getenv("GOBIN") bin := os.Getenv("GOBIN")
if bin == "" { 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{ conf := &Config{
BinPath: bin, BinPath: bin,
@@ -80,6 +85,21 @@ func NewDefaultConf(mode Mode) *Config {
return conf 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 { func DefaultAppExt() string {
if runtime.GOOS == "windows" { if runtime.GOOS == "windows" {
return ".exe" return ".exe"