Skip to content
This repository has been archived by the owner on Jun 3, 2023. It is now read-only.

Commit

Permalink
fix: GOROOT detection
Browse files Browse the repository at this point in the history
  • Loading branch information
ldez committed Jun 1, 2023
1 parent 84475ef commit 087bc78
Showing 1 changed file with 25 additions and 3 deletions.
28 changes: 25 additions & 3 deletions internal/utils/variables.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,12 @@ package utils

import (
"fmt"
"go/build"
"os"
"os/exec"
"path"
"path/filepath"
"runtime"
"strings"
)

type Expander interface {
Expand Down Expand Up @@ -39,13 +42,14 @@ type gostdExpander struct {
cache []string
}

// We can do this as all imports that are not root are either prefixed with a domain
// Expand We can do this as all imports that are not root are either prefixed with a domain
// or prefixed with `./` or `/` to dictate it is a local file reference
func (e *gostdExpander) Expand() ([]string, error) {
if len(e.cache) != 0 {
return e.cache, nil
}
root := path.Join(build.Default.GOROOT, "src")

root := path.Join(findGOROOT(), "src")
fs, err := os.ReadDir(root)
if err != nil {
return nil, fmt.Errorf("could not read GOROOT directory: %w", err)
Expand All @@ -61,6 +65,24 @@ func (e *gostdExpander) Expand() ([]string, error) {
return pkgPrefix, nil
}

// code borrowed from https://github.com/golang/tools/blob/86c93e8732cce300d0270bce23117456ce92bb17/cmd/godoc/goroot.go#L15-L30
func findGOROOT() string {
if env := os.Getenv("GOROOT"); env != "" {
return filepath.Clean(env)
}
def := filepath.Clean(runtime.GOROOT())
if runtime.Compiler == "gccgo" {
// gccgo has no real GOROOT, and it certainly doesn't
// depend on the executable's location.
return def
}
out, err := exec.Command("go", "env", "GOROOT").Output()
if err != nil {
return def
}
return strings.TrimSpace(string(out))
}

func ExpandSlice(sl []string, exp ExpanderMap) ([]string, error) {
for i, s := range sl {
f, found := exp[s]
Expand Down

0 comments on commit 087bc78

Please sign in to comment.