MCPcopy Create free account
hub / github.com/JordanCoin/codemap / ScanDirectory

Method ScanDirectory

scanner/astgrep.go:211–319  ·  view source on GitHub ↗

ScanDirectory analyzes all files in a directory using sg scan

(root string)

Source from the content-addressed store, hash-verified

209
210// ScanDirectory analyzes all files in a directory using sg scan
211func (s *AstGrepScanner) ScanDirectory(root string) ([]FileAnalysis, error) {
212 if !s.Available() {
213 return nil, nil
214 }
215
216 // Combine all rules into one string with --- separators
217 var rules []string
218 entries, _ := os.ReadDir(s.rulesDir)
219 for _, e := range entries {
220 if strings.HasSuffix(e.Name(), ".yml") && e.Name() != "sgconfig.yml" {
221 content, err := os.ReadFile(filepath.Join(s.rulesDir, e.Name()))
222 if err == nil {
223 rules = append(rules, string(content))
224 }
225 }
226 }
227 inlineRules := strings.Join(rules, "\n---\n")
228
229 // Build command args, excluding nested git repos that ast-grep would
230 // treat as separate repo boundaries (ignoring parent .gitignore)
231 args := []string{"scan", "--inline-rules", inlineRules, "--json"}
232 for _, repo := range findNestedGitRepos(root) {
233 args = append(args, "--globs", "!"+repo+"/**")
234 }
235 args = append(args, root)
236
237 ctx, cancel := context.WithTimeout(context.Background(), astGrepScanTimeout)
238 defer cancel()
239
240 cmd := exec.CommandContext(ctx, s.binary, args...)
241 out, err := cmd.Output()
242 if err != nil {
243 if errors.Is(ctx.Err(), context.DeadlineExceeded) || errors.Is(err, context.DeadlineExceeded) {
244 fmt.Fprintf(os.Stderr, "warning: ast-grep timed out after %s in %s; skipping ast-grep results\n", astGrepScanTimeout, root)
245 return nil, nil
246 }
247
248 var exitErr *exec.ExitError
249 if errors.As(err, &exitErr) {
250 if status, ok := exitErr.Sys().(syscall.WaitStatus); ok && status.Signaled() {
251 fmt.Fprintf(os.Stderr, "warning: ast-grep exited with signal %d in %s; skipping ast-grep results\n", status.Signal(), root)
252 return nil, nil
253 }
254 }
255
256 // sg scan returns non-zero if no matches, check if output contains JSON
257 if len(out) == 0 {
258 return nil, nil
259 }
260 }
261
262 // Extract JSON array from output (handles debug output before JSON, e.g. ast-grep 0.40.2 bug)
263 jsonData := extractJSONArray(out)
264 if jsonData == nil {
265 return nil, nil
266 }
267
268 var matches []ScanMatch

Callers 5

TestBenchmarkAstGrepFunction · 0.95
TestAstGrepScannerFunction · 0.95
ScanForDepsFunction · 0.95
AnalyzeFileMethod · 0.95

Calls 7

AvailableMethod · 0.95
findNestedGitReposFunction · 0.85
extractJSONArrayFunction · 0.85
detectLangFromRuleIDFunction · 0.85
extractImportPathFunction · 0.85
extractFunctionNameFunction · 0.85
dedupeFunction · 0.85

Tested by 3

TestBenchmarkAstGrepFunction · 0.76
TestAstGrepScannerFunction · 0.76