`go mod tidy` results in panic due to nil pointer dereference with the
current implementation. Though the panic occurs only in a limited situation
described as below, we had better fix it.
Situation:
- go.mod is in the exactly system's temporary directory (i.e. temp root)
- `go mod tidy` in temp root or in the child directory not having go.mod
No go.mod are found in the situation (i.e. *modFile is nil), however,
*modFile is referred without nil check.
Although just adding nil check works well, the better solution is using
ModFile() function. It works as same as the current implementation and,
in addition, it has either nil check and user friendly error indication.
With using it, users can get a proper error message like "go.mod file not
found in current directory or any parent directory" instead of a panic.
Fixes #51992
Change-Id: I2ba26762778acca6cd637c8eb8c615fb747063f4
Reviewed-on: https://go-review.googlesource.com/c/go/+/400554
Reviewed-by: Bryan Mills <bcmills@google.com>
TryBot-Result: Gopher Robot <gobot@golang.org>
Auto-Submit: Bryan Mills <bcmills@google.com>
Run-TryBot: Bryan Mills <bcmills@google.com>
Reviewed-by: David Chase <drchase@google.com>
}
// Update the go.mod file's Go version if necessary.
- modFile := MainModules.ModFile(MainModules.mustGetSingleMainModule())
- if ld.GoVersion != "" {
+ if modFile := ModFile(); modFile != nil && ld.GoVersion != "" {
modFile.AddGoStmt(ld.GoVersion)
}
}
--- /dev/null
+# Regression test for https://go.dev/issue/51992
+
+# 'go mod tidy' should error instead of throwing panic in the situation below.
+# 1. /tmp/go.mod exists
+# 2. run 'go mod tidy' in /tmp or in the child directory not having go.mod.
+
+[plan9] stop # Plan 9 has no $TMPDIR variable to set.
+
+env GOROOT=$TESTGO_GOROOT
+env TMP=$WORK
+env TMPDIR=$WORK
+mkdir $WORK/child
+
+! go mod tidy
+! stdout .
+stderr 'go: go.mod file not found in current directory or any parent directory'
+
+cd $WORK/child
+! go mod tidy
+! stdout .
+stderr 'go: go.mod file not found in current directory or any parent directory'
+
+-- $WORK/go.mod --
+module issue51992
+
+go 1.18