]> Cypherpunks repositories - gostls13.git/commitdiff
os: add OpenInRoot
authorDamien Neil <dneil@google.com>
Tue, 19 Nov 2024 02:09:17 +0000 (18:09 -0800)
committerDamien Neil <dneil@google.com>
Wed, 20 Nov 2024 23:21:51 +0000 (23:21 +0000)
For #67002

Change-Id: If919ee8a5e3d90e91c7848330762e3254245fba1
Reviewed-on: https://go-review.googlesource.com/c/go/+/629555
Reviewed-by: Ian Lance Taylor <iant@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>

api/next/67002.txt
src/os/root.go
src/os/root_test.go

index 67c47969f4f3f67b410b3a9ddb7c054a5e82597e..72fdec837089dcaa906eb843149af86ef633d097 100644 (file)
@@ -1,3 +1,4 @@
+pkg os, func OpenInRoot(string, string) (*File, error) #67002
 pkg os, func OpenRoot(string) (*Root, error) #67002
 pkg os, method (*Root) Close() error #67002
 pkg os, method (*Root) Create(string) (*File, error) #67002
index c7d9b5b071215daf3e9d4ffc07b8970b518b5568..d9fc6358a504ce12d69360a9572ec238512e6bee 100644 (file)
@@ -14,6 +14,22 @@ import (
        "slices"
 )
 
+// OpenInRoot opens the file name in the directory dir.
+// It is equivalent to OpenRoot(dir) followed by opening the file in the root.
+//
+// OpenInRoot returns an error if any component of the name
+// references a location outside of dir.
+//
+// See [Root] for details and limitations.
+func OpenInRoot(dir, name string) (*File, error) {
+       r, err := OpenRoot(dir)
+       if err != nil {
+               return nil, err
+       }
+       defer r.Close()
+       return r.Open(name)
+}
+
 // Root may be used to only access files within a single directory tree.
 //
 // Methods on Root can only access files and directories beneath a root directory.
index 1cff474b939061dd97dc9f2f21eb59263cd0d5e1..288b4060cd8e404342880e2558fb19fcd67ec233 100644 (file)
@@ -1157,3 +1157,26 @@ func TestRootRaceRenameDir(t *testing.T) {
                }
        }
 }
+
+func TestOpenInRoot(t *testing.T) {
+       dir := makefs(t, []string{
+               "file",
+               "link => ../ROOT/file",
+       })
+       f, err := os.OpenInRoot(dir, "file")
+       if err != nil {
+               t.Fatalf("OpenInRoot(`file`) = %v, want success", err)
+       }
+       f.Close()
+       for _, name := range []string{
+               "link",
+               "../ROOT/file",
+               dir + "/file",
+       } {
+               f, err := os.OpenInRoot(dir, name)
+               if err == nil {
+                       f.Close()
+                       t.Fatalf("OpenInRoot(%q) = nil, want error", name)
+               }
+       }
+}