MCPcopy Create free account
hub / github.com/danielmiessler/Fabric / ScanDirectory

Function ScanDirectory

cmd/code2context/code.go:35–125  ·  view source on GitHub ↗

ScanDirectory scans a directory and returns a JSON representation of its structure

(rootDir string, maxDepth int, instructions string, ignoreList []string)

Source from the content-addressed store, hash-verified

33
34// ScanDirectory scans a directory and returns a JSON representation of its structure
35func ScanDirectory(rootDir string, maxDepth int, instructions string, ignoreList []string) ([]byte, error) {
36 // dirCount starts at 1 to include rootDir.
37 dirCount := 1
38 fileCount := 0
39
40 rootItem := FileItem{
41 Type: "directory",
42 Name: rootDir,
43 Contents: []FileItem{},
44 }
45
46 err := filepath.Walk(rootDir, func(path string, info os.FileInfo, err error) error {
47 if err != nil {
48 return err
49 }
50
51 // Skip every path that contains ".git". This also matches .gitignore and .github.
52 if strings.Contains(path, ".git") {
53 if info.IsDir() {
54 return filepath.SkipDir
55 }
56 return nil
57 }
58
59 relPath, err := filepath.Rel(rootDir, path)
60 if err != nil {
61 return err
62 }
63
64 for _, pattern := range ignoreList {
65 if strings.Contains(relPath, pattern) {
66 if info.IsDir() {
67 return filepath.SkipDir
68 }
69 return nil
70 }
71 }
72
73 if relPath == "." {
74 return nil
75 }
76
77 depth := len(strings.Split(relPath, string(filepath.Separator)))
78 if depth > maxDepth {
79 if info.IsDir() {
80 return filepath.SkipDir
81 }
82 return nil
83 }
84
85 // Read only regular files. Skip symlinks, devices and sockets, so
86 // that a symlink cannot add a file from outside the project.
87 if info.IsDir() {
88 dirCount++
89 } else if info.Mode().IsRegular() {
90 fileCount++
91
92 content, err := os.ReadFile(path)

Callers 3

TestScanDirectoryFunction · 0.85
mainFunction · 0.85

Calls 1

addFileToDirectoryFunction · 0.85

Tested by 2

TestScanDirectoryFunction · 0.68