From fa54ab02a8e30e6254537a706aec6abc21d89d97 Mon Sep 17 00:00:00 2001 From: izumin5210 Date: Tue, 30 Oct 2018 11:55:45 +0900 Subject: [PATCH] Fix file.Readdir to not return sub-dir contents --- fs/fs.go | 2 +- fs/walk_test.go | 62 +++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 63 insertions(+), 1 deletion(-) create mode 100644 fs/walk_test.go diff --git a/fs/fs.go b/fs/fs.go index 0cd95434..ca91bd91 100644 --- a/fs/fs.go +++ b/fs/fs.go @@ -160,7 +160,7 @@ func (f *httpFile) Readdir(count int) ([]os.FileInfo, error) { } prefix := f.Name() for fn, f := range f.file.fs.files { - if strings.HasPrefix(fn, prefix) && len(fn) > len(prefix) { + if strings.HasPrefix(fn, prefix) && len(fn) > len(prefix) && strings.Index(strings.TrimPrefix(fn, prefix), "/") < 1 { fis = append(fis, f.FileInfo) } } diff --git a/fs/walk_test.go b/fs/walk_test.go new file mode 100644 index 00000000..9ac452ee --- /dev/null +++ b/fs/walk_test.go @@ -0,0 +1,62 @@ +package fs + +import ( + "os" + "testing" +) + +func TestWalk(t *testing.T) { + type wantPath struct { + isDir bool + } + tests := []struct { + description string + zipData string + wantPaths map[string]wantPath + }{ + { + zipData: mustZipTree("../testdata/index"), + wantPaths: map[string]wantPath{ + "/": wantPath{isDir: true}, + "/index.html": wantPath{isDir: false}, + "/sub_dir": wantPath{isDir: true}, + "/sub_dir/index.html": wantPath{isDir: false}, + }, + }, + } + + for _, tc := range tests { + t.Run(tc.description, func(t *testing.T) { + Register(tc.zipData) + fs, err := New() + if err != nil { + t.Errorf("New() = %v", err) + return + } + + err = Walk(fs, "/", func(path string, info os.FileInfo, err error) error { + if err != nil { + t.Errorf("unexpected error = %v", err) + } + if wantPath, ok := tc.wantPaths[path]; ok { + if got, want := info.IsDir(), wantPath.isDir; got != want { + t.Errorf("IsDir(%v) = %t; want %t", path, got, want) + } + delete(tc.wantPaths, path) + } else { + t.Errorf("unexpected path = %v (info = %#v)", path, info) + } + + return nil + }) + + if err != nil { + t.Errorf("Walk(fs, \"/\", WalkFunc) = %v", err) + } + + if len(tc.wantPaths) != 0 { + t.Errorf("ignored paths: %v", tc.wantPaths) + } + }) + } +}