Repository navigation
Expand file tree
/
Copy pathdirective_scanner.go
More file actions
77 lines (72 loc) · 1.94 KB
/
Copy pathdirective_scanner.go
File metadata and controls
77 lines (72 loc) · 1.94 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package engine
import (
"fmt"
"io/fs"
"os"
"path/filepath"
"regexp"
"strings"
)
// Directive is a parsed reflect: comment from source code.
type Directive struct {
File string
Line int
Command string
Context string
}
var reflectDirectivePattern = regexp.MustCompile(`(?i)(?://|#|--|/\*)\s*reflect:\s*(.+?)(?:\s*\*/)?$`)
// ScanDirectives finds all `// reflect: <command>` comments in source files.
func ScanDirectives(dir string) []Directive {
var directives []Directive
_ = filepath.WalkDir(dir, func(path string, d fs.DirEntry, err error) error {
if err != nil {
return err
}
if d.IsDir() {
name := d.Name()
if name == ".git" || name == "node_modules" || name == "vendor" || name == ".reflect" {
return filepath.SkipDir
}
return nil
}
ext := strings.ToLower(filepath.Ext(path))
switch ext {
case ".go", ".py", ".js", ".ts", ".rs", ".rb", ".java", ".c", ".cpp", ".h", ".jsx", ".tsx":
default:
return nil
}
data, err := os.ReadFile(path) // #nosec G304,G122 -- read-only directive scan
if err != nil {
return nil
}
lines := strings.Split(string(data), "\n")
for i, line := range lines {
matches := reflectDirectivePattern.FindStringSubmatch(line)
if len(matches) > 1 {
start := i - 3
if start < 0 {
start = 0
}
end := i + 4
if end > len(lines) {
end = len(lines)
}
directives = append(directives, Directive{
File: path,
Line: i + 1,
Command: strings.TrimSpace(matches[1]),
Context: strings.Join(lines[start:end], "\n"),
})
}
}
return nil
})
return directives
}
// DirectivePrompt formats a directive as a prompt for the LLM.
func DirectivePrompt(d Directive) string {
return "File: " + d.File + " (line " + fmt.Sprintf("%d", d.Line) + ")\n" +
"Directive: " + d.Command + "\n" +
"Context:\n```\n" + d.Context + "\n```\n\n" +
"Implement what the reflect: comment asks for. Remove the reflect: comment after implementing."
}