]> Cypherpunks repositories - gostls13.git/commitdiff
os: add DirFS
authorRuss Cox <rsc@golang.org>
Mon, 6 Jul 2020 15:27:38 +0000 (11:27 -0400)
committerRuss Cox <rsc@golang.org>
Tue, 20 Oct 2020 17:52:48 +0000 (17:52 +0000)
It will inevitably be important to be able to pass an operating system
directory to code written to expect an fs.FS.

os.DirFS provides the conversion.

For #41190.

Change-Id: Id1a8fcbe4c7a30de2c47dea0504e9481a88b1b39
Reviewed-on: https://go-review.googlesource.com/c/go/+/243911
Trust: Russ Cox <rsc@golang.org>
Reviewed-by: Rob Pike <r@golang.org>
src/os/file.go
src/os/os_test.go

index 5f16fc28eeada55cb0193ea3c0d7802c499ebce8..835d44ab8c42f3d5ce92f5161fc3b658fa1115ed 100644 (file)
@@ -45,6 +45,7 @@ import (
        "internal/poll"
        "internal/testlog"
        "io"
+       "io/fs"
        "runtime"
        "syscall"
        "time"
@@ -608,3 +609,21 @@ func isWindowsNulName(name string) bool {
        }
        return true
 }
+
+// DirFS returns a file system (an fs.FS) for the tree of files rooted at the directory dir.
+func DirFS(dir string) fs.FS {
+       return dirFS(dir)
+}
+
+type dirFS string
+
+func (dir dirFS) Open(name string) (fs.File, error) {
+       if !fs.ValidPath(name) {
+               return nil, &PathError{Op: "open", Path: name, Err: ErrInvalid}
+       }
+       f, err := Open(string(dir) + "/" + name)
+       if err != nil {
+               return nil, err // nil fs.File
+       }
+       return f, nil
+}
index 8f14263401d3093813b2c1999a7406fb77d8d7d8..378ddf58dd4434d8efc8a8e57924e13c841be7dd 100644 (file)
@@ -23,6 +23,7 @@ import (
        "sync"
        "syscall"
        "testing"
+       "testing/fstest"
        "time"
 )
 
@@ -2671,3 +2672,9 @@ func TestOpenFileKeepsPermissions(t *testing.T) {
                t.Errorf("Stat after OpenFile is %v, should be writable", fi.Mode())
        }
 }
+
+func TestDirFS(t *testing.T) {
+       if err := fstest.TestFS(DirFS("./signal"), "signal.go", "internal/pty/pty.go"); err != nil {
+               t.Fatal(err)
+       }
+}