From 1097ef1706fe6f0a59ae7eefa41965a1d6dd8640 Mon Sep 17 00:00:00 2001 From: CrazyMax <1951866+crazy-max@users.noreply.github.com> Date: Sat, 10 Feb 2024 11:20:15 +0100 Subject: [PATCH] retrieve root path from FS instances Signed-off-by: CrazyMax <1951866+crazy-max@users.noreply.github.com> --- fs.go | 10 ++++++++++ fs_test.go | 44 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 54 insertions(+) diff --git a/fs.go b/fs.go index fe37019..007f8f5 100644 --- a/fs.go +++ b/fs.go @@ -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) { diff --git a/fs_test.go b/fs_test.go index fc60c1f..27e088e 100644 --- a/fs_test.go +++ b/fs_test.go @@ -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()