diff --git a/src/cmd/go/internal/modload/init.go b/src/cmd/go/internal/modload/init.go index 41b3b9df1ba20c..feee871fc44145 100644 --- a/src/cmd/go/internal/modload/init.go +++ b/src/cmd/go/internal/modload/init.go @@ -1710,6 +1710,15 @@ func findModulePath(dir string) (string, error) { badPathErr = err break } + // Ensure the inferred path is valid. + if _, _, ok := module.SplitPathVersion(path); !ok { + if strings.HasPrefix(path, "gopkg.in/") { + badPathErr = errors.New("module paths beginning with gopkg.in/ must always have a major version suffix in the form of .vN") + } else { + badPathErr = errors.New("major version suffixes must be in the form of /vN and are only allowed for v2 or later") + } + break + } return path, nil } } diff --git a/src/cmd/go/testdata/script/mod_init_empty.txt b/src/cmd/go/testdata/script/mod_init_empty.txt index d197a79a67180c..2ae22271f03b0f 100644 --- a/src/cmd/go/testdata/script/mod_init_empty.txt +++ b/src/cmd/go/testdata/script/mod_init_empty.txt @@ -8,6 +8,26 @@ stdout '^example.com$' go list stdout '^example.com$' +# Reset $GOPATH +env GOPATH=$WORK/gopath + +# 'go mod init' should not create a go.mod file in v0 or v1 directory. +cd $GOPATH/src/example.com/m/v0 +! go mod init +stderr '(?s)^go: cannot determine module path for source directory (.*v0) \(bad module path inferred from directory in GOPATH: major version suffixes must be in the form of /vN and are only allowed for v2 or later\)(.*)' + +cd $GOPATH/src/example.com/m/v1 +! go mod init +stderr '(?s)^go: cannot determine module path for source directory (.*v1) \(bad module path inferred from directory in GOPATH: major version suffixes must be in the form of /vN and are only allowed for v2 or later\)(.*)' + +cd $GOPATH/src/example.com/m/v2 +go mod init +stderr '^go: creating new go.mod: module example.com/m/v2$' + +cd $GOPATH/src/gopkg.in/m +! go mod init +stderr '(?s)^go: cannot determine module path for source directory (.*m) \(bad module path inferred from directory in GOPATH: module paths beginning with gopkg.in/ must always have a major version suffix in the form of .vN\)(.*)' + -- go.mod -- module example.com @@ -19,3 +39,12 @@ func main() {} -- $WORK/invalid-gopath This is a text file, not a directory. + +-- example.com/m/v0/main.go -- +package main +-- example.com/m/v1/main.go -- +package main +-- example.com/m/v2/main.go -- +package main +-- gopkg.in/m/main.go -- +package main