Skip to content

Commit 1a79171

Browse files
do not allow main module to replace itself
Change-Id: I6d94f00e1c607581ba32253ba00fe4110e2bb5b8
1 parent bbd25d2 commit 1a79171

File tree

2 files changed

+64
-0
lines changed

2 files changed

+64
-0
lines changed

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

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -426,6 +426,7 @@ func InitMod() {
426426
legacyModInit()
427427
}
428428

429+
checkMainModuleReplaces()
429430
modFileToBuildList()
430431
setDefaultBuildMod()
431432
if cfg.BuildMod == "vendor" {
@@ -555,6 +556,29 @@ func setDefaultBuildMod() {
555556
}
556557
}
557558

559+
// checkMainModuleReplaces checks that modFile is not trying to replace
560+
// main module with the same version of itself
561+
func checkMainModuleReplaces() {
562+
for _, r := range modFile.Replace {
563+
isMainModule := r.Old.Path == modFile.Module.Mod.Path
564+
isSameVersion := r.Old.Path == r.New.Path && r.Old.Version == r.New.Version
565+
566+
if isMainModule {
567+
if isSameVersion {
568+
base.Fatalf("go: replacing main module with the same version of itself is forbidden")
569+
}
570+
571+
if modfile.IsDirectoryPath(r.New.Path) {
572+
newModFilePath, _ := filepath.Abs(r.New.Path)
573+
574+
if newModFilePath == ModRoot() {
575+
base.Fatalf("go: replace directive points to current main module directory")
576+
}
577+
}
578+
}
579+
}
580+
}
581+
558582
// checkVendorConsistency verifies that the vendor/modules.txt file matches (if
559583
// go 1.14) or at least does not contradict (go 1.13 or earlier) the
560584
// requirements and replacements listed in the main module's go.mod file.
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
env GO111MODULE=on
2+
[short] skip
3+
4+
# Replace directive that points to current main module directory isn't allowed
5+
cd fail1
6+
! go list all
7+
stderr 'go: replace directive points to current main module directory'
8+
9+
# Replace directive that attempts to replace main module with the same version of itself isn't allowed
10+
cd ../fail2
11+
! go list all
12+
stderr 'go: replacing main module with the same version of itself is forbidden'
13+
14+
# Replace directive that resolves to another directory with main module is allowed
15+
cd ../success
16+
go list all
17+
stdout 'example.com/m'
18+
19+
-- fail1/go.mod --
20+
module example.com/m
21+
22+
replace example.com/m => ./.
23+
24+
-- fail2/go.mod --
25+
module example.com/m
26+
27+
replace example.com/m v1.1.1 => example.com/m v1.1.1
28+
29+
-- success/go.mod --
30+
module example.com/m
31+
32+
replace example.com/m => ../fork
33+
34+
-- fork/go.mod --
35+
module example.com/m
36+
37+
-- success/m.go --
38+
package main
39+
40+
func main() {}

0 commit comments

Comments
 (0)