From d7a03da8edf37ee4fa9c1200040db001c6c3e56a Mon Sep 17 00:00:00 2001 From: tenkoh Date: Fri, 15 Apr 2022 13:58:08 +0900 Subject: [PATCH] cmd/go: mod tidy returns proper error with /tmp/go.mod `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 TryBot-Result: Gopher Robot Auto-Submit: Bryan Mills Run-TryBot: Bryan Mills Reviewed-by: David Chase --- src/cmd/go/internal/modload/load.go | 3 +-- src/cmd/go/testdata/script/mod_tidy_temp.txt | 26 ++++++++++++++++++++ 2 files changed, 27 insertions(+), 2 deletions(-) create mode 100644 src/cmd/go/testdata/script/mod_tidy_temp.txt diff --git a/src/cmd/go/internal/modload/load.go b/src/cmd/go/internal/modload/load.go index 29c0a4280a..5214a9e2d1 100644 --- a/src/cmd/go/internal/modload/load.go +++ b/src/cmd/go/internal/modload/load.go @@ -421,8 +421,7 @@ func LoadPackages(ctx context.Context, opts PackageOpts, patterns ...string) (ma } // 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) } } diff --git a/src/cmd/go/testdata/script/mod_tidy_temp.txt b/src/cmd/go/testdata/script/mod_tidy_temp.txt new file mode 100644 index 0000000000..635a336bca --- /dev/null +++ b/src/cmd/go/testdata/script/mod_tidy_temp.txt @@ -0,0 +1,26 @@ +# 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 -- 2.50.0