Skip to content

Commit c315862

Browse files
committed
os: add OpenInRoot
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]>
1 parent a1b5394 commit c315862

File tree

3 files changed

+40
-0
lines changed

3 files changed

+40
-0
lines changed

api/next/67002.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
pkg os, func OpenInRoot(string, string) (*File, error) #67002
12
pkg os, func OpenRoot(string) (*Root, error) #67002
23
pkg os, method (*Root) Close() error #67002
34
pkg os, method (*Root) Create(string) (*File, error) #67002

src/os/root.go

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,22 @@ import (
1414
"slices"
1515
)
1616

17+
// OpenInRoot opens the file name in the directory dir.
18+
// It is equivalent to OpenRoot(dir) followed by opening the file in the root.
19+
//
20+
// OpenInRoot returns an error if any component of the name
21+
// references a location outside of dir.
22+
//
23+
// See [Root] for details and limitations.
24+
func OpenInRoot(dir, name string) (*File, error) {
25+
r, err := OpenRoot(dir)
26+
if err != nil {
27+
return nil, err
28+
}
29+
defer r.Close()
30+
return r.Open(name)
31+
}
32+
1733
// Root may be used to only access files within a single directory tree.
1834
//
1935
// Methods on Root can only access files and directories beneath a root directory.

src/os/root_test.go

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1157,3 +1157,26 @@ func TestRootRaceRenameDir(t *testing.T) {
11571157
}
11581158
}
11591159
}
1160+
1161+
func TestOpenInRoot(t *testing.T) {
1162+
dir := makefs(t, []string{
1163+
"file",
1164+
"link => ../ROOT/file",
1165+
})
1166+
f, err := os.OpenInRoot(dir, "file")
1167+
if err != nil {
1168+
t.Fatalf("OpenInRoot(`file`) = %v, want success", err)
1169+
}
1170+
f.Close()
1171+
for _, name := range []string{
1172+
"link",
1173+
"../ROOT/file",
1174+
dir + "/file",
1175+
} {
1176+
f, err := os.OpenInRoot(dir, name)
1177+
if err == nil {
1178+
f.Close()
1179+
t.Fatalf("OpenInRoot(%q) = nil, want error", name)
1180+
}
1181+
}
1182+
}

0 commit comments

Comments
 (0)