new SubFS that can tell you the full FS path

This commit is contained in:
Neale Pickett 2021-12-03 17:58:08 -07:00
parent b6eea388d9
commit 55254234bf
4 changed files with 56 additions and 0 deletions

28
pkg/subfs/subfs.go Normal file
View File

@ -0,0 +1,28 @@
package transpile
import (
"io/fs"
"path"
)
func Sub(fsys fs.FS, dir string) (*SubFS, error) {
return &SubFS{fsys, dir}, nil
}
type SubFS struct {
fs.FS
dir string
}
func (f *SubFS) FullName(name string) string {
return path.Join(f.dir, name)
}
func (f *SubFS) Sub(dir string) (*SubFS, error) {
newFS, err := fs.Sub(f, dir)
newSubFS := SubFS{
FS: newFS,
dir: f.FullName(dir),
}
return &newSubFS, err
}

26
pkg/subfs/subfs_test.go Normal file
View File

@ -0,0 +1,26 @@
package transpile
import (
"io/fs"
"os"
"testing"
)
func TestSubFS(t *testing.T) {
testdata := os.DirFS("testdata")
if static, err := Sub(testdata, "static"); err != nil {
t.Error(err)
} else if buf, err := fs.ReadFile(static, "moo.txt"); err != nil {
t.Error(err)
} else if string(buf) != "moo.\n" {
t.Error("Wrong file contents")
} else if subdir, err := static.Sub("subdir"); err != nil {
t.Error(err)
} else if buf, err := fs.ReadFile(subdir, "moo2.txt"); err != nil {
t.Error(err)
} else if string(buf) != "moo too.\n" {
t.Error("Wrong file contents too")
} else if subdir.FullName("glue") != "static/subdir/glue" {
t.Error("Wrong full name")
}
}

1
pkg/subfs/testdata/moo.txt vendored Normal file
View File

@ -0,0 +1 @@
moo.

1
pkg/subfs/testdata/subdir/moo2.txt vendored Normal file
View File

@ -0,0 +1 @@
moo too.