MCPcopy Create free account
hub / github.com/VirusTotal/vt-cli / NewFileDirReader

Function NewFileDirReader

utils/file_utils.go:31–69  ·  view source on GitHub ↗

NewFileDirReader reads all files from the given directory `fileDir`. It can optionally traverse subdirectories if `recursive` is true, and will limit recursion to `maxDepth` levels if specified. Uses the standard library's `filepath.WalkDir` to traverse directories efficiently, and `fs.SkipDir` to

(fileDir string, recursive bool, maxDepth int)

Source from the content-addressed store, hash-verified

29// Uses the standard library's `filepath.WalkDir` to traverse directories efficiently,
30// and `fs.SkipDir` to skip directories when recursion is disabled or maxDepth is reached.
31func NewFileDirReader(fileDir string, recursive bool, maxDepth int) (*StringArrayReader, error) {
32 var filePaths []string
33 rootDepth := pathDepth(fileDir)
34
35 var errs []error
36
37 // filePaths is safely appended within WalkDir because WalkDir executes the callback sequentially.
38 // No race conditions occur in this implementation, even with slice reallocation.
39 err := filepath.WalkDir(fileDir, func(path string, d fs.DirEntry, err error) error {
40 if err != nil {
41 errs = append(errs, fmt.Errorf("%s: %w", path, err))
42 if d != nil && d.IsDir() {
43 return fs.SkipDir
44 }
45 return nil
46 }
47
48 if d != nil && !d.IsDir() {
49 filePaths = append(filePaths, path)
50 return nil
51 }
52
53 currentDepth := pathDepth(path) - rootDepth
54 // we skip directory if recursive is disabled or
55 // if we reached configured maxDepth
56 if !recursive && path != fileDir ||
57 currentDepth >= maxDepth {
58 return fs.SkipDir
59 }
60
61 return nil
62 })
63
64 if err != nil {
65 errs = append(errs, err)
66 }
67
68 return &StringArrayReader{strings: filePaths}, errors.Join(errs...)
69}
70
71// pathDepth returns the depth of a given path by counting its components.
72// It uses filepath.Separator, which ensures correct behavior across all platforms

Callers 3

NewScanFileCmdFunction · 0.92
Test_NewFileDirReaderFunction · 0.85

Calls 1

pathDepthFunction · 0.85

Tested by 2

Test_NewFileDirReaderFunction · 0.68