Skip to content

Commit b1e0bc0

Browse files
committed
Go: Fix check for whether it is safe to initialise a go.mod file in a given directory
1 parent 367ecf7 commit b1e0bc0

File tree

1 file changed

+13
-2
lines changed

1 file changed

+13
-2
lines changed

go/extractor/project/project.go

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -439,8 +439,9 @@ func getBuildRoots(emitDiagnostics bool) (goWorkspaces []GoWorkspace, totalModul
439439
for _, component := range components {
440440
path = filepath.Join(path, component)
441441

442-
// Try to initialize a `go.mod` file automatically for the stray source files.
443-
if !slices.Contains(goModDirs, path) {
442+
// Try to initialize a `go.mod` file automatically for the stray source files if
443+
// doing so would not place it in a parent directory of an existing `go.mod` file.
444+
if !startsWithAnyOf(path, goModDirs) {
444445
goWorkspaces = append(goWorkspaces, GoWorkspace{
445446
BaseDir: path,
446447
DepMode: GoGetNoModules,
@@ -477,6 +478,16 @@ func getBuildRoots(emitDiagnostics bool) (goWorkspaces []GoWorkspace, totalModul
477478
return
478479
}
479480

481+
// Determines whether `str` starts with any of `prefixes`.
482+
func startsWithAnyOf(str string, prefixes []string) bool {
483+
for _, prefix := range prefixes {
484+
if strings.HasPrefix(str, prefix) {
485+
return true
486+
}
487+
}
488+
return false
489+
}
490+
480491
// Finds Go workspaces in the current working directory.
481492
func GetWorkspaceInfo(emitDiagnostics bool) []GoWorkspace {
482493
bazelPaths := slices.Concat(

0 commit comments

Comments
 (0)