/
build.go
1205 lines (1003 loc) · 37.5 KB
/
build.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
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
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package ast
import (
"bytes"
"errors"
"fmt"
"go/ast"
"go/parser"
"go/token"
"io"
"os"
"path/filepath"
"runtime"
"strconv"
"strings"
"sync"
"unicode"
"github.com/influx6/faux/metrics"
"github.com/influx6/faux/types/actions"
"github.com/influx6/faux/types/events"
"github.com/influx6/gobuild/build"
"github.com/influx6/gobuild/srcpath"
"github.com/influx6/moz/gen"
)
var (
// ErrEmptyList defines a error returned for a empty array or slice.
ErrEmptyList = errors.New("Slice/List is empty")
// ErrPackageParseFailed defines a error returned when a package processing failed to work.
ErrPackageParseFailed = errors.New("Package or Package file failed to be parsed")
// we need to ensure we catch all processed packages to ensure we dont get stuck
// re-processing in a loop again.
processedPackages = struct {
pl sync.Mutex
pkgs map[string]Package
processing map[string]struct{}
}{
pkgs: make(map[string]Package),
}
)
// ParseFileAnnotations parses the package from the provided file.
func ParseFileAnnotations(log metrics.Metrics, path string) (Package, error) {
return PackageFileWithBuildCtx(log, path, build.Default)
}
// ParseAnnotations parses the package which generates a series of ast with associated
// annotation for processing.
func ParseAnnotations(log metrics.Metrics, dir string) (Packages, error) {
return PackageWithBuildCtx(log, dir, build.Default)
}
//===========================================================================================================
// FilteredPackageWithBuildCtx parses the package directory which generates a series of ast with associated
// annotation for processing by using the golang token parser, it uses the build.Context to
// collected context details for the package and only processes the files found by the build context.
// If you need something more broad without filtering, use PackageWithBuildCtx.
func FilteredPackageWithBuildCtx(log metrics.Metrics, dir string, ctx build.Context) (Packages, error) {
rootbuildPkg, err := ctx.ImportDir(dir, 0)
if err != nil {
log.Emit(metrics.Errorf("Failed to retrieve build.Package for root directory"),
metrics.With("file", dir),
metrics.With("dir", dir),
metrics.With("error", err.Error()),
metrics.With("mode", build.FindOnly))
return nil, err
}
if len(rootbuildPkg.GoFiles) == 0 {
return nil, &build.NoGoError{}
}
log.Emit(metrics.Info("Generated build.Package"),
metrics.With("file", dir),
metrics.With("dir", dir),
metrics.With("pkg", rootbuildPkg),
metrics.With("mode", build.FindOnly))
allowed := make(map[string]bool)
for _, file := range rootbuildPkg.GoFiles {
allowed[file] = true
}
filter := func(f os.FileInfo) bool {
log.Emit(metrics.Info("Parse Filtering file"), metrics.With("incoming-file", f.Name()), metrics.With("allowed", allowed[f.Name()]))
return allowed[f.Name()]
}
tokenFiles := token.NewFileSet()
packages, err := parser.ParseDir(tokenFiles, dir, filter, parser.ParseComments)
if err != nil {
log.Emit(metrics.Error(err), metrics.With("message", "Failed to parse dir"), metrics.With("dir", dir))
return nil, err
}
packageDeclrs := make(map[string]Package)
packageBuilds := make(map[string]*build.Package)
for tag, pkg := range packages {
var pkgFiles []string
for path, file := range pkg.Files {
pkgFiles = append(pkgFiles, path)
pathPkg := filepath.Dir(path)
buildPkg, ok := packageBuilds[pathPkg]
if !ok {
buildPkg, err = ctx.ImportDir(pathPkg, 0)
if err != nil {
log.Emit(metrics.Errorf("Failed to retrieve build.Package"),
metrics.With("file", path),
metrics.With("dir", dir),
metrics.With("file-dir", filepath.Dir(path)),
metrics.With("error", err.Error()),
metrics.With("mode", build.FindOnly))
} else {
packageBuilds[pathPkg] = buildPkg
log.Emit(metrics.Info("Generated build.Package"),
metrics.With("file", path),
metrics.With("pkg", buildPkg),
metrics.With("file-dir", filepath.Dir(path)),
metrics.With("dir", dir),
metrics.With("mode", build.FindOnly))
}
}
res, err := parseFileToPackage(log, dir, path, pkg.Name, tokenFiles, file, pkg)
if err != nil {
log.Emit(metrics.Error(err), metrics.With("message", "Failed to parse file"), metrics.With("dir", dir), metrics.With("file", file.Name.Name), metrics.With("Package", pkg.Name))
return nil, err
}
log.Emit(metrics.Info("Parsed Package File"), metrics.With("dir", dir), metrics.With("file", file.Name.Name), metrics.With("path", path), metrics.With("Package", pkg.Name))
if owner, ok := packageDeclrs[pkg.Name]; ok {
if strings.HasSuffix(tag, "_test") {
owner.TestPackages = append(owner.TestPackages, res)
} else {
owner.Packages = append(owner.Packages, res)
}
packageDeclrs[res.Package] = owner
continue
}
var testPkgs, codePkgs []PackageDeclaration
if strings.HasSuffix(tag, "_test") {
testPkgs = append(testPkgs, res)
} else {
codePkgs = append(codePkgs, res)
}
packageDeclrs[res.Package] = Package{
Tag: tag,
Name: res.Package,
Path: res.Path,
FilePath: filepath.Base(res.FilePath),
BuildPkg: buildPkg,
Files: pkgFiles,
Packages: codePkgs,
TestPackages: testPkgs,
}
}
if owner, ok := packageDeclrs[pkg.Name]; ok {
owner.Files = pkgFiles
packageDeclrs[pkg.Name] = owner
}
}
var pkgs []Package
for _, pkg := range packageDeclrs {
pkgs = append(pkgs, pkg)
}
return pkgs, nil
}
// PackageWithBuildCtx parses the package directory which generates a series of ast with associated
// annotation for processing by using the golang token parser, it uses the build.Context to
// collected context details for the package but does not use it has a means to select the files to
// process. PackageWithBuildCtx processes all files in package directory. If you want one which takes
// into consideration build.Context fields using FilteredPackageWithBuildCtx.
func PackageWithBuildCtx(log metrics.Metrics, dir string, ctx build.Context) ([]Package, error) {
tokenFiles := token.NewFileSet()
packages, err := parser.ParseDir(tokenFiles, dir, nil, parser.ParseComments)
if err != nil {
log.Emit(metrics.Error(err), metrics.With("message", "Failed to parse directory"), metrics.With("dir", dir))
return nil, err
}
packageDeclrs := make(map[string]Package)
packageBuilds := make(map[string]*build.Package)
for pkgTag, pkg := range packages {
uniqueDir := fmt.Sprintf("%s#%s", dir, pkgTag)
processedPackages.pl.Lock()
res, ok := processedPackages.pkgs[uniqueDir]
if ok {
log.Emit(metrics.Info("Skipping package processing"), metrics.With("dir", dir))
processedPackages.pl.Unlock()
packageDeclrs[pkg.Name] = res
continue
}
processedPackages.pl.Unlock()
var pkgFiles []string
for path, file := range pkg.Files {
pkgFiles = append(pkgFiles, path)
pathPkg := filepath.Dir(path)
buildPkg, ok := packageBuilds[pathPkg]
if !ok {
buildPkg, err = ctx.ImportDir(pathPkg, 0)
if err != nil {
log.Emit(metrics.Errorf("Failed to retrieve build.Package"),
metrics.With("file", path),
metrics.With("dir", dir),
metrics.With("file-dir", filepath.Dir(path)),
metrics.With("error", err.Error()),
metrics.With("mode", build.FindOnly))
} else {
packageBuilds[pathPkg] = buildPkg
log.Emit(metrics.Info("Generated build.Package"),
metrics.With("file", path),
metrics.With("pkg", buildPkg),
metrics.With("file-dir", filepath.Dir(path)),
metrics.With("dir", dir),
metrics.With("mode", build.FindOnly))
}
}
res, err := parseFileToPackage(log, dir, path, pkg.Name, tokenFiles, file, pkg)
if err != nil {
log.Emit(metrics.Error(err), metrics.With("message", "Failed to parse file"), metrics.With("dir", dir), metrics.With("file", file.Name.Name), metrics.With("Package", pkg.Name))
return nil, err
}
if owner, ok := packageDeclrs[pkg.Name]; ok {
if strings.HasSuffix(pkgTag, "_test") {
owner.TestPackages = append(owner.TestPackages, res)
} else {
owner.Packages = append(owner.Packages, res)
}
packageDeclrs[res.Package] = owner
continue
}
var testPkgs, codePkgs []PackageDeclaration
if strings.HasSuffix(pkgTag, "_test") {
testPkgs = append(testPkgs, res)
} else {
codePkgs = append(codePkgs, res)
}
impPkg := Package{
Name: res.Package,
Dir: pathPkg,
FilePath: path,
Path: res.Path,
Tag: pkgTag,
BuildPkg: buildPkg,
Packages: codePkgs,
TestPackages: testPkgs,
}
packageDeclrs[pkg.Name] = impPkg
}
if owner, ok := packageDeclrs[pkg.Name]; ok {
owner.Files = pkgFiles
packageDeclrs[pkg.Name] = owner
processedPackages.pl.Lock()
processedPackages.pkgs[uniqueDir] = owner
processedPackages.pl.Unlock()
}
}
var pkgs []Package
for _, pkg := range packageDeclrs {
pkgs = append(pkgs, pkg)
}
return pkgs, nil
}
// PackageFileWithBuildCtx parses the package from the provided file.
func PackageFileWithBuildCtx(log metrics.Metrics, path string, ctx build.Context) (Package, error) {
dir := filepath.Dir(path)
fName := filepath.Base(path)
buildPkg, err := ctx.ImportDir(dir, 0)
if err != nil {
log.Emit(metrics.Errorf("Failed to retrieve build.Package"),
metrics.With("file", path),
metrics.With("dir", dir),
metrics.With("error", err.Error()),
metrics.With("mode", build.FindOnly))
}
log.Emit(metrics.Info("Generated build.Package"),
metrics.With("file", path),
metrics.With("dir", dir),
metrics.With("pkg", buildPkg),
metrics.With("mode", build.FindOnly))
allowed := map[string]bool{
fName: true,
}
filter := func(f os.FileInfo) bool {
log.Emit(metrics.Info("Parse Filtering file"), metrics.With("incoming-file", f.Name()), metrics.With("allowed", allowed[f.Name()]))
return allowed[f.Name()]
}
tokenFiles := token.NewFileSet()
packages, err := parser.ParseDir(tokenFiles, path, filter, parser.ParseComments)
if err != nil {
log.Emit(metrics.Error(err), metrics.With("message", "Failed to parse file"), metrics.With("dir", dir), metrics.With("file", path))
return Package{}, err
}
var pkg *ast.Package
var pkgTag string
pkgName := filepath.Base(filepath.Dir(path))
for pkgTag, pkg = range packages {
if pkg.Name != pkgName {
continue
}
break
}
var pkgFiles []string
for fpath, file := range pkg.Files {
if fpath != path {
continue
}
pkgFiles = append(pkgFiles, fpath)
res, err := parseFileToPackage(log, dir, path, buildPkg.Name, tokenFiles, file, pkg)
if err != nil {
log.Emit(metrics.Error(err), metrics.With("message", "Failed to parse file"), metrics.With("dir", dir), metrics.With("file", file.Name.Name), metrics.With("Package", pkg.Name))
return Package{}, err
}
var testPkgs, codePkgs []PackageDeclaration
if strings.HasSuffix(pkgTag, "_test") {
testPkgs = append(testPkgs, res)
} else {
codePkgs = append(codePkgs, res)
}
return Package{
BuildPkg: buildPkg,
Tag: pkgTag,
Files: pkgFiles,
Path: res.Path,
Name: res.Package,
FilePath: res.FilePath,
Packages: codePkgs,
TestPackages: testPkgs,
}, nil
}
return Package{}, ErrPackageParseFailed
}
func parseFileToPackage(log metrics.Metrics, dir string, path string, pkgName string, tokenFiles *token.FileSet, file *ast.File, pkgAstObj *ast.Package) (PackageDeclaration, error) {
var packageDeclr PackageDeclaration
{
pkgSource, _ := readSource(path)
packageDeclr.Package = pkgName
packageDeclr.Dir = dir
packageDeclr.FilePath = path
packageDeclr.Source = string(pkgSource)
packageDeclr.ImportedPackages = make(map[string]Package)
packageDeclr.Imports = make(map[string]ImportDeclaration, 0)
packageDeclr.ObjectFunc = make(map[*ast.Object][]FuncDeclaration, 0)
if relPath, err := relativeToSrc(path); err == nil {
packageDeclr.Path = filepath.Dir(relPath)
packageDeclr.File = filepath.Base(relPath)
}
if file.Doc != nil {
for _, comment := range file.Doc.List {
packageDeclr.Comments = append(packageDeclr.Comments, comment.Text)
}
}
for _, imp := range file.Imports {
beginPosition, endPosition := tokenFiles.Position(imp.Pos()), tokenFiles.Position(imp.End())
positionLength := endPosition.Offset - beginPosition.Offset
source, err := readSourceIn(beginPosition.Filename, int64(beginPosition.Offset), positionLength)
if err != nil {
return packageDeclr, err
}
var pkgName string
if imp.Name != nil {
if imp.Name.Name == "_" {
continue
}
pkgName = strings.Replace(imp.Name.Name, "/", "", -1)
} else {
pkgName = strings.Replace(filepath.Base(imp.Path.Value), "\"", "", -1)
}
if pkgNm, perr := strconv.Unquote(pkgName); perr == nil {
pkgName = pkgNm
}
impPkgPath, err := strconv.Unquote(imp.Path.Value)
if err != nil {
impPkgPath = imp.Path.Value
}
if impPkgPath == packageDeclr.Path {
continue
}
var comment string
if imp.Comment != nil {
comment = imp.Comment.Text()
}
var internal bool
if _, err := relativeToSrc(filepath.Join(goSrcPath, impPkgPath)); err != nil {
internal = true
}
imported := ImportDeclaration{
Comments: comment,
Name: pkgName,
Path: impPkgPath,
InternalPkg: internal,
Source: string(source),
}
packageDeclr.Imports[pkgName] = imported
if _, ok := packageDeclr.ImportedPackages[imported.Path]; !ok {
var importDir string
if !imported.InternalPkg {
importDir = srcpath.FromSrcPath(imported.Path)
} else {
//importDir = srcpath.FromRootPath(imported.Path)
}
// Check if import path exists else skip.
if stat, err := os.Stat(importDir); err == nil && stat.IsDir() {
uniqueImportDir := importDir + "#" + imported.Name
processedPackages.pl.Lock()
res, ok := processedPackages.pkgs[uniqueImportDir]
processedPackages.pl.Unlock()
if ok {
packageDeclr.ImportedPackages[imported.Path] = res
} else {
imps, err := PackageWithBuildCtx(log, importDir, build.Default)
if err != nil {
return packageDeclr, err
}
processedPackages.pl.Lock()
for _, imppkg := range imps {
imppath := imppkg.Dir + "#" + imported.Name
processedPackages.pkgs[imppath] = imppkg
packageDeclr.ImportedPackages[imppkg.Path] = imppkg
}
processedPackages.pl.Unlock()
}
}
}
}
if runtime.GOOS == "windows" {
packageDeclr.Path = filepath.ToSlash(packageDeclr.Path)
packageDeclr.File = filepath.ToSlash(packageDeclr.File)
packageDeclr.FilePath = filepath.ToSlash(packageDeclr.FilePath)
}
if file.Doc != nil {
annotationRead := ReadAnnotationsFromCommentry(bytes.NewBufferString(file.Doc.Text()))
log.Emit(metrics.Info("Annotations in Package comments"),
metrics.With("dir", dir),
metrics.With("annotations", len(annotationRead)),
metrics.With("file", file.Name.Name))
packageDeclr.Annotations = append(packageDeclr.Annotations, annotationRead...)
}
// Collect and categorize annotations in types and their fields.
declrLoop:
for _, declr := range file.Decls {
tokenFile := tokenFiles.File(declr.Pos())
beginPosition, endPosition := tokenFile.Position(declr.Pos()), tokenFile.Position(declr.End())
beginOffset := beginPosition.Offset
endOffset := endPosition.Offset
positionLength := (endOffset - beginOffset)
source, err := readSourceIn(tokenFile.Name(), int64(beginOffset), positionLength)
if err != nil {
return packageDeclr, err
}
switch rdeclr := declr.(type) {
case *ast.FuncDecl:
var comment string
if rdeclr.Doc != nil {
comment = rdeclr.Doc.Text()
}
var annotations []AnnotationDeclaration
associations := make(map[string]AnnotationAssociationDeclaration, 0)
if rdeclr.Doc != nil {
annotationRead := ReadAnnotationsFromCommentry(bytes.NewBufferString(rdeclr.Doc.Text()))
for _, item := range annotationRead {
log.Emit(metrics.Info("Annotation in Function Decleration comment"), metrics.With("dir", dir), metrics.With("annotation", item.Name))
switch item.Name {
case "associates":
log.Emit(
metrics.Info("Association found"),
metrics.With("dir", dir),
metrics.With("association", item.Arguments),
)
if len(item.Arguments) >= 3 {
associations[item.Arguments[0]] = AnnotationAssociationDeclaration{
Record: item,
Template: item.Template,
Action: item.Arguments[1],
TypeName: item.Arguments[2],
Annotation: strings.TrimPrefix(item.Arguments[0], "@"),
}
} else {
log.Emit(metrics.Error(errors.New("Association Annotation in Declaration is incomplete: Expects 3 elements")), metrics.With("dir", dir), metrics.With("association", item.Arguments))
}
default:
annotations = append(annotations, item)
}
}
}
var defFunc FuncDeclaration
defFunc.Comments = comment
defFunc.Source = string(source)
defFunc.TypeDeclr = declr
defFunc.FuncDeclr = rdeclr
defFunc.Type = rdeclr.Type
defFunc.Position = rdeclr.Pos()
defFunc.Path = packageDeclr.Path
defFunc.File = packageDeclr.File
defFunc.Declr = &packageDeclr
defFunc.FuncName = rdeclr.Name.Name
defFunc.FuncNameWithPackage = fmt.Sprintf("%s.%s", packageDeclr.Package, rdeclr.Name.Name)
defFunc.Length = positionLength
defFunc.From = beginPosition.Offset
defFunc.Package = packageDeclr.Package
defFunc.FilePath = packageDeclr.FilePath
defFunc.Annotations = annotations
defFunc.Associations = associations
defFunc.Exported = unicode.IsUpper(rune(rdeclr.Name.Name[0]))
if rdeclr.Type != nil {
defFunc.Returns = rdeclr.Type.Results
defFunc.Arguments = rdeclr.Type.Params
}
if rdeclr.Recv != nil {
defFunc.FuncType = rdeclr.Recv
nameIdent := rdeclr.Recv.List[0]
var receiverNameType *ast.Ident
switch nmi := nameIdent.Type.(type) {
case *ast.Ident:
receiverNameType = nmi
case *ast.StarExpr:
receiverNameType = nmi.X.(*ast.Ident)
defFunc.RecieverPointer = nmi
}
defFunc.Reciever = receiverNameType.Obj
defFunc.RecieverIdent = receiverNameType
defFunc.RecieverName = receiverNameType.Name
if rems, ok := packageDeclr.ObjectFunc[receiverNameType.Obj]; ok {
rems = append(rems, defFunc)
packageDeclr.ObjectFunc[receiverNameType.Obj] = rems
} else {
packageDeclr.ObjectFunc[receiverNameType.Obj] = []FuncDeclaration{defFunc}
}
continue declrLoop
}
packageDeclr.Functions = append(packageDeclr.Functions, defFunc)
continue declrLoop
case *ast.GenDecl:
var comment string
if rdeclr.Doc != nil {
comment = rdeclr.Doc.Text()
}
var annotations []AnnotationDeclaration
associations := make(map[string]AnnotationAssociationDeclaration, 0)
if rdeclr.Doc != nil {
annotationRead := ReadAnnotationsFromCommentry(bytes.NewBufferString(rdeclr.Doc.Text()))
for _, item := range annotationRead {
log.Emit(metrics.Info("Annotation in Decleration comment"),
metrics.With("dir", dir),
metrics.With("annotation", item.Name))
switch item.Name {
case "associates":
log.Emit(
metrics.Info("Association found"),
metrics.With("dir", dir),
metrics.With("association", item.Arguments),
)
if len(item.Arguments) >= 3 {
associations[item.Arguments[0]] = AnnotationAssociationDeclaration{
Record: item,
Template: item.Template,
Action: item.Arguments[1],
TypeName: item.Arguments[2],
Annotation: strings.TrimPrefix(item.Arguments[0], "@"),
}
} else {
log.Emit(metrics.Error(errors.New("Association Annotation in Declaration is incomplete: Expects 3 elements")), metrics.With("dir", dir), metrics.With("association", item.Arguments))
}
default:
annotations = append(annotations, item)
}
}
}
for _, spec := range rdeclr.Specs {
switch obj := spec.(type) {
case *ast.ValueSpec:
// Handles variable declaration
// i.e Spec:
// &ast.ValueSpec{Doc:(*ast.CommentGroup)(nil), Names:[]*ast.Ident{(*ast.Ident)(0xc4200e4a00)}, Type:ast.Expr(nil), Values:[]ast.Expr{(*ast.BasicLit)(0xc4200e4a20)}, Comment:(*ast.CommentGroup)(nil)}
// &ast.ValueSpec{Doc:(*ast.CommentGroup)(nil), Names:[]*ast.Ident{(*ast.Ident)(0xc4200e4a40)}, Type:(*ast.Ident)(0xc4200e4a60), Values:[]ast.Expr(nil), Comment:(*ast.CommentGroup)(nil)}
var name string
var nameWithPackage string
var nameIdent *ast.Ident
if len(obj.Names) != 0 {
nameIdent = obj.Names[0]
name = nameIdent.Name
nameWithPackage = fmt.Sprintf("%s.%s", packageDeclr.Package, name)
}
packageDeclr.Variables = append(packageDeclr.Variables, VariableDeclaration{
Object: obj,
Name: name,
NameIdent: nameIdent,
NameWithPackage: nameWithPackage,
Annotations: annotations,
Associations: associations,
GenObj: rdeclr,
Source: string(source),
Comments: comment,
Declr: &packageDeclr,
File: packageDeclr.File,
Package: packageDeclr.Package,
Path: packageDeclr.Path,
FilePath: packageDeclr.FilePath,
From: beginPosition.Offset,
Length: positionLength,
})
case *ast.TypeSpec:
switch robj := obj.Type.(type) {
case *ast.StructType:
log.Emit(metrics.Info("Annotation in Decleration"),
metrics.With("Type", "Struct"),
metrics.With("Annotations", len(annotations)),
metrics.With("StructName", obj.Name.Name))
packageDeclr.Structs = append(packageDeclr.Structs, StructDeclaration{
Object: obj,
Struct: robj,
Name: obj.Name.Name,
NameWithPackage: fmt.Sprintf("%s.%s", packageDeclr.Package, obj.Name.Name),
Annotations: annotations,
Associations: associations,
GenObj: rdeclr,
Source: string(source),
Comments: comment,
Declr: &packageDeclr,
File: packageDeclr.File,
Package: packageDeclr.Package,
Path: packageDeclr.Path,
FilePath: packageDeclr.FilePath,
From: beginPosition.Offset,
Length: positionLength,
})
case *ast.InterfaceType:
log.Emit(metrics.Info("Annotation in Decleration"),
metrics.With("Type", "Interface"),
metrics.With("Annotations", len(annotations)),
metrics.With("StructName", obj.Name.Name))
packageDeclr.Interfaces = append(packageDeclr.Interfaces, InterfaceDeclaration{
Object: obj,
Interface: robj,
GenObj: rdeclr,
Name: obj.Name.Name,
NameWithPackage: fmt.Sprintf("%s.%s", packageDeclr.Package, obj.Name.Name),
Comments: comment,
Annotations: annotations,
Associations: associations,
Declr: &packageDeclr,
Source: string(source),
File: packageDeclr.File,
Package: packageDeclr.Package,
Path: packageDeclr.Path,
FilePath: packageDeclr.FilePath,
From: beginPosition.Offset,
Length: positionLength,
})
default:
log.Emit(metrics.Info("Annotation in Decleration"),
metrics.With("Type", "OtherType"),
metrics.With("Marker", "NonStruct/NonInterface:Type"),
metrics.With("Annotations", len(annotations)),
metrics.With("StructName", obj.Name.Name))
var mainType *ast.Ident
var argType *ArgType
var aliasedObject *ast.Object
var aliasedObjectSpec *ast.TypeSpec
if typeIdent, ok := obj.Type.(*ast.Ident); ok {
mainType = typeIdent
if mainType.Obj != nil {
aliasedObject = mainType.Obj
if atype, ok := mainType.Obj.Decl.(*ast.TypeSpec); ok {
aliasedObjectSpec = atype
var field ast.Field
field.Type = atype.Type
if arg, err := GetArgTypeFromField(1, "type", mainType.Name, packageDeclr.File, &field, &packageDeclr); err == nil {
argType = &arg
} else {
log.Emit(
metrics.Error(err),
metrics.Message("Failed to parse TypeSpec internal type"),
metrics.With("type", mainType.Name),
)
}
}
} else {
var field ast.Field
field.Type = typeIdent
if arg, err := GetArgTypeFromField(1, "type", typeIdent.Name, packageDeclr.File, &field, &packageDeclr); err == nil {
argType = &arg
} else {
log.Emit(
metrics.Error(err),
metrics.Message("Failed to parse IdentSpec internal type"),
metrics.With("type", typeIdent.Name),
)
}
}
}
packageDeclr.Types = append(packageDeclr.Types, TypeDeclaration{
Object: obj,
GenObj: rdeclr,
Annotations: annotations,
Name: obj.Name.Name,
NameWithPackage: fmt.Sprintf("%s.%s", packageDeclr.Package, obj.Name.Name),
Comments: comment,
TypeInfo: argType,
Type: mainType,
AliasedType: aliasedObject,
AliasedTypeSpec: aliasedObjectSpec,
Aliased: (aliasedObject != nil),
Associations: associations,
Declr: &packageDeclr,
Source: string(source),
File: packageDeclr.File,
Package: packageDeclr.Package,
Path: packageDeclr.Path,
FilePath: packageDeclr.FilePath,
From: beginPosition.Offset,
Length: positionLength,
})
}
case *ast.ImportSpec:
// Do Nothing.
}
}
case *ast.BadDecl:
// Do Nothing.
}
}
}
return packageDeclr, nil
}
func relativeToSrc(path string) (string, error) {
if _, err := os.Stat(path); err != nil {
return "", err
}
return filepath.Rel(goSrcPath, path)
}
//===========================================================================================================
// SimplyParse takes the provided packages parsing all internals declarations with the appropriate generators suited to the type and annotations.
// Relies on SimpleParsePackage.
func SimplyParse(toDir string, log metrics.Metrics, provider *AnnotationRegistry, doFileOverwrite bool, pkgDeclrs ...Package) error {
for _, pkg := range pkgDeclrs {
if err := SimplyParsePackage(toDir, log, provider, doFileOverwrite, pkg); err != nil {
return err
}
}
return nil
}
// Parse takes the provided packages parsing all internals declarations with the appropriate generators suited to the type and annotations.
// Relies on ParsePackage.
func Parse(toDir string, log metrics.Metrics, provider *AnnotationRegistry, doFileOverwrite bool, pkgDeclrs ...Package) error {
for _, pkg := range pkgDeclrs {
if err := ParsePackage(toDir, log, provider, doFileOverwrite, pkg); err != nil {
return err
}
}
return nil
}
// WriteDirectives defines a function which houses the logic to write WriteDirective into file system.
func WriteDirectives(log metrics.Metrics, toDir string, doFileOverwrite bool, wds ...gen.WriteDirective) error {
for _, wd := range wds {
if err := WriteDirective(log, toDir, doFileOverwrite, wd); err != nil {
return err
}
}
return nil
}
// SimpleWriteDirectives defines a function which houses the logic to write WriteDirective into file system.
func SimpleWriteDirectives(toDir string, doFileOverwrite bool, wds ...gen.WriteDirective) error {
for _, wd := range wds {
if err := SimpleWriteDirective(toDir, doFileOverwrite, wd); err != nil {
return err
}
}
return nil
}
// SimpleWriteDirective defines a function which houses the logic to write WriteDirective into file system.
func SimpleWriteDirective(toDir string, doFileOverwrite bool, item gen.WriteDirective) error {
if filepath.IsAbs(item.Dir) {
return fmt.Errorf("gen.WriteDirectiveError: Expected relative Dir path not absolute: %+q", item.Dir)
}
if item.Before != nil {
if err := item.Before(); err != nil {
return err
}
}
namedFileDir := toDir
baseDir := toDir
if item.Dir != "" {
namedFileDir = filepath.Join(toDir, item.Dir)
}
if filepath.IsAbs(baseDir) {
baseDir = filepath.Base(baseDir)
}
if namedFileDir != "" {
if _, err := os.Stat(namedFileDir); err != nil {
err = os.MkdirAll(namedFileDir, 0700)
if err != nil && err != os.ErrExist {
err = fmt.Errorf("IOError: Unable to create directory: %+q", err)
return err
}
fmt.Printf("Creating directory %q\n", filepath.Join(baseDir, item.Dir))
}
}
if item.Writer == nil {
return nil
}
if item.FileName == "" {
err := fmt.Errorf("WriteDirective has no filename value attached")
return err
}
namedFile := filepath.Join(namedFileDir, item.FileName)
fileStat, err := os.Stat(namedFile)
if err == nil && !fileStat.IsDir() && item.DontOverride && !doFileOverwrite {
return err
}
newFile, err := os.Create(namedFile)
if err != nil {
return err
}
fmt.Printf("Creating new file %q\n", filepath.Join(baseDir, item.Dir, item.FileName))
defer newFile.Close()
_, err = item.Writer.WriteTo(newFile)
if err != nil && err != io.EOF {
err = fmt.Errorf("IOError: Unable to write content to file: %+q", err)
return err
}
if item.After == nil {
return nil
}
return item.After()
}
// WriteDirective defines a function which houses the logic to write WriteDirective into file system.
func WriteDirective(log metrics.Metrics, toDir string, doFileOverwrite bool, item gen.WriteDirective) error {
if item.Before != nil {
if err := item.Before(); err != nil {
return err
}
}
log.Emit(metrics.Info("Execute WriteDirective"),
metrics.With("overwrite", item.DontOverride),
metrics.With("action", actions.MkDirectory{
Dir: item.Dir,
RootDir: toDir,
Mode: 0700,
}))
if filepath.IsAbs(item.Dir) {
err := fmt.Errorf("gen.WriteDirectiveError: Expected relative Dir path not absolute: %+q", item.Dir)
log.Emit(metrics.Error(err), metrics.With("File", item.FileName), metrics.With("Overwrite", item.DontOverride), metrics.With("Dir", item.Dir))
return err
}
namedFileDir := toDir
if item.Dir != "" {
namedFileDir = filepath.Join(toDir, item.Dir)