Skip to content

Commit 4042b90

Browse files
seankhliaogopherbot
authored andcommitted
os: implement fs.ReadFileFS for DirFS
Use the os.ReadFile implementation to handle sysfs files not reporting size properly via stat. Fixes #53761 Change-Id: I6f34515e8a211e3659f4f6c3598fae7ec0c86975 Reviewed-on: https://go-review.googlesource.com/c/go/+/416775 TryBot-Result: Gopher Robot <[email protected]> Reviewed-by: Bryan Mills <[email protected]> Auto-Submit: Ian Lance Taylor <[email protected]> Reviewed-by: Rob Pike <[email protected]> Reviewed-by: Ian Lance Taylor <[email protected]> Run-TryBot: Rob Pike <[email protected]> Reviewed-by: hopehook <[email protected]> Run-TryBot: Ian Lance Taylor <[email protected]>
1 parent 8c30460 commit 4042b90

File tree

2 files changed

+29
-0
lines changed

2 files changed

+29
-0
lines changed

src/os/file.go

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -652,6 +652,18 @@ func (dir dirFS) Open(name string) (fs.File, error) {
652652
return f, nil
653653
}
654654

655+
// The ReadFile method calls the [ReadFile] function for the file
656+
// with the given name in the directory. The function provides
657+
// robust handling for small files and special file systems.
658+
// Through this method, dirFS implements [io/fs.ReadFileFS].
659+
func (dir dirFS) ReadFile(name string) ([]byte, error) {
660+
fullname, err := dir.join(name)
661+
if err != nil {
662+
return nil, &PathError{Op: "readfile", Path: name, Err: err}
663+
}
664+
return ReadFile(fullname)
665+
}
666+
655667
func (dir dirFS) Stat(name string) (fs.FileInfo, error) {
656668
fullname, err := dir.join(name)
657669
if err != nil {

src/os/os_test.go

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3114,6 +3114,23 @@ func TestReadFileProc(t *testing.T) {
31143114
}
31153115
}
31163116

3117+
func TestDirFSReadFileProc(t *testing.T) {
3118+
t.Parallel()
3119+
3120+
fsys := DirFS("/")
3121+
name := "proc/sys/fs/pipe-max-size"
3122+
if _, err := fs.Stat(fsys, name); err != nil {
3123+
t.Skip()
3124+
}
3125+
data, err := fs.ReadFile(fsys, name)
3126+
if err != nil {
3127+
t.Fatal(err)
3128+
}
3129+
if len(data) == 0 || data[len(data)-1] != '\n' {
3130+
t.Fatalf("read %s: not newline-terminated: %q", name, data)
3131+
}
3132+
}
3133+
31173134
func TestWriteStringAlloc(t *testing.T) {
31183135
if runtime.GOOS == "js" {
31193136
t.Skip("js allocates a lot during File.WriteString")

0 commit comments

Comments
 (0)