From 1292176bc98be4b7b9d24abec05e88b3dbd89e21 Mon Sep 17 00:00:00 2001 From: Michael Matloob Date: Wed, 8 Jun 2022 14:26:44 -0400 Subject: [PATCH] cmd/go: clean paths before using them form index functions We use str.TrimFilePathPrefix to trim the module root prefix and get the relative path of each package in the module when scanning the module and in the RelPath function. Make sure to clean the path before indexing and in RelPath to ensure that each path starts with that prefix, because walk will clean the root path before joining each subdirectory path to it. Change-Id: I1dc1eddbd42030eb6d5d8e76a8675f94216447c3 Reviewed-on: https://go-review.googlesource.com/c/go/+/411118 Run-TryBot: Michael Matloob TryBot-Result: Gopher Robot Reviewed-by: Russ Cox Reviewed-by: Michael Matloob --- src/cmd/go/internal/modindex/read.go | 3 +- .../script/list_replace_absolute_windows.txt | 37 +++++++++++++++++++ 2 files changed, 39 insertions(+), 1 deletion(-) create mode 100644 src/cmd/go/testdata/script/list_replace_absolute_windows.txt diff --git a/src/cmd/go/internal/modindex/read.go b/src/cmd/go/internal/modindex/read.go index daa85762be..6ec3a6b3af 100644 --- a/src/cmd/go/internal/modindex/read.go +++ b/src/cmd/go/internal/modindex/read.go @@ -112,6 +112,7 @@ func Get(modroot string) (*ModuleIndex, error) { if modroot == "" { panic("modindex.Get called with empty modroot") } + modroot = filepath.Clean(modroot) isModCache := str.HasFilePathPrefix(modroot, cfg.GOMODCACHE) return openIndex(modroot, isModCache) } @@ -217,7 +218,7 @@ func (mi *ModuleIndex) Packages() []string { // RelPath returns the path relative to the module's root. func (mi *ModuleIndex) RelPath(path string) string { - return str.TrimFilePathPrefix(path, mi.modroot) + return str.TrimFilePathPrefix(filepath.Clean(path), mi.modroot) // mi.modroot is already clean } // ImportPackage is the equivalent of build.Import given the information in ModuleIndex. diff --git a/src/cmd/go/testdata/script/list_replace_absolute_windows.txt b/src/cmd/go/testdata/script/list_replace_absolute_windows.txt new file mode 100644 index 0000000000..6f5d737ade --- /dev/null +++ b/src/cmd/go/testdata/script/list_replace_absolute_windows.txt @@ -0,0 +1,37 @@ +# Test a replacement with an absolute path (so the path isn't +# cleaned by having filepath.Abs called on it). This checks +# whether the modindex logic cleans the modroot path before using +# it. + +[!windows] [short] skip + +go run print_go_mod.go # use this program to write a go.mod with an absolute path +cp stdout go.mod + +go list -modfile=go.mod all +-- print_go_mod.go -- +//go:build ignore +package main + +import ( + "fmt" + "os" +) + +func main() { + work := os.Getenv("WORK") +fmt.Printf(`module example.com/mod + +require b.com v0.0.0 + +replace b.com => %s\gopath\src/modb +`, work) +} +-- a.go -- +package a + +import _ "b.com/b" +-- modb/go.mod -- +module b.com +-- modb/b/b.go -- +package b -- 2.50.0