Skip to content

Commit

Permalink
os: add OpenInRoot
Browse files Browse the repository at this point in the history
For #67002

Change-Id: If919ee8a5e3d90e91c7848330762e3254245fba1
Reviewed-on: https://go-review.googlesource.com/c/go/+/629555
Reviewed-by: Ian Lance Taylor <[email protected]>
LUCI-TryBot-Result: Go LUCI <[email protected]>
  • Loading branch information
neild committed Nov 20, 2024
1 parent a1b5394 commit c315862
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 0 deletions.
1 change: 1 addition & 0 deletions api/next/67002.txt
Original file line number Diff line number Diff line change
@@ -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
Expand Down
16 changes: 16 additions & 0 deletions src/os/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
23 changes: 23 additions & 0 deletions src/os/root_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
}
}

0 comments on commit c315862

Please sign in to comment.