Skip to content

Commit 058bf32

Browse files
committed
Go: Initialise Go modules for stray source files outside of existing modules
1 parent d99ad01 commit 058bf32

File tree

1 file changed

+26
-9
lines changed

1 file changed

+26
-9
lines changed

go/extractor/project/project.go

Lines changed: 26 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import (
55
"os"
66
"path/filepath"
77
"regexp"
8+
"slices"
89
"sort"
910
"strings"
1011

@@ -411,16 +412,32 @@ func getBuildRoots(emitDiagnostics bool) (goWorkspaces []GoWorkspace, totalModul
411412
diagnostics.EmitGoFilesOutsideGoModules(goModPaths)
412413
}
413414

414-
// Try to initialize a `go.mod` file automatically for the stray source files.
415-
initGoModForLegacyProject(".")
415+
// We need to initialise Go modules for the stray source files. Our goal is to initialise
416+
// as few Go modules as possible, in locations which do not overlap with existing Go
417+
// modules.
418+
for _, straySourceFile := range straySourceFiles {
419+
path := "."
420+
components := strings.Split(filepath.Dir(straySourceFile), string(os.PathSeparator))
421+
422+
for _, component := range components {
423+
path = filepath.Join(path, component)
424+
425+
// Try to initialize a `go.mod` file automatically for the stray source files.
426+
if !slices.Contains(goModDirs, path) {
427+
initGoModForLegacyProject(path)
428+
goWorkspaces = append(goWorkspaces, GoWorkspace{
429+
BaseDir: path,
430+
Modules: loadGoModules([]string{filepath.Join(path, "go.mod")}),
431+
DepMode: GoGetWithModules,
432+
ModMode: ModUnset,
433+
})
434+
totalModuleFiles += 1
435+
goModDirs = append(goModDirs, path)
436+
break
437+
}
438+
}
439+
}
416440

417-
goWorkspaces = append(goWorkspaces, GoWorkspace{
418-
BaseDir: ".",
419-
Modules: loadGoModules([]string{"go.mod"}),
420-
DepMode: GoGetWithModules,
421-
ModMode: ModUnset,
422-
})
423-
totalModuleFiles += 1
424441
return
425442
}
426443

0 commit comments

Comments
 (0)