From da73b21eabb132bb730364d87544763109381b7a Mon Sep 17 00:00:00 2001 From: jwillp Date: Tue, 27 Aug 2024 08:33:11 -0400 Subject: [PATCH] Add Rel method to filesystem --- filesystem.go | 9 +++++++++ filesystem_test.go | 4 ++++ 2 files changed, 13 insertions(+) diff --git a/filesystem.go b/filesystem.go index f03cba3..0be1156 100644 --- a/filesystem.go +++ b/filesystem.go @@ -17,6 +17,11 @@ type FileSystem interface { // differ depending on the underlying file system. Abs(location string) (string, error) + // Rel a relative path that is lexically equivalent to targetPath when joined to basepath with an + // intervening separator. + // [Join](basepath, Rel(basepath, targpath)) is equivalent to targpath itself. + Rel(basePath, targetPath string) (string, error) + // StatPath returns file information for the specified location. This typically // includes details like size, modification time, and whether the path is a file // or directory. @@ -54,6 +59,10 @@ var _ FileSystem = LocalFileSystem{} // LocalFileSystem is an implementation of a FileSystem that works on the local file system where this program is running. type LocalFileSystem struct{} +func (l LocalFileSystem) Rel(basePath, targetPath string) (string, error) { + return filepath.Rel(basePath, targetPath) +} + func (l LocalFileSystem) Remove(path string) error { return os.Remove(path) } diff --git a/filesystem_test.go b/filesystem_test.go index 98db315..0cce15e 100644 --- a/filesystem_test.go +++ b/filesystem_test.go @@ -53,6 +53,10 @@ type mockFileSystem struct { rmErr error } +func (m *mockFileSystem) Rel(basePath, targetPath string) (string, error) { + return strings.ReplaceAll(targetPath, basePath, "./"), nil +} + func (m *mockFileSystem) WriteFile(filePath string, data []byte, _ fs.FileMode) error { if m.writeFileErr != nil { return m.writeFileErr