Go: Fix check for whether it is safe to initialise a go.mod file in a given directory

This commit is contained in:
Michael B. Gale
2024-03-05 11:55:10 +00:00
parent 367ecf75d5
commit b1e0bc03ab

View File

@@ -439,8 +439,9 @@ func getBuildRoots(emitDiagnostics bool) (goWorkspaces []GoWorkspace, totalModul
for _, component := range components {
path = filepath.Join(path, component)
// Try to initialize a `go.mod` file automatically for the stray source files.
if !slices.Contains(goModDirs, path) {
// Try to initialize a `go.mod` file automatically for the stray source files if
// doing so would not place it in a parent directory of an existing `go.mod` file.
if !startsWithAnyOf(path, goModDirs) {
goWorkspaces = append(goWorkspaces, GoWorkspace{
BaseDir: path,
DepMode: GoGetNoModules,
@@ -477,6 +478,16 @@ func getBuildRoots(emitDiagnostics bool) (goWorkspaces []GoWorkspace, totalModul
return
}
// Determines whether `str` starts with any of `prefixes`.
func startsWithAnyOf(str string, prefixes []string) bool {
for _, prefix := range prefixes {
if strings.HasPrefix(str, prefix) {
return true
}
}
return false
}
// Finds Go workspaces in the current working directory.
func GetWorkspaceInfo(emitDiagnostics bool) []GoWorkspace {
bazelPaths := slices.Concat(