Skip to content

Commit fb311d8

Browse files
cmd/go: fail if the user tries to modify the GOMOD environment variable
GOMOD was previously silently ignored. now fails if the user tries to modify the GOMOD environment variable and it is not the same as the module file that would be used. Fixes #51217
1 parent 2bbf383 commit fb311d8

File tree

1 file changed

+13
-11
lines changed

1 file changed

+13
-11
lines changed

src/cmd/go/internal/modload/init.go

+13-11
Original file line numberDiff line numberDiff line change
@@ -6,12 +6,18 @@ package modload
66

77
import (
88
"bytes"
9+
"cmd/go/internal/base"
10+
"cmd/go/internal/cfg"
11+
"cmd/go/internal/fsys"
12+
"cmd/go/internal/lockedfile"
13+
"cmd/go/internal/modconv"
14+
"cmd/go/internal/modfetch"
15+
"cmd/go/internal/search"
916
"context"
1017
"encoding/json"
1118
"errors"
1219
"fmt"
1320
"go/build"
14-
"internal/lazyregexp"
1521
"io/ioutil"
1622
"os"
1723
"path"
@@ -20,13 +26,7 @@ import (
2026
"strings"
2127
"sync"
2228

23-
"cmd/go/internal/base"
24-
"cmd/go/internal/cfg"
25-
"cmd/go/internal/fsys"
26-
"cmd/go/internal/lockedfile"
27-
"cmd/go/internal/modconv"
28-
"cmd/go/internal/modfetch"
29-
"cmd/go/internal/search"
29+
"internal/lazyregexp"
3030

3131
"golang.org/x/mod/modfile"
3232
"golang.org/x/mod/module"
@@ -409,6 +409,10 @@ func Init() {
409409
if !mustUseModules {
410410
return
411411
}
412+
} else if os.Getenv("GOMOD") != "" && filepath.Join(modRoot, "go.mod") != filepath.Join(modRoot, os.Getenv("GOMOD")) {
413+
// if GOMOD is set and does not point to module file, error as they must use -modfile
414+
// see golang.org/issue/51217
415+
base.Fatalf("go: GOMOD cannot be used to set the module file. use -modfile")
412416
} else {
413417
modRoots = []string{modRoot}
414418
}
@@ -1420,9 +1424,7 @@ Run 'go help mod init' for more information.
14201424
return "", fmt.Errorf(msg, dir, reason)
14211425
}
14221426

1423-
var (
1424-
importCommentRE = lazyregexp.New(`(?m)^package[ \t]+[^ \t\r\n/]+[ \t]+//[ \t]+import[ \t]+(\"[^"]+\")[ \t]*\r?\n`)
1425-
)
1427+
var importCommentRE = lazyregexp.New(`(?m)^package[ \t]+[^ \t\r\n/]+[ \t]+//[ \t]+import[ \t]+(\"[^"]+\")[ \t]*\r?\n`)
14261428

14271429
func findImportComment(file string) string {
14281430
data, err := os.ReadFile(file)

0 commit comments

Comments
 (0)