Skip to content

Commit

Permalink
feat: refactor relative path function for filesystem walker
Browse files Browse the repository at this point in the history
Signed-off-by: Brian McGee <brian@bmcgee.ie>
  • Loading branch information
brianmcgee committed Jul 9, 2024
1 parent a018c29 commit ff8b1ed
Showing 1 changed file with 18 additions and 14 deletions.
32 changes: 18 additions & 14 deletions walk/filesystem.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,35 +8,35 @@ import (
)

type filesystemWalker struct {
root string
pathsCh chan string
root string
pathsCh chan string
relPathOffset int
}

func (f filesystemWalker) Root() string {
return f.root
}

func (f filesystemWalker) Walk(_ context.Context, fn WalkFunc) error {
relPathOffset := len(f.root) + 1

relPathFn := func(path string) (string, error) {
// quick optimization for the majority of use cases
if len(path) >= relPathOffset && path[:len(f.root)] == f.root {
return path[relPathOffset:], nil
}
// fallback to proper relative path resolution
return filepath.Rel(f.root, path)
func (f filesystemWalker) relPath(path string) (string, error) {
// quick optimization for the majority of use cases
if len(path) >= f.relPathOffset && path[:len(f.root)] == f.root {
return path[f.relPathOffset:], nil
}
// fallback to proper relative path resolution
return filepath.Rel(f.root, path)
}

func (f filesystemWalker) Walk(_ context.Context, fn WalkFunc) error {
walkFn := func(path string, info fs.FileInfo, _ error) error {
if info == nil {
return fmt.Errorf("no such file or directory '%s'", path)
}

relPath, err := relPathFn(path)
relPath, err := f.relPath(path)
if err != nil {
return fmt.Errorf("failed to determine a relative path for %s: %w", path, err)
}

file := File{
Path: path,
RelPath: relPath,
Expand All @@ -55,5 +55,9 @@ func (f filesystemWalker) Walk(_ context.Context, fn WalkFunc) error {
}

func NewFilesystem(root string, paths chan string) (Walker, error) {
return filesystemWalker{root, paths}, nil
return filesystemWalker{
root: root,
pathsCh: paths,
relPathOffset: len(root) + 1,
}, nil
}

0 comments on commit ff8b1ed

Please sign in to comment.