-
Notifications
You must be signed in to change notification settings - Fork 0
/
reader.go
286 lines (244 loc) · 6.05 KB
/
reader.go
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
package readgo
import (
"bytes"
"context"
"fmt"
"go/ast"
"go/parser"
"go/token"
"os"
"path/filepath"
"sort"
"strings"
)
// DefaultReader implements SourceReader
type DefaultReader struct {
workDir string
}
// NewSourceReader creates a new DefaultReader instance
func NewSourceReader(workDir string) SourceReader {
return &DefaultReader{
workDir: workDir,
}
}
// ReadSourceFile reads a source file with the given options
func (r *DefaultReader) ReadSourceFile(ctx context.Context, path string, opts ReadOptions) ([]byte, error) {
if path == "" {
return nil, fmt.Errorf("empty path")
}
// Convert to absolute path if needed
absPath := path
if !filepath.IsAbs(path) {
absPath = filepath.Join(r.workDir, path)
}
// Clean the path
absPath = filepath.Clean(absPath)
// Verify file exists and get info
info, err := os.Stat(absPath)
if err != nil {
return nil, err
}
// Check if it's a regular file
if !info.Mode().IsRegular() {
return nil, fmt.Errorf("not a regular file: %s", path)
}
// Read file
content, err := os.ReadFile(absPath)
if err != nil {
return nil, err
}
// Apply options
if opts.StripSpaces {
content = bytes.TrimSpace(content)
}
return content, nil
}
// NewDefaultReader creates a new DefaultReader instance
func NewDefaultReader() *DefaultReader {
return &DefaultReader{}
}
// WithWorkDir sets the working directory for the reader
func (r *DefaultReader) WithWorkDir(dir string) *DefaultReader {
r.workDir = dir
return r
}
// ReadFileWithFunctions reads a source file and returns its content along with function positions
func (r *DefaultReader) ReadFileWithFunctions(ctx context.Context, path string) (*FileContent, error) {
content, err := r.ReadSourceFile(ctx, path, ReadOptions{})
if err != nil {
return nil, err
}
// Parse the file
fset := token.NewFileSet()
file, err := parser.ParseFile(fset, path, content, parser.ParseComments)
if err != nil {
return nil, err
}
// Extract function positions
var functions []FunctionPosition
for _, decl := range file.Decls {
if fn, ok := decl.(*ast.FuncDecl); ok {
pos := fset.Position(fn.Pos())
end := fset.Position(fn.End())
functions = append(functions, FunctionPosition{
Name: fn.Name.Name,
StartLine: pos.Line,
EndLine: end.Line,
})
}
}
return &FileContent{
Content: content,
Functions: functions,
}, nil
}
// isGeneratedFile checks if a file is generated based on its content
func isGeneratedFile(content []byte) bool {
contentStr := string(content)
markers := []string{
"Code generated", "DO NOT EDIT",
"@generated",
"// Generated by",
"/* Generated by",
}
for _, marker := range markers {
if strings.Contains(contentStr, marker) {
return true
}
}
return false
}
// findNode finds a node in the tree by its path
func findNode(root *FileTreeNode, path string) *FileTreeNode {
if root.Path == path {
return root
}
for _, child := range root.Children {
if child.Type == "directory" {
if node := findNode(child, path); node != nil {
return node
}
}
}
return nil
}
// SearchFiles searches for files matching the given pattern
func (r *DefaultReader) SearchFiles(ctx context.Context, pattern string, opts TreeOptions) ([]*FileTreeNode, error) {
if pattern == "" {
return nil, ErrInvalidInput
}
tree, err := r.GetFileTree(ctx, ".", opts)
if err != nil {
return nil, err
}
var matches []*FileTreeNode
var search func(*FileTreeNode)
search = func(node *FileTreeNode) {
if node.Type == "file" && strings.Contains(node.Name, pattern) {
matches = append(matches, node)
}
for _, child := range node.Children {
search(child)
}
}
search(tree)
return matches, nil
}
// GetPackageFiles returns all files in a package
func (r *DefaultReader) GetPackageFiles(ctx context.Context, pkgPath string, opts TreeOptions) ([]*FileTreeNode, error) {
tree, err := r.GetFileTree(ctx, pkgPath, opts)
if err != nil {
return nil, err
}
var files []*FileTreeNode
var collect func(*FileTreeNode)
collect = func(node *FileTreeNode) {
if node.Type == "file" {
files = append(files, node)
}
for _, child := range node.Children {
collect(child)
}
}
collect(tree)
return files, nil
}
// GetFileTree returns the file tree starting from the given root
func (r *DefaultReader) GetFileTree(ctx context.Context, root string, opts TreeOptions) (*FileTreeNode, error) {
if root == "" {
root = "."
}
absRoot := filepath.Join(r.workDir, root)
absRoot, err := filepath.Abs(absRoot)
if err != nil {
return nil, err
}
tree := &FileTreeNode{
Name: filepath.Base(absRoot),
Path: root,
Type: "directory",
}
err = filepath.Walk(absRoot, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
// Skip if path matches exclude patterns
for _, pattern := range opts.ExcludePatterns {
if matched, _ := filepath.Match(pattern, info.Name()); matched {
if info.IsDir() {
return filepath.SkipDir
}
return nil
}
}
// Skip if path doesn't match include patterns
if len(opts.IncludePatterns) > 0 {
matched := false
for _, pattern := range opts.IncludePatterns {
if m, _ := filepath.Match(pattern, info.Name()); m {
matched = true
break
}
}
if !matched {
if info.IsDir() {
return filepath.SkipDir
}
return nil
}
}
// Convert absolute path to relative path
relPath, err := filepath.Rel(r.workDir, path)
if err != nil {
return err
}
node := &FileTreeNode{
Name: info.Name(),
Path: relPath,
Size: info.Size(),
ModTime: info.ModTime(),
}
if info.IsDir() {
node.Type = "directory"
} else {
node.Type = "file"
}
// Find parent node
if path != absRoot {
parentPath := filepath.Dir(relPath)
parentNode := findNode(tree, parentPath)
if parentNode != nil {
parentNode.Children = append(parentNode.Children, node)
// Sort children by name
sort.Slice(parentNode.Children, func(i, j int) bool {
return parentNode.Children[i].Name < parentNode.Children[j].Name
})
}
}
return nil
})
if err != nil {
return nil, err
}
return tree, nil
}