-
Notifications
You must be signed in to change notification settings - Fork 0
/
parse.go
242 lines (203 loc) · 9.3 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
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
package ddlctlgo
import (
"context"
"errors"
"fmt"
"go/ast"
"go/parser"
"go/token"
"os"
"path/filepath"
"reflect"
"sort"
"strings"
"unicode"
filepathz "github.com/kunitsucom/util.go/path/filepath"
slicez "github.com/kunitsucom/util.go/slices"
apperr "github.com/kunitsucom/ddlctl/pkg/apperr"
"github.com/kunitsucom/ddlctl/pkg/internal/config"
ddlast "github.com/kunitsucom/ddlctl/pkg/internal/generator"
langutil "github.com/kunitsucom/ddlctl/pkg/internal/lang/util"
"github.com/kunitsucom/ddlctl/pkg/internal/util"
"github.com/kunitsucom/ddlctl/pkg/logs"
)
const (
Language = "go"
DDLCTL_ERROR_STRUCT_FIELD_TAG_NOT_FOUND = "DDLCTL_ERROR_STRUCT_FIELD_TAG_NOT_FOUND" //nolint:revive,stylecheck
)
//nolint:cyclop
func Parse(ctx context.Context, src string) (*ddlast.DDL, error) {
// MEMO: get absolute path for parser.ParseFile()
sourceAbs := util.Abs(src)
info, err := os.Stat(sourceAbs)
if err != nil {
return nil, apperr.Errorf("os.Stat: %w", err)
}
ddl := ddlast.NewDDL(ctx)
if info.IsDir() {
if err := filepath.WalkDir(sourceAbs, walkDirFn(ctx, ddl)); err != nil {
return nil, apperr.Errorf("filepath.WalkDir: %w", err)
}
return ddl, nil
}
stmts, err := parseFile(ctx, sourceAbs)
if err != nil {
return nil, apperr.Errorf("Parse: %w", err)
}
ddl.Stmts = append(ddl.Stmts, stmts...)
return ddl, nil
}
//nolint:gochecknoglobals
var fileSuffix = ".go"
func walkDirFn(ctx context.Context, ddl *ddlast.DDL) func(path string, d os.DirEntry, err error) error {
return func(path string, d os.DirEntry, err error) error {
if err != nil {
return err //nolint:wrapcheck
}
if d.IsDir() || !strings.HasSuffix(path, fileSuffix) || strings.HasSuffix(path, "_test.go") {
return nil
}
stmts, err := parseFile(ctx, path)
if err != nil {
if errors.Is(err, apperr.ErrDDLTagGoAnnotationNotFoundInSource) {
logs.Debug.Printf("parseFile: %s: %v", path, err)
return nil
}
return apperr.Errorf("parseFile: %w", err)
}
ddl.Stmts = append(ddl.Stmts, stmts...)
return nil
}
}
//nolint:cyclop,funlen,gocognit
func parseFile(ctx context.Context, filename string) ([]ddlast.Stmt, error) {
fset := token.NewFileSet()
f, err := parser.ParseFile(fset, filename, nil, parser.ParseComments)
if err != nil {
return nil, apperr.Errorf("parser.ParseFile: %w", err)
}
ddlSrc, err := extractDDLSourceFromDDLTagGo(ctx, fset, f)
if err != nil {
return nil, apperr.Errorf("extractDDLSourceFromDDLTagGo: %w", err)
}
dumpDDLSource(fset, ddlSrc)
stmts := make([]ddlast.Stmt, 0)
for _, r := range ddlSrc {
createTableStmt := &ddlast.CreateTableStmt{}
// source
createTableStmt.SourceFile = r.Position.Filename
createTableStmt.SourceLine = r.Position.Line
// CREATE TABLE (or INDEX) / CONSTRAINT / OPTIONS (from comments)
comments := slicez.Select(r.CommentGroup.List, func(_ int, comment *ast.Comment) string {
return strings.TrimLeftFunc(strings.TrimPrefix(strings.TrimPrefix(strings.TrimPrefix(comment.Text, "//"), "/*"), "*/"), unicode.IsSpace)
})
for _, comment := range comments {
logs.Debug.Printf("[COMMENT DETECTED]: %s:%d: %s", createTableStmt.SourceFile, createTableStmt.SourceLine, comment)
// NOTE: CREATE INDEX may be written in CREATE TABLE annotation, so process it here
if /* CREATE INDEX */ matches := langutil.StmtRegexCreateIndex.Regex.FindStringSubmatch(comment); len(matches) > langutil.StmtRegexCreateIndex.Index {
commentMatchedCreateIndex := comment
source := fset.Position(extractContainingCommentFromCommentGroup(r.CommentGroup, commentMatchedCreateIndex).Pos())
createIndexStmt := &ddlast.CreateIndexStmt{
Comments: []string{commentMatchedCreateIndex},
SourceFile: source.Filename,
SourceLine: source.Line,
}
createIndexStmt.SetCreateIndex(matches[langutil.StmtRegexCreateIndex.Index])
stmts = append(stmts, createIndexStmt)
continue
}
if /* CREATE TABLE */ matches := langutil.StmtRegexCreateTable.Regex.FindStringSubmatch(comment); len(matches) > langutil.StmtRegexCreateTable.Index {
createTableStmt.SetCreateTable(matches[langutil.StmtRegexCreateTable.Index])
} else if /* CONSTRAINT */ matches := langutil.StmtRegexCreateTableConstraint.Regex.FindStringSubmatch(comment); len(matches) > langutil.StmtRegexCreateTableConstraint.Index {
createTableStmt.Constraints = append(createTableStmt.Constraints, &ddlast.CreateTableConstraint{
Constraint: matches[langutil.StmtRegexCreateTableConstraint.Index],
})
} else if /* OPTIONS */ matches := langutil.StmtRegexCreateTableOptions.Regex.FindStringSubmatch(comment); len(matches) > langutil.StmtRegexCreateTableOptions.Index {
createTableStmt.Options = append(createTableStmt.Options, &ddlast.CreateTableOption{
Option: matches[langutil.StmtRegexCreateTableOptions.Index],
})
}
// comment
createTableStmt.Comments = append(createTableStmt.Comments, comment)
}
// CREATE TABLE (default: struct name)
if r.TypeSpec != nil && createTableStmt.CreateTable == "" {
name := r.TypeSpec.Name.String()
source := fset.Position(r.CommentGroup.Pos())
createTableStmt.Comments = append(createTableStmt.Comments, fmt.Sprintf("WARN: the comment (%s:%d) does not have a key for table (%s: table: CREATE TABLE <table>), so the struct name \"%s\" is used as the table name.", filepathz.Short(source.Filename), source.Line, config.DDLTagGo(), name))
createTableStmt.SetCreateTable(name)
}
// columns
if r.StructType != nil {
for _, field := range r.StructType.Fields.List {
column := &ddlast.CreateTableColumn{}
tag := reflect.StructTag(strings.Trim(field.Tag.Value, "`"))
// column name
switch columnName := tag.Get(config.ColumnTagGo()); columnName {
case "-":
createTableStmt.Comments = append(createTableStmt.Comments, fmt.Sprintf("NOTE: the \"%s\" struct's \"%s\" field has a tag for column name (`%s:\"-\"`), so the field is ignored.", r.TypeSpec.Name, field.Names[0], config.ColumnTagGo()))
continue
case "":
name := field.Names[0].Name
column.Comments = append(column.Comments, fmt.Sprintf("WARN: the \"%s\" struct's \"%s\" field does not have a tag for column name (`%s:\"<ColumnName>\"`), so the field name \"%s\" is used as the column name.", r.TypeSpec.Name, field.Names[0], config.ColumnTagGo(), name))
column.ColumnName = name
default:
column.ColumnName = columnName
}
// column type and constraint
switch columnTypeConstraint := tag.Get(config.DDLTagGo()); columnTypeConstraint {
case "", "-":
// NOTE: ignore no-annotation fields
// column.Comments = append(column.Comments, fmt.Sprintf("ERROR: the \"%s\" struct's \"%s\" field does not have a tag for column type and constraint (`%s:\"<TYPE> [CONSTRAINT]\"`)", r.TypeSpec.Name, field.Names[0], config.DDLTagGo()))
// column.TypeConstraint = DDLCTL_ERROR_STRUCT_FIELD_TAG_NOT_FOUND
continue
default:
column.TypeConstraint = columnTypeConstraint
}
// primary key
switch primaryKey := tag.Get(config.PKTagGo()); primaryKey {
case "true", "1":
createTableStmt.PrimaryKey = append(createTableStmt.PrimaryKey, column.ColumnName)
case "", "-":
// do nothing
default:
column.Comments = append(column.Comments, fmt.Sprintf("WARN: the field \"%s\" does not have valid primary key tag (`%s:\"true\"`), so the column is not used as primary key.", field.Names[0], config.PKTagGo()))
}
// comments
comments := strings.Split(strings.Trim(field.Doc.Text(), "\n"), "\n")
column.Comments = append(column.Comments, langutil.TrimCommentElementTailEmpty(langutil.TrimCommentElementHasPrefix(comments, config.DDLTagGo()))...)
createTableStmt.Columns = append(createTableStmt.Columns, column)
}
}
if createTableStmt.CreateTable == "" {
// CREATE TABLE (ERROR)
source := fset.Position(r.CommentGroup.Pos())
createTableStmt.Comments = append(createTableStmt.Comments, fmt.Sprintf("WARN: the comment (%s:%d) does not have a key for table (%s: table: CREATE TABLE <table>), or the comment is not associated with struct.", filepathz.Short(source.Filename), source.Line, config.DDLTagGo()))
} else if len(createTableStmt.Columns) == 0 {
// columns (ERROR)
source := fset.Position(r.CommentGroup.Pos())
createTableStmt.Comments = append(createTableStmt.Comments, fmt.Sprintf("ERROR: the comment (%s:%d) does not have struct fields for column type and constraint (`%s:\"<TYPE> [CONSTRAINT]\"`), or the comment is not associated with struct.", filepathz.Short(source.Filename), source.Line, config.DDLTagGo()))
}
if len(createTableStmt.Columns) > 0 {
// NOTE: append only if there are columns
stmts = append(stmts, createTableStmt)
} else {
logs.Warn.Printf("parseFile: %s:%d: %s", createTableStmt.SourceFile, createTableStmt.SourceLine, "no columns")
}
}
sort.Slice(stmts, func(i, j int) bool {
return fmt.Sprintf("%s:%09d", stmts[i].GetSourceFile(), stmts[i].GetSourceLine()) < fmt.Sprintf("%s:%09d", stmts[j].GetSourceFile(), stmts[j].GetSourceLine())
})
for i := range stmts {
logs.Trace.Print(fmt.Sprintf("%s:%09d", stmts[i].GetSourceFile(), stmts[i].GetSourceLine()))
}
return stmts, nil
}
func extractContainingCommentFromCommentGroup(commentGroup *ast.CommentGroup, sub string) *ast.Comment {
for _, commentLine := range commentGroup.List {
if strings.Contains(commentLine.Text, sub) {
return commentLine
}
}
return nil
}