@@ -13,7 +13,6 @@ import (
1313 "path/filepath"
1414 "strconv"
1515 "strings"
16- "sync"
1716
1817 "golang.org/x/mod/modfile"
1918 "golang.org/x/mod/module"
@@ -30,8 +29,8 @@ type Opts struct {
3029
3130func New (ctx context.Context , opts Opts ) (* analysis.Analyzer , error ) {
3231 inst := & instance {
33- Opts : opts ,
34- modDirs : make ( map [ string ] string ),
32+ Opts : opts ,
33+ gusser : modpath . NewGuesser ( ),
3534 }
3635 a := & analysis.Analyzer {
3736 Name : "gosocialcheck" ,
@@ -46,13 +45,12 @@ func New(ctx context.Context, opts Opts) (*analysis.Analyzer, error) {
4645
4746type instance struct {
4847 Opts
49- modDirs map [string ]string // key: MODULE@VER
50- mu sync.RWMutex
48+ gusser * modpath.Guesser
5149}
5250
5351func run (ctx context.Context , inst * instance ) func (* analysis.Pass ) (any , error ) {
5452 return func (pass * analysis.Pass ) (any , error ) {
55- modDir , err := inst .guessModuleDir (pass )
53+ modDir , err := inst .gusser . GuessModuleDir (pass )
5654 if err != nil {
5755 return nil , err
5856 }
@@ -152,53 +150,3 @@ func parseGoSum(r io.Reader) (map[string]string, error) {
152150 }
153151 return res , sc .Err ()
154152}
155-
156- // guessModuleDir guess the directory that contains go.mod and go.sum.
157- // This function might not be robust.
158- //
159- // A workaround for https://github.com/golang/go/issues/73878
160- func (inst * instance ) guessModuleDir (pass * analysis.Pass ) (string , error ) {
161- if pass .Module == nil {
162- return "" , errors .New ("got nil module" )
163- }
164- mod := pass .Module .Path
165- modVer := pass .Module .Version
166- inst .mu .RLock ()
167- k := mod
168- if modVer != "" {
169- k += "@" + modVer
170- }
171- v := inst .modDirs [k ]
172- inst .mu .RUnlock ()
173- if v != "" {
174- return v , nil
175- }
176- if len (pass .Files ) == 0 {
177- return "" , fmt .Errorf ("%s: got no files" , mod )
178- }
179- var sawGoBuildDir bool
180- for _ , f := range pass .Files {
181- ff := pass .Fset .File (f .Pos ())
182- file := ff .Name ()
183- fileSlash := filepath .ToSlash (file )
184- if strings .Contains (fileSlash , "/go-build/" ) {
185- // tmp file like /Users/suda/Library/Caches/go-build/a0/a0f5d4693b09f2e3e24d18608f43e8540c5c52248877ef966df196f36bed5dfb-d
186- sawGoBuildDir = true
187- }
188- if strings .Contains (fileSlash , modpath .StripMajorVersion (mod )) {
189- dir , err := modpath .DirFromFileAndMod (file , mod , modVer )
190- if err != nil {
191- return "" , err
192- }
193- slog .Debug ("guessed module dir" , "mod" , mod , "modVer" , modVer , "dir" , dir )
194- inst .mu .Lock ()
195- inst .modDirs [k ] = dir
196- inst .mu .Unlock ()
197- return dir , nil
198- }
199- }
200- if sawGoBuildDir {
201- return "" , nil
202- }
203- return "" , fmt .Errorf ("could not guess the directory of module %s" , k )
204- }
0 commit comments