2024-01-11 23:52:22 +03:00
|
|
|
package walk
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
2024-05-01 21:03:26 +03:00
|
|
|
"io/fs"
|
2024-01-10 18:45:57 +03:00
|
|
|
"os"
|
2024-01-11 23:52:22 +03:00
|
|
|
"path/filepath"
|
|
|
|
)
|
|
|
|
|
2024-01-12 14:33:14 +03:00
|
|
|
type filesystemWalker struct {
|
2024-01-10 18:45:57 +03:00
|
|
|
root string
|
|
|
|
paths []string
|
2024-01-11 23:52:22 +03:00
|
|
|
}
|
|
|
|
|
2024-01-12 14:33:14 +03:00
|
|
|
func (f filesystemWalker) Root() string {
|
2024-01-11 23:52:22 +03:00
|
|
|
return f.root
|
|
|
|
}
|
|
|
|
|
2024-05-01 21:03:26 +03:00
|
|
|
func (f filesystemWalker) Walk(_ context.Context, fn WalkFunc) error {
|
|
|
|
relPathOffset := len(f.root) + 1
|
|
|
|
|
|
|
|
relPathFn := func(path string) (relPath string) {
|
|
|
|
if len(path) >= relPathOffset {
|
|
|
|
relPath = path[relPathOffset:]
|
|
|
|
}
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
walkFn := func(path string, info fs.FileInfo, err error) error {
|
|
|
|
file := File{
|
|
|
|
Path: path,
|
|
|
|
RelPath: relPathFn(path),
|
|
|
|
Info: info,
|
|
|
|
}
|
|
|
|
return fn(&file, err)
|
|
|
|
}
|
|
|
|
|
2024-01-10 18:45:57 +03:00
|
|
|
if len(f.paths) == 0 {
|
2024-05-01 21:03:26 +03:00
|
|
|
return filepath.Walk(f.root, walkFn)
|
2024-01-10 18:45:57 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
for _, path := range f.paths {
|
|
|
|
info, err := os.Stat(path)
|
2024-05-01 21:03:26 +03:00
|
|
|
if err = filepath.Walk(path, walkFn); err != nil {
|
2024-01-10 18:45:57 +03:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2024-05-01 21:03:26 +03:00
|
|
|
file := File{
|
|
|
|
Path: path,
|
|
|
|
RelPath: relPathFn(path),
|
|
|
|
Info: info,
|
|
|
|
}
|
|
|
|
|
|
|
|
if err = fn(&file, err); err != nil {
|
2024-01-10 18:45:57 +03:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
2024-01-11 23:52:22 +03:00
|
|
|
}
|
|
|
|
|
2024-01-10 18:45:57 +03:00
|
|
|
func NewFilesystem(root string, paths []string) (Walker, error) {
|
|
|
|
return filesystemWalker{root, paths}, nil
|
2024-01-11 23:52:22 +03:00
|
|
|
}
|