Skip to content

Commit

Permalink
Merge pull request #78 from cpunion/fs-parent-sub
Browse files Browse the repository at this point in the history
fs: add fs.Parent, fs.Sub
  • Loading branch information
xushiwei committed Sep 13, 2023
2 parents a99ed55 + 6479e03 commit d2cf56f
Show file tree
Hide file tree
Showing 2 changed files with 80 additions and 0 deletions.
43 changes: 43 additions & 0 deletions http/fs/fs.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import (
"net/http"
"os"
"path"
"strings"
"time"
)

Expand Down Expand Up @@ -258,3 +259,45 @@ func Root() http.FileSystem {
}

// -----------------------------------------------------------------------------------------

type parentFS struct {
parentDir string
fs http.FileSystem
}

func Parent(parentDir string, fs http.FileSystem) http.FileSystem {
parentDir = strings.TrimSuffix(parentDir, "/")
if !strings.HasPrefix(parentDir, "/") {
parentDir = "/" + parentDir
}
return &parentFS{parentDir, fs}
}

func (p *parentFS) Open(name string) (f http.File, err error) {
if !strings.HasPrefix(name, p.parentDir) {
return nil, os.ErrNotExist
}
path := name[len(p.parentDir):]
return p.fs.Open(path)
}

// -----------------------------------------------------------------------------------------

type subFS struct {
subDir string
fs http.FileSystem
}

func Sub(fs http.FileSystem, subDir string) http.FileSystem {
subDir = strings.TrimSuffix(subDir, "/")
if !strings.HasPrefix(subDir, "/") {
subDir = "/" + subDir
}
return &subFS{subDir, fs}
}

func (p *subFS) Open(name string) (f http.File, err error) {
return p.fs.Open(p.subDir + name)
}

// -----------------------------------------------------------------------------------------
37 changes: 37 additions & 0 deletions http/fs/fs_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
package fs

import (
"os"
"testing"
)

func TestParentFS(t *testing.T) {
fs := FilesWithContent("a.txt", "a")
if _, err := fs.Open("/a.txt"); err != nil {
t.Fatal(err)
}

p := Parent("files", fs)
if _, err := p.Open("/files/a.txt"); err != nil {
t.Fatal(err)
}
_, err := p.Open("/a.txt")
if err == nil {
t.Fatal("expect error")
}
if !os.IsNotExist(err) {
t.Fatalf("expect os.IsNotExist(err) but got %v", err)
}
}

func TestSubFS(t *testing.T) {
fs := FilesWithContent("files/a.txt", "a")
if _, err := fs.Open("/files/a.txt"); err != nil {
t.Fatal(err)
}

s := Sub(fs, "files")
if _, err := s.Open("/a.txt"); err != nil {
t.Fatal(err)
}
}

0 comments on commit d2cf56f

Please sign in to comment.