Skip to content

Commit ff8b1ed

Browse files
committed
feat: refactor relative path function for filesystem walker
Signed-off-by: Brian McGee <[email protected]>
1 parent a018c29 commit ff8b1ed

File tree

1 file changed

+18
-14
lines changed

1 file changed

+18
-14
lines changed

walk/filesystem.go

+18-14
Original file line numberDiff line numberDiff line change
@@ -8,35 +8,35 @@ import (
88
)
99

1010
type filesystemWalker struct {
11-
root string
12-
pathsCh chan string
11+
root string
12+
pathsCh chan string
13+
relPathOffset int
1314
}
1415

1516
func (f filesystemWalker) Root() string {
1617
return f.root
1718
}
1819

19-
func (f filesystemWalker) Walk(_ context.Context, fn WalkFunc) error {
20-
relPathOffset := len(f.root) + 1
21-
22-
relPathFn := func(path string) (string, error) {
23-
// quick optimization for the majority of use cases
24-
if len(path) >= relPathOffset && path[:len(f.root)] == f.root {
25-
return path[relPathOffset:], nil
26-
}
27-
// fallback to proper relative path resolution
28-
return filepath.Rel(f.root, path)
20+
func (f filesystemWalker) relPath(path string) (string, error) {
21+
// quick optimization for the majority of use cases
22+
if len(path) >= f.relPathOffset && path[:len(f.root)] == f.root {
23+
return path[f.relPathOffset:], nil
2924
}
25+
// fallback to proper relative path resolution
26+
return filepath.Rel(f.root, path)
27+
}
3028

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

36-
relPath, err := relPathFn(path)
35+
relPath, err := f.relPath(path)
3736
if err != nil {
3837
return fmt.Errorf("failed to determine a relative path for %s: %w", path, err)
3938
}
39+
4040
file := File{
4141
Path: path,
4242
RelPath: relPath,
@@ -55,5 +55,9 @@ func (f filesystemWalker) Walk(_ context.Context, fn WalkFunc) error {
5555
}
5656

5757
func NewFilesystem(root string, paths chan string) (Walker, error) {
58-
return filesystemWalker{root, paths}, nil
58+
return filesystemWalker{
59+
root: root,
60+
pathsCh: paths,
61+
relPathOffset: len(root) + 1,
62+
}, nil
5963
}

0 commit comments

Comments
 (0)