From 82e357d6d5944fc5b0293085a0305fe328c505ea Mon Sep 17 00:00:00 2001 From: Ian Lance Taylor Date: Fri, 26 Aug 2022 19:22:50 -0700 Subject: [PATCH] os: use backslashes for DirFS on Windows Otherwise DirFS of a UNC path does not work. Fixes #54694 Change-Id: I82c1c436f7c26b3935c2cc4fd238daf094fc4d86 Reviewed-on: https://go-review.googlesource.com/c/go/+/426094 Reviewed-by: Ian Lance Taylor TryBot-Result: Gopher Robot Run-TryBot: Ian Lance Taylor Reviewed-by: Dmitri Shuralyov Run-TryBot: Ian Lance Taylor Reviewed-by: Alex Brainman Reviewed-by: hopehook Auto-Submit: Ian Lance Taylor --- src/os/file.go | 19 +++++++++++++++++-- 1 file changed, 17 insertions(+), 2 deletions(-) diff --git a/src/os/file.go b/src/os/file.go index e2eef8ec5d30dc..78677c2f8fdfd8 100644 --- a/src/os/file.go +++ b/src/os/file.go @@ -642,7 +642,7 @@ func (dir dirFS) Open(name string) (fs.File, error) { if !fs.ValidPath(name) || runtime.GOOS == "windows" && containsAny(name, `\:`) { return nil, &PathError{Op: "open", Path: name, Err: ErrInvalid} } - f, err := Open(string(dir) + "/" + name) + f, err := Open(dir.join(name)) if err != nil { return nil, err // nil fs.File } @@ -653,13 +653,28 @@ func (dir dirFS) Stat(name string) (fs.FileInfo, error) { if !fs.ValidPath(name) || runtime.GOOS == "windows" && containsAny(name, `\:`) { return nil, &PathError{Op: "stat", Path: name, Err: ErrInvalid} } - f, err := Stat(string(dir) + "/" + name) + f, err := Stat(dir.join(name)) if err != nil { return nil, err } return f, nil } +// join returns the path for name in dir. We can't always use "/" +// because that fails on Windows for UNC paths. +func (dir dirFS) join(name string) string { + if runtime.GOOS == "windows" && containsAny(name, "/") { + buf := []byte(name) + for i, b := range buf { + if b == '/' { + buf[i] = '\\' + } + } + name = string(buf) + } + return string(dir) + string(PathSeparator) + name +} + // ReadFile reads the named file and returns the contents. // A successful call returns err == nil, not err == EOF. // Because ReadFile reads the whole file, it does not treat an EOF from Read