-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparser.go
More file actions
955 lines (805 loc) · 24.7 KB
/
parser.go
File metadata and controls
955 lines (805 loc) · 24.7 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
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
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
package gogo
import (
"bytes"
"fmt"
"go/ast"
"go/format"
"go/parser"
"go/token"
"strings"
)
// parseFieldsString parses a field string like `ID uuid.UUID \`json:"id"\“ into StructField slice
func parseFieldsString(fields string) ([]StructField, error) {
// Simple parser for field strings
// This is a basic implementation - could be enhanced
var result []StructField
lines := strings.Split(fields, "\n")
for _, line := range lines {
line = strings.TrimSpace(line)
if line == "" {
continue
}
// Parse each line: Name Type `annotation`
parts := strings.Fields(line)
if len(parts) < 2 {
continue
}
field := StructField{
Name: parts[0],
Type: parts[1],
}
// Find annotation (everything after backtick)
if idx := strings.Index(line, "`"); idx >= 0 {
field.Annotation = line[idx:]
}
result = append(result, field)
}
return result, nil
}
// createNewFileWithStruct creates a new Go file with the specified struct
func createNewFileWithStruct(s structDef, packageName string) ([]byte, error) {
if packageName == "" {
packageName = "main"
}
var buf bytes.Buffer
// Write package declaration
buf.WriteString(fmt.Sprintf("package %s\n\n", packageName))
// Write struct
buf.WriteString(fmt.Sprintf("type %s struct {\n", s.Name))
for _, field := range s.EnsureFields {
buf.WriteString(fmt.Sprintf("\t%s %s", field.Name, field.Type))
if field.Annotation != "" {
// Ensure the annotation has backticks if not already present
annotation := field.Annotation
if !strings.HasPrefix(annotation, "`") {
annotation = "`" + annotation + "`"
}
buf.WriteString(" " + annotation)
}
buf.WriteString("\n")
}
buf.WriteString("}\n")
// Format the code
formatted, err := format.Source(buf.Bytes())
if err != nil {
return buf.Bytes(), nil // Return unformatted if format fails
}
return formatted, nil
}
// modifyExistingFile modifies an existing Go file to ensure/delete struct fields
func modifyExistingFile(content []byte, s structDef) ([]byte, error) {
fset := token.NewFileSet()
file, err := parser.ParseFile(fset, "", content, parser.ParseComments)
if err != nil {
return nil, fmt.Errorf("failed to parse Go file: %w", err)
}
// Find or create the struct
structType := findOrCreateStruct(file, s.Name)
if structType == nil {
// Add new struct to file
structType = createStructDecl(s)
file.Decls = append(file.Decls, structType)
} else {
// Modify existing struct
modifyStruct(structType, s)
}
// Format and return the modified code
var buf bytes.Buffer
if err := format.Node(&buf, fset, file); err != nil {
return nil, fmt.Errorf("failed to format Go code: %w", err)
}
return buf.Bytes(), nil
}
// findOrCreateStruct finds an existing struct or returns nil if not found
func findOrCreateStruct(file *ast.File, name string) *ast.GenDecl {
for _, decl := range file.Decls {
genDecl, ok := decl.(*ast.GenDecl)
if !ok || genDecl.Tok != token.TYPE {
continue
}
for _, spec := range genDecl.Specs {
typeSpec, ok := spec.(*ast.TypeSpec)
if !ok {
continue
}
if typeSpec.Name.Name == name {
if _, ok := typeSpec.Type.(*ast.StructType); ok {
return genDecl
}
}
}
}
return nil
}
// createStructDecl creates a new struct declaration
func createStructDecl(s structDef) *ast.GenDecl {
fields := &ast.FieldList{
List: make([]*ast.Field, 0, len(s.EnsureFields)),
}
for _, field := range s.EnsureFields {
astField := &ast.Field{
Names: []*ast.Ident{{Name: field.Name}},
Type: parseTypeExpr(field.Type),
}
if field.Annotation != "" {
// Ensure the annotation has backticks
annotation := field.Annotation
if !strings.HasPrefix(annotation, "`") {
annotation = "`" + annotation + "`"
}
astField.Tag = &ast.BasicLit{
Kind: token.STRING,
Value: annotation,
}
}
fields.List = append(fields.List, astField)
}
return &ast.GenDecl{
Tok: token.TYPE,
Specs: []ast.Spec{
&ast.TypeSpec{
Name: &ast.Ident{Name: s.Name},
Type: &ast.StructType{
Fields: fields,
},
},
},
}
}
// modifyStruct modifies an existing struct according to the Struct specification
func modifyStruct(genDecl *ast.GenDecl, s structDef) {
for _, spec := range genDecl.Specs {
typeSpec, ok := spec.(*ast.TypeSpec)
if !ok || typeSpec.Name.Name != s.Name {
continue
}
structType, ok := typeSpec.Type.(*ast.StructType)
if !ok {
continue
}
// Build map of existing fields
existingFields := make(map[string]*ast.Field)
for _, field := range structType.Fields.List {
for _, name := range field.Names {
existingFields[name.Name] = field
}
}
// Remove fields marked for deletion
if len(s.DeleteFields) > 0 {
newFields := make([]*ast.Field, 0)
for _, field := range structType.Fields.List {
shouldDelete := false
// Check if field should be deleted
for _, name := range field.Names {
for _, deleteField := range s.DeleteFields {
if name.Name == deleteField.Name {
shouldDelete = true
break
}
}
if shouldDelete {
break
}
}
if !shouldDelete {
newFields = append(newFields, field)
}
}
structType.Fields.List = newFields
// Rebuild existing fields map after deletion
existingFields = make(map[string]*ast.Field)
for _, field := range structType.Fields.List {
for _, name := range field.Names {
existingFields[name.Name] = field
}
}
} else if !s.PreserveExisting {
// If not preserving existing fields and not deleting specific ones,
// clear all fields
structType.Fields.List = make([]*ast.Field, 0)
existingFields = make(map[string]*ast.Field)
}
// Add or update ensure fields
for _, ensureField := range s.EnsureFields {
if existing, ok := existingFields[ensureField.Name]; ok {
// Update existing field
existing.Type = parseTypeExpr(ensureField.Type)
if ensureField.Annotation != "" {
// Ensure the annotation has backticks
annotation := ensureField.Annotation
if !strings.HasPrefix(annotation, "`") {
annotation = "`" + annotation + "`"
}
existing.Tag = &ast.BasicLit{
Kind: token.STRING,
Value: annotation,
}
}
} else {
// Add new field
newField := &ast.Field{
Names: []*ast.Ident{{Name: ensureField.Name}},
Type: parseTypeExpr(ensureField.Type),
}
if ensureField.Annotation != "" {
// Ensure the annotation has backticks
annotation := ensureField.Annotation
if !strings.HasPrefix(annotation, "`") {
annotation = "`" + annotation + "`"
}
newField.Tag = &ast.BasicLit{
Kind: token.STRING,
Value: annotation,
}
}
structType.Fields.List = append(structType.Fields.List, newField)
}
}
}
}
// parseTypeExpr parses a type string into an AST expression
func parseTypeExpr(typeStr string) ast.Expr {
// Handle basic types
if !strings.Contains(typeStr, ".") && !strings.Contains(typeStr, "[") && !strings.Contains(typeStr, "*") {
return &ast.Ident{Name: typeStr}
}
// Handle pointer types
if strings.HasPrefix(typeStr, "*") {
return &ast.StarExpr{
X: parseTypeExpr(typeStr[1:]),
}
}
// Handle slice types
if strings.HasPrefix(typeStr, "[]") {
return &ast.ArrayType{
Elt: parseTypeExpr(typeStr[2:]),
}
}
// Handle map types
if strings.HasPrefix(typeStr, "map[") {
// Simple map parsing - could be enhanced
closeIdx := strings.Index(typeStr, "]")
if closeIdx > 0 {
keyType := typeStr[4:closeIdx]
valueType := typeStr[closeIdx+1:]
return &ast.MapType{
Key: parseTypeExpr(keyType),
Value: parseTypeExpr(valueType),
}
}
}
// Handle qualified types (package.Type)
if idx := strings.LastIndex(typeStr, "."); idx > 0 {
return &ast.SelectorExpr{
X: &ast.Ident{Name: typeStr[:idx]},
Sel: &ast.Ident{Name: typeStr[idx+1:]},
}
}
// Default to identifier
return &ast.Ident{Name: typeStr}
}
// createNewFileWithMethod creates a new Go file with the specified method
func createNewFileWithMethod(opts MethodOpts, packageName string) ([]byte, error) {
if packageName == "" {
packageName = "main"
}
var buf bytes.Buffer
// Write package declaration
buf.WriteString(fmt.Sprintf("package %s\n\n", packageName))
// If Content is provided, use it directly
if opts.Content != "" {
// Determine receiver name
receiverName := opts.ReceiverName
if receiverName == "" {
// Default receiver name (first letter of type, skipping pointer)
typeWithoutPointer := strings.TrimPrefix(opts.ReceiverType, "*")
if len(typeWithoutPointer) > 0 {
receiverName = strings.ToLower(string(typeWithoutPointer[0]))
} else {
receiverName = "r"
}
}
buf.WriteString(fmt.Sprintf("func (%s %s) %s%s\n", receiverName, opts.ReceiverType, opts.Name, opts.Content))
} else {
// Write method
receiverName := opts.ReceiverName
if receiverName == "" {
// Default receiver name (first letter of type, skipping pointer)
typeWithoutPointer := strings.TrimPrefix(opts.ReceiverType, "*")
if len(typeWithoutPointer) > 0 {
receiverName = strings.ToLower(string(typeWithoutPointer[0]))
} else {
receiverName = "r"
}
}
buf.WriteString(fmt.Sprintf("func (%s %s) %s(", receiverName, opts.ReceiverType, opts.Name))
// Add parameters
for i, param := range opts.Parameters {
if i > 0 {
buf.WriteString(", ")
}
buf.WriteString(fmt.Sprintf("%s %s", param.Name, param.Type))
}
buf.WriteString(")")
// Add return type
if opts.ReturnType != "" {
buf.WriteString(" " + opts.ReturnType)
}
buf.WriteString(" {\n")
// Add body
if opts.Body != "" {
// Split body into lines and indent
lines := strings.Split(opts.Body, "\n")
for _, line := range lines {
if strings.TrimSpace(line) != "" {
buf.WriteString("\t" + line + "\n")
} else {
buf.WriteString("\n")
}
}
}
buf.WriteString("}\n")
}
// Format the code
formatted, err := format.Source(buf.Bytes())
if err != nil {
return buf.Bytes(), nil // Return unformatted if format fails
}
return formatted, nil
}
// createNewFileWithFunction creates a new Go file with the specified function
func createNewFileWithFunction(opts FunctionOpts, packageName string) ([]byte, error) {
if packageName == "" {
packageName = "main"
}
var buf bytes.Buffer
// Write package declaration
buf.WriteString(fmt.Sprintf("package %s\n\n", packageName))
// If Content is provided, use it directly
if opts.Content != "" {
buf.WriteString(fmt.Sprintf("func %s%s\n", opts.Name, opts.Content))
} else {
// Write function
buf.WriteString(fmt.Sprintf("func %s(", opts.Name))
// Add parameters
for i, param := range opts.Parameters {
if i > 0 {
buf.WriteString(", ")
}
buf.WriteString(fmt.Sprintf("%s %s", param.Name, param.Type))
}
buf.WriteString(")")
// Add return type
if opts.ReturnType != "" {
buf.WriteString(" " + opts.ReturnType)
}
buf.WriteString(" {\n")
// Add body
if opts.Body != "" {
// Split body into lines and indent
lines := strings.Split(opts.Body, "\n")
for _, line := range lines {
if strings.TrimSpace(line) != "" {
buf.WriteString("\t" + line + "\n")
} else {
buf.WriteString("\n")
}
}
}
buf.WriteString("}\n")
}
// Format the code
formatted, err := format.Source(buf.Bytes())
if err != nil {
return buf.Bytes(), nil // Return unformatted if format fails
}
return formatted, nil
}
// createNewFileWithVariable creates a new Go file with the specified variables
func createNewFileWithVariable(opts VariableOpts, packageName string) ([]byte, error) {
if packageName == "" {
packageName = "main"
}
var buf bytes.Buffer
// Write package declaration
buf.WriteString(fmt.Sprintf("package %s\n\n", packageName))
// If Content is provided, use it directly
if opts.Content != "" {
buf.WriteString(opts.Content)
} else {
// Write variables
for _, variable := range opts.Variables {
buf.WriteString("var ")
buf.WriteString(variable.Name)
if variable.Type != "" {
buf.WriteString(" " + variable.Type)
}
if variable.Value != "" {
buf.WriteString(" = " + variable.Value)
}
buf.WriteString("\n")
}
}
// Format the code
formatted, err := format.Source(buf.Bytes())
if err != nil {
return buf.Bytes(), nil // Return unformatted if format fails
}
return formatted, nil
}
// createNewFileWithConstant creates a new Go file with the specified constants
func createNewFileWithConstant(opts ConstantOpts, packageName string) ([]byte, error) {
if packageName == "" {
packageName = "main"
}
var buf bytes.Buffer
// Write package declaration
buf.WriteString(fmt.Sprintf("package %s\n\n", packageName))
// If Content is provided, use it directly
if opts.Content != "" {
buf.WriteString(opts.Content)
} else {
// Write constants
for _, constant := range opts.Constants {
buf.WriteString("const ")
buf.WriteString(constant.Name)
if constant.Type != "" {
buf.WriteString(" " + constant.Type)
}
if constant.Value != "" {
buf.WriteString(" = " + constant.Value)
}
buf.WriteString("\n")
}
}
// Format the code
formatted, err := format.Source(buf.Bytes())
if err != nil {
return buf.Bytes(), nil // Return unformatted if format fails
}
return formatted, nil
}
// createNewFileWithType creates a new Go file with the specified type definitions
func createNewFileWithType(opts TypeOpts, packageName string) ([]byte, error) {
if packageName == "" {
packageName = "main"
}
var buf bytes.Buffer
// Write package declaration
buf.WriteString(fmt.Sprintf("package %s\n\n", packageName))
// If Content is provided, use it directly
if opts.Content != "" {
buf.WriteString(opts.Content)
} else {
// Write types
for _, typeDef := range opts.Types {
buf.WriteString("type ")
buf.WriteString(typeDef.Name)
buf.WriteString(" ")
buf.WriteString(typeDef.Definition)
buf.WriteString("\n")
}
}
// Format the code
formatted, err := format.Source(buf.Bytes())
if err != nil {
return buf.Bytes(), nil // Return unformatted if format fails
}
return formatted, nil
}
// modifyExistingFileForMethod modifies an existing Go file to ensure/modify methods
func modifyExistingFileForMethod(content []byte, opts MethodOpts) ([]byte, error) {
fset := token.NewFileSet()
file, err := parser.ParseFile(fset, "", content, parser.ParseComments)
if err != nil {
return nil, fmt.Errorf("failed to parse Go file: %w", err)
}
var methodCode []byte
if opts.Content != "" {
// Use Content directly with receiver and method name
receiverName := opts.ReceiverName
if receiverName == "" {
// Default receiver name (first letter of type, skipping pointer)
typeWithoutPointer := strings.TrimPrefix(opts.ReceiverType, "*")
if len(typeWithoutPointer) > 0 {
receiverName = strings.ToLower(string(typeWithoutPointer[0]))
} else {
receiverName = "r"
}
}
methodCode = []byte(fmt.Sprintf("package tmp\n\nfunc (%s %s) %s%s", receiverName, opts.ReceiverType, opts.Name, opts.Content))
} else {
// For now, just append the method - this is a basic implementation
// A full implementation would parse existing methods and merge/replace them
var err error
methodCode, err = createMethodDeclaration(opts)
if err != nil {
return nil, fmt.Errorf("failed to create method: %w", err)
}
}
// Parse the method code and add to the file
methodFile, err := parser.ParseFile(fset, "", methodCode, parser.ParseComments)
if err != nil {
return nil, fmt.Errorf("failed to parse method code: %w", err)
}
// Append the method declaration to the file
for _, decl := range methodFile.Decls {
if funcDecl, ok := decl.(*ast.FuncDecl); ok {
file.Decls = append(file.Decls, funcDecl)
}
}
// Format and return the modified code
var buf bytes.Buffer
if err := format.Node(&buf, fset, file); err != nil {
return nil, fmt.Errorf("failed to format Go code: %w", err)
}
return buf.Bytes(), nil
}
// modifyExistingFileForFunction modifies an existing Go file to ensure/modify functions
func modifyExistingFileForFunction(content []byte, opts FunctionOpts) ([]byte, error) {
fset := token.NewFileSet()
file, err := parser.ParseFile(fset, "", content, parser.ParseComments)
if err != nil {
return nil, fmt.Errorf("failed to parse Go file: %w", err)
}
var functionCode []byte
if opts.Content != "" {
// Use Content directly with function name
functionCode = []byte(fmt.Sprintf("package tmp\n\nfunc %s%s", opts.Name, opts.Content))
} else {
// For now, just append the function - this is a basic implementation
var err error
functionCode, err = createFunctionDeclaration(opts)
if err != nil {
return nil, fmt.Errorf("failed to create function: %w", err)
}
}
// Parse the function code and add to the file
functionFile, err := parser.ParseFile(fset, "", functionCode, parser.ParseComments)
if err != nil {
return nil, fmt.Errorf("failed to parse function code: %w", err)
}
// Append the function declaration to the file
for _, decl := range functionFile.Decls {
if funcDecl, ok := decl.(*ast.FuncDecl); ok {
file.Decls = append(file.Decls, funcDecl)
}
}
// Format and return the modified code
var buf bytes.Buffer
if err := format.Node(&buf, fset, file); err != nil {
return nil, fmt.Errorf("failed to format Go code: %w", err)
}
return buf.Bytes(), nil
}
// modifyExistingFileForVariable modifies an existing Go file to ensure/modify variables
func modifyExistingFileForVariable(content []byte, opts VariableOpts) ([]byte, error) {
fset := token.NewFileSet()
file, err := parser.ParseFile(fset, "", content, parser.ParseComments)
if err != nil {
return nil, fmt.Errorf("failed to parse Go file: %w", err)
}
// If Content is provided, parse and append it
if opts.Content != "" {
// Parse the content as Go code
contentWithPackage := fmt.Sprintf("package tmp\n\n%s", opts.Content)
contentFile, err := parser.ParseFile(fset, "", contentWithPackage, parser.ParseComments)
if err != nil {
return nil, fmt.Errorf("failed to parse content: %w", err)
}
// Add the declarations from content
for _, decl := range contentFile.Decls {
if genDecl, ok := decl.(*ast.GenDecl); ok && genDecl.Tok == token.VAR {
file.Decls = append(file.Decls, genDecl)
}
}
} else {
// For now, just append variables - this is a basic implementation
for _, variable := range opts.Variables {
varDecl := createVariableDeclaration(variable)
file.Decls = append(file.Decls, varDecl)
}
}
// Format and return the modified code
var buf bytes.Buffer
if err := format.Node(&buf, fset, file); err != nil {
return nil, fmt.Errorf("failed to format Go code: %w", err)
}
return buf.Bytes(), nil
}
// modifyExistingFileForConstant modifies an existing Go file to ensure/modify constants
func modifyExistingFileForConstant(content []byte, opts ConstantOpts) ([]byte, error) {
fset := token.NewFileSet()
file, err := parser.ParseFile(fset, "", content, parser.ParseComments)
if err != nil {
return nil, fmt.Errorf("failed to parse Go file: %w", err)
}
// If Content is provided, parse and append it
if opts.Content != "" {
// Parse the content as Go code
contentWithPackage := fmt.Sprintf("package tmp\n\n%s", opts.Content)
contentFile, err := parser.ParseFile(fset, "", contentWithPackage, parser.ParseComments)
if err != nil {
return nil, fmt.Errorf("failed to parse content: %w", err)
}
// Add the declarations from content
for _, decl := range contentFile.Decls {
if genDecl, ok := decl.(*ast.GenDecl); ok && genDecl.Tok == token.CONST {
file.Decls = append(file.Decls, genDecl)
}
}
} else {
// For now, just append constants - this is a basic implementation
for _, constant := range opts.Constants {
constDecl := createConstantDeclaration(constant)
file.Decls = append(file.Decls, constDecl)
}
}
// Format and return the modified code
var buf bytes.Buffer
if err := format.Node(&buf, fset, file); err != nil {
return nil, fmt.Errorf("failed to format Go code: %w", err)
}
return buf.Bytes(), nil
}
// modifyExistingFileForType modifies an existing Go file to ensure/modify type definitions
func modifyExistingFileForType(content []byte, opts TypeOpts) ([]byte, error) {
fset := token.NewFileSet()
file, err := parser.ParseFile(fset, "", content, parser.ParseComments)
if err != nil {
return nil, fmt.Errorf("failed to parse Go file: %w", err)
}
// If Content is provided, parse and append it
if opts.Content != "" {
// Parse the content as Go code
contentWithPackage := fmt.Sprintf("package tmp\n\n%s", opts.Content)
contentFile, err := parser.ParseFile(fset, "", contentWithPackage, parser.ParseComments)
if err != nil {
return nil, fmt.Errorf("failed to parse content: %w", err)
}
// Add the declarations from content
for _, decl := range contentFile.Decls {
if genDecl, ok := decl.(*ast.GenDecl); ok && genDecl.Tok == token.TYPE {
file.Decls = append(file.Decls, genDecl)
}
}
} else {
// For now, just append types - this is a basic implementation
for _, typeDef := range opts.Types {
typeDecl := createTypeDeclaration(typeDef)
file.Decls = append(file.Decls, typeDecl)
}
}
// Format and return the modified code
var buf bytes.Buffer
if err := format.Node(&buf, fset, file); err != nil {
return nil, fmt.Errorf("failed to format Go code: %w", err)
}
return buf.Bytes(), nil
}
// Helper functions to create AST declarations
// createMethodDeclaration creates the Go code for a method
func createMethodDeclaration(opts MethodOpts) ([]byte, error) {
var buf bytes.Buffer
receiverName := opts.ReceiverName
if receiverName == "" {
// Default receiver name (first letter of type, skipping pointer)
typeWithoutPointer := strings.TrimPrefix(opts.ReceiverType, "*")
if len(typeWithoutPointer) > 0 {
receiverName = strings.ToLower(string(typeWithoutPointer[0]))
} else {
receiverName = "r"
}
}
buf.WriteString(fmt.Sprintf("package tmp\n\nfunc (%s %s) %s(", receiverName, opts.ReceiverType, opts.Name))
// Add parameters
for i, param := range opts.Parameters {
if i > 0 {
buf.WriteString(", ")
}
buf.WriteString(fmt.Sprintf("%s %s", param.Name, param.Type))
}
buf.WriteString(")")
// Add return type
if opts.ReturnType != "" {
buf.WriteString(" " + opts.ReturnType)
}
buf.WriteString(" {\n")
// Add body
if opts.Body != "" {
// Split body into lines and indent
lines := strings.Split(opts.Body, "\n")
for _, line := range lines {
if strings.TrimSpace(line) != "" {
buf.WriteString("\t" + line + "\n")
} else {
buf.WriteString("\n")
}
}
}
buf.WriteString("}\n")
return buf.Bytes(), nil
}
// createFunctionDeclaration creates the Go code for a function
func createFunctionDeclaration(opts FunctionOpts) ([]byte, error) {
var buf bytes.Buffer
buf.WriteString(fmt.Sprintf("package tmp\n\nfunc %s(", opts.Name))
// Add parameters
for i, param := range opts.Parameters {
if i > 0 {
buf.WriteString(", ")
}
buf.WriteString(fmt.Sprintf("%s %s", param.Name, param.Type))
}
buf.WriteString(")")
// Add return type
if opts.ReturnType != "" {
buf.WriteString(" " + opts.ReturnType)
}
buf.WriteString(" {\n")
// Add body
if opts.Body != "" {
// Split body into lines and indent
lines := strings.Split(opts.Body, "\n")
for _, line := range lines {
if strings.TrimSpace(line) != "" {
buf.WriteString("\t" + line + "\n")
} else {
buf.WriteString("\n")
}
}
}
buf.WriteString("}\n")
return buf.Bytes(), nil
}
// createVariableDeclaration creates an AST variable declaration
func createVariableDeclaration(variable Variable) *ast.GenDecl {
var specs []ast.Spec
spec := &ast.ValueSpec{
Names: []*ast.Ident{{Name: variable.Name}},
}
if variable.Type != "" {
spec.Type = parseTypeExpr(variable.Type)
}
if variable.Value != "" {
// This is a simplified value parsing - in reality we would need to parse expressions properly
spec.Values = []ast.Expr{&ast.BasicLit{Kind: token.STRING, Value: variable.Value}}
}
specs = append(specs, spec)
return &ast.GenDecl{
Tok: token.VAR,
Specs: specs,
}
}
// createConstantDeclaration creates an AST constant declaration
func createConstantDeclaration(constant Constant) *ast.GenDecl {
var specs []ast.Spec
spec := &ast.ValueSpec{
Names: []*ast.Ident{{Name: constant.Name}},
}
if constant.Type != "" {
spec.Type = parseTypeExpr(constant.Type)
}
if constant.Value != "" {
// This is a simplified value parsing - in reality we would need to parse expressions properly
spec.Values = []ast.Expr{&ast.BasicLit{Kind: token.STRING, Value: constant.Value}}
}
specs = append(specs, spec)
return &ast.GenDecl{
Tok: token.CONST,
Specs: specs,
}
}
// createTypeDeclaration creates an AST type declaration
func createTypeDeclaration(typeDef TypeDef) *ast.GenDecl {
var specs []ast.Spec
spec := &ast.TypeSpec{
Name: &ast.Ident{Name: typeDef.Name},
Type: parseTypeExpr(typeDef.Definition),
}
specs = append(specs, spec)
return &ast.GenDecl{
Tok: token.TYPE,
Specs: specs,
}
}