@@ -19,14 +19,12 @@ import (
1919 "bytes"
2020 "container/list"
2121 "fmt"
22- "github.com/cloudwego/abcoder/lang/log"
2322 "go/ast"
23+ "go/build"
2424 "go/types"
2525 "io"
2626 "os"
27- "os/exec"
2827 "path"
29- "path/filepath"
3028 "regexp"
3129 "strings"
3230 "sync"
@@ -109,55 +107,20 @@ func (pc *PackageCache) Set(key string, value bool) {
109107 pc .cache [key ] = elem
110108}
111109
112- var (
113- gorootOnce sync.Once
114- detectedGoRoot string
115- gorootErr error
116- )
117-
118- // getGoRoot 获取 go root 环境变量。
119- func getGoRoot () (string , error ) {
120- gorootOnce .Do (func () {
121- cmd := exec .Command ("go" , "env" , "GOROOT" )
122- var out bytes.Buffer
123- var stderr bytes.Buffer
124- cmd .Stdout = & out
125- cmd .Stderr = & stderr
126- err := cmd .Run ()
127- if err != nil {
128- log .Info ("'go env GOROOT' failed: %v, stderr: %s; \n `isSysPkg` will downgrade." , err , stderr .String ())
129- gorootErr = fmt .Errorf ("'go env GOROOT' failed: %w, stderr: %s" , err , stderr .String ())
130- return
131- }
132-
133- gorootPath := strings .TrimSpace (out .String ())
134- if gorootPath == "" {
135- log .Info ("'go env GOROOT' returns a empty string \n `isSysPkg` will downgrade." )
136- gorootErr = fmt .Errorf ("'go env GOROOT' returns a empty string" )
137- return
138- }
139- detectedGoRoot = gorootPath
140- })
141- return detectedGoRoot , gorootErr
142- }
143-
144110// IsStandardPackage 检查一个包是否为标准库,并使用内部缓存。
145111func (pc * PackageCache ) IsStandardPackage (path string ) bool {
146112 if isStd , found := pc .Get (path ); found {
147113 return isStd
148114 }
149115
150- goRoot , err := getGoRoot ()
151- // 当前环境找不到 go root,退化到最简单判断
152- var isStd bool
153- if err != nil || goRoot == "" {
154- isStd = ! strings .Contains (strings .Split (path , "/" )[0 ], "." )
155- } else {
156- pkgPath := filepath .Join (goRoot , "src" , path )
157- _ , err = os .Stat (pkgPath )
158- isStd = ! os .IsNotExist (err )
116+ pkg , err := build .Import (path , "" , build .FindOnly )
117+ if err != nil {
118+ // Cannot find the package, assume it's not a standard package
119+ pc .Set (path , false )
120+ return false
159121 }
160122
123+ isStd := pkg .Goroot
161124 pc .Set (path , isStd )
162125 return isStd
163126}
0 commit comments