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 <matloob@golang.org>
TryBot-Result: Gopher Robot <gobot@golang.org>
Reviewed-by: Russ Cox <rsc@golang.org>
Reviewed-by: Michael Matloob <matloob@golang.org>
This commit is contained in:
Michael Matloob 2022-06-08 14:26:44 -04:00
parent 1858ea5d85
commit 1292176bc9
2 changed files with 39 additions and 1 deletions

View file

@ -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.

View file

@ -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