Skip to content

cmd/go: do not allow main module to replace itself #36358

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions src/cmd/go/internal/modload/init.go
Original file line number Diff line number Diff line change
Expand Up @@ -1012,6 +1012,18 @@ func indexModFile(data []byte, modFile *modfile.File, needsFix bool) *modFileInd
if prev, dup := i.replace[r.Old]; dup && prev != r.New {
base.Fatalf("go: conflicting replacements for %v:\n\t%v\n\t%v", r.Old, prev, r.New)
}

if r.Old.Path == modFile.Module.Mod.Path && r.Old.Version == "" {
base.Fatalf("go: %s:%d: the main module (%s) cannot be replaced",
modFile.Syntax.Name, r.Syntax.Start.Line, modFile.Module.Mod.Path)
}

if modfile.IsDirectoryPath(r.New.Path) && HasModRoot() && ((search.IsRelativePath(r.New.Path) && filepath.Join(ModRoot(), r.New.Path) == ModRoot()) ||
search.InDir(r.New.Path, ModRoot()) == ".") {
base.Fatalf("go: %s:%d: the main module root directory (%s) cannot be a replacement for another module",
modFile.Syntax.Name, r.Syntax.Start.Line, modFile.Module.Mod.Path)
}

i.replace[r.Old] = r.New
}

Expand Down
38 changes: 38 additions & 0 deletions src/cmd/go/testdata/script/mod_replace_main.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
env GO111MODULE=on
[short] skip

cd fail1
! go list all
stderr 'go: \$WORK\/gopath\/src\/fail1\/go\.mod:3: the main module root directory \(example\.com\/m\) cannot be a replacement for another module'

cd ../fail2
! go list all
stderr 'go: \$WORK\/gopath\/src\/fail2\/go\.mod:3: the main module \(example\.com\/m\) cannot be replaced'

# Different module version can be replaced
cd ../success
go list all
stdout 'example.com/m'

-- fail1/go.mod --
module example.com/m

replace example.com/m2 => ./.

-- fail2/go.mod --
module example.com/m

replace example.com/m => example.com/m v1.1.1

-- success/go.mod --
module example.com/m

replace example.com/m v1.1.1 => example.com/m v1.1.2

-- fork/go.mod --
module example.com/m

-- success/m.go --
package main

func main() {}