Skip to content

Commit

Permalink
retrieve root path from FS instances
Browse files Browse the repository at this point in the history
Signed-off-by: CrazyMax <[email protected]>
  • Loading branch information
crazy-max committed Feb 10, 2024
1 parent c14d0ee commit 1097ef1
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 0 deletions.
10 changes: 10 additions & 0 deletions fs.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,16 @@ type fs struct {
root string
}

// GetRoot returns root dir for FS implementations created by NewFS.
// Returns an empty string and false if the FS implementation does not have a
// root path.
func GetRoot(fsys FS) (string, bool) {
if fsi, ok := fsys.(*fs); ok {
return fsi.root, true
}
return "", false
}

func (fs *fs) Walk(ctx context.Context, target string, fn gofs.WalkDirFunc) error {
seenFiles := make(map[uint64]string)
return filepath.WalkDir(filepath.Join(fs.root, target), func(path string, dirEntry gofs.DirEntry, walkErr error) (retErr error) {
Expand Down
44 changes: 44 additions & 0 deletions fs_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,50 @@ import (
"github.com/tonistiigi/fsutil/types"
)

func TestGetRoot(t *testing.T) {
testCases := []struct {
name string
setupFS func() FS
wantRoot string
wantOk bool
}{
{
name: "Valid FS",
setupFS: func() FS {
fsys, err := NewFS("/tmp")
require.NoError(t, err)
return fsys
},
wantRoot: filepath.FromSlash("/tmp"),
wantOk: true,
},
{
name: "Invalid FS",
setupFS: func() FS {
return nil
},
wantRoot: "",
wantOk: false,
},
}
for _, tt := range testCases {
tt := tt
t.Run(tt.name, func(t *testing.T) {
fsys := tt.setupFS()
if fsys == nil && tt.wantOk {
t.Fatal("FS setup returned nil, but test case expects a valid FS")
}
gotRoot, gotOk := GetRoot(fsys)
if gotOk != tt.wantOk {
t.Errorf("GetRoot() gotOk = %v, want %v", gotOk, tt.wantOk)
}
if gotRoot != tt.wantRoot {
t.Errorf("GetRoot() gotRoot = %q, want %q", gotRoot, tt.wantRoot)
}
})
}
}

func TestWalk(t *testing.T) {
tmpDir := t.TempDir()

Expand Down

0 comments on commit 1097ef1

Please sign in to comment.