-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathparse.go
219 lines (190 loc) · 5.8 KB
/
parse.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
package main
import (
"fmt"
"go/ast"
"go/parser"
"go/token"
"io"
"log"
"os"
"strings"
)
type Func struct {
FullDescriptions []string
FunctionDescriptions []FunctionDescription
TestFunctionDescriptions []FunctionDescription
}
type FunctionDescription struct {
Name string `json:"name"`
Doc string `json:"doc"`
Package string `json:"package"`
IsTestFunction bool `json:"is_test_function"`
}
type Param struct {
FilePath string
FileName string
IncludeBody bool
}
func (f *Func) ParseFunctions(p Param) {
code, err := readFile(p.FilePath)
if err != nil {
log.Printf("Error reading file %s: %v", p.FilePath, err)
return
}
file, err := parseCode(p.FileName, code)
if err != nil {
log.Printf("Error parsing file %s: %v", p.FileName, err)
return
}
description, funcDescriptions, testFuncDescriptions := buildFileDescription(p, file, code)
f.FullDescriptions = append(f.FullDescriptions, description)
f.FunctionDescriptions = append(f.FunctionDescriptions, funcDescriptions...)
f.TestFunctionDescriptions = append(f.TestFunctionDescriptions, testFuncDescriptions...)
}
func (f *Func) Print() {
for _, desc := range f.FullDescriptions {
fmt.Println(desc)
}
}
func readFile(filePath string) (string, error) {
codeFile, err := os.Open(filePath)
if err != nil {
return "", fmt.Errorf("failed to open file: %w", err)
}
defer codeFile.Close()
srcbuf, err := io.ReadAll(codeFile)
if err != nil {
return "", fmt.Errorf("failed to read file: %w", err)
}
return string(srcbuf), nil
}
func parseCode(fileName, code string) (*ast.File, error) {
fset := token.NewFileSet()
return parser.ParseFile(fset, fileName, code, parser.ParseComments)
}
func buildFileDescription(p Param, file *ast.File, code string) (string, []FunctionDescription, []FunctionDescription) {
var sb strings.Builder
var funcDescriptions, testFuncDescriptions []FunctionDescription
isTestFile := strings.Contains(p.FileName, "_test")
writeFileHeader(&sb, p, file, isTestFile)
ast.Inspect(file, func(n ast.Node) bool {
if fn, ok := n.(*ast.FuncDecl); ok {
funcStr := describeFunctionDeclaration(&sb, fn, code, p.IncludeBody)
funcDesc := FunctionDescription{
Name: fn.Name.Name,
Doc: funcStr,
Package: file.Name.Name,
IsTestFunction: isTestFile,
}
if isTestFile {
testFuncDescriptions = append(testFuncDescriptions, funcDesc)
} else {
funcDescriptions = append(funcDescriptions, funcDesc)
}
}
return true
})
writeFileFooter(&sb, p, isTestFile)
return sb.String(), funcDescriptions, testFuncDescriptions
}
func writeFileHeader(sb *strings.Builder, p Param, file *ast.File, isTestFile bool) {
fileType := "go"
if isTestFile {
fileType += " test"
}
sb.WriteString(fmt.Sprintf("##Start of %s file %s\n", fileType, p.FilePath))
sb.WriteString(fmt.Sprintf("###File path: %s\n", p.FilePath))
sb.WriteString(fmt.Sprintf("###File name: %s\n", p.FileName))
sb.WriteString(fmt.Sprintf("##Package name: %s\n", file.Name.Name))
sb.WriteString(fmt.Sprintf("##%s\n", strings.Title(fileType)+" Functions"))
}
func writeFileFooter(sb *strings.Builder, p Param, isTestFile bool) {
fileType := "go"
if isTestFile {
fileType += " test"
}
sb.WriteString(fmt.Sprintf("----- End of %s file %s -------\n", fileType, p.FilePath))
}
func describeFunctionDeclaration(funcSb *strings.Builder, fn *ast.FuncDecl, code string, includeBody bool) string {
var sb strings.Builder
writeComments(&sb, fn.Doc)
sb.WriteString(fmt.Sprintf("##Function name: %s\n", fn.Name.Name))
if fn.Recv != nil {
sb.WriteString(fmt.Sprintf("##Receiver: \n%s\n", fields(*fn.Recv)))
}
writeParameters(&sb, fn.Type.Params)
writeResults(&sb, fn.Type.Results)
writeFunctionCalls(&sb, fn, code)
if includeBody {
writeFunctionBody(&sb, fn, code)
}
sb.WriteString(fmt.Sprintf("`###End of function with name %s ###`\n", fn.Name.Name))
funcSb.WriteString(sb.String())
return sb.String()
}
func writeComments(sb *strings.Builder, doc *ast.CommentGroup) {
if doc != nil {
for _, c := range doc.List {
sb.WriteString(c.Text + "\n")
}
}
}
func writeParameters(sb *strings.Builder, params *ast.FieldList) {
if params != nil {
sb.WriteString("##Parameters: " + fields(*params) + "\n")
}
}
func writeResults(sb *strings.Builder, results *ast.FieldList) {
if results != nil {
sb.WriteString("##Return: " + fields(*results) + "\n")
}
}
func writeFunctionCalls(sb *strings.Builder, fn *ast.FuncDecl, code string) {
sb.WriteString("## Function calls from other packages\n")
sb.WriteString("```go\n")
ast.Inspect(fn, func(n ast.Node) bool {
if call, ok := n.(*ast.CallExpr); ok {
sb.WriteString(" " + code[call.Pos()-1:call.End()-1] + "\n")
}
return true
})
sb.WriteString("```\n")
}
func writeFunctionBody(sb *strings.Builder, fn *ast.FuncDecl, code string) {
sb.WriteString(fmt.Sprintf("####Function Body of function %s\n", fn.Name.Name))
sb.WriteString("```go\n")
sb.WriteString(code[fn.Pos()-1 : fn.End()-1])
sb.WriteString("```\n")
}
func expr(e ast.Expr) string {
switch x := e.(type) {
case *ast.StarExpr:
return fmt.Sprintf("*%v", expr(x.X))
case *ast.Ident:
return x.Name
case *ast.ArrayType:
if x.Len != nil {
return fmt.Sprintf("[%s]%s", expr(x.Len), expr(x.Elt))
}
return fmt.Sprintf("[]%s", expr(x.Elt))
case *ast.MapType:
return fmt.Sprintf("map[%s]%s", expr(x.Key), expr(x.Value))
case *ast.SelectorExpr:
return fmt.Sprintf("%s.%s", expr(x.X), expr(x.Sel))
default:
log.Printf("Unknown type: %T\n", x)
return ""
}
}
func fields(fl ast.FieldList) string {
var parts []string
for _, f := range fl.List {
names := make([]string, len(f.Names))
for i, n := range f.Names {
names[i] = n.Name
}
part := fmt.Sprintf("%s %s", strings.Join(names, ", "), expr(f.Type))
parts = append(parts, part)
}
return strings.Join(parts, ", ")
}