1
0
mirror of https://github.com/golang/go synced 2024-11-18 05:04:47 -07:00

godoc/vfs/mapfs: panic on invalid New usage

mapfs.New documentation says:

> Map keys should be forward slash-separated pathnames
> and not contain a leading slash.

It is invalid input if a provided path contains a leading slash, and it
causes the returned filesystem to have undefined behavior. Package mapfs
is often used in tests, so this can lead to a serious problem elsewhere.

Help detect invalid API usage sooner by validating input, and panicking
when it contains leading slashes. Programs that use mapfs API correctly
will be unaffected, and it will be faster for incorrect programs—if any
exist today or will be created in the future—to detect and correct such
problems.

Fixes golang/go#34591.

Change-Id: I77e5f0f4628edf83480604135f58bfb62e521d80
Reviewed-on: https://go-review.googlesource.com/c/tools/+/197859
Run-TryBot: Dmitri Shuralyov <dmitshur@golang.org>
TryBot-Result: Gobot Gobot <gobot@golang.org>
Reviewed-by: Jay Conrod <jayconrod@google.com>
This commit is contained in:
Dmitri Shuralyov 2019-09-28 16:31:27 -04:00
parent 058404a2dd
commit ead0a56930

View File

@ -7,6 +7,7 @@
package mapfs // import "golang.org/x/tools/godoc/vfs/mapfs"
import (
"fmt"
"io"
"os"
pathpkg "path"
@ -18,9 +19,21 @@ import (
)
// New returns a new FileSystem from the provided map.
// Map keys should be forward slash-separated pathnames
// and not contain a leading slash.
// Map keys must be forward slash-separated paths with
// no leading slash, such as "file1.txt" or "dir/file2.txt".
// New panics if any of the paths contain a leading slash.
func New(m map[string]string) vfs.FileSystem {
// Verify all provided paths are relative before proceeding.
var pathsWithLeadingSlash []string
for p := range m {
if strings.HasPrefix(p, "/") {
pathsWithLeadingSlash = append(pathsWithLeadingSlash, p)
}
}
if len(pathsWithLeadingSlash) > 0 {
panic(fmt.Errorf("mapfs.New: invalid paths with a leading slash: %q", pathsWithLeadingSlash))
}
return mapFS(m)
}