-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmodel.go
1731 lines (1563 loc) · 53.1 KB
/
model.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 gopoet
import (
"bytes"
"errors"
"fmt"
"io"
"os"
"path/filepath"
"reflect"
"strings"
"go/format"
"go/types"
"path"
"strconv"
"text/template"
)
// Package is a simple representation of a Go package. The name may actually be
// an effective alias (when the package is imported using an alias). A symbol
// whose package has an empty Name is a local symbol: in the same package as the
// referencing context (and thus needs no package prefix to reference that
// symbol).
type Package struct {
ImportPath, Name string
}
// NewPackage is a simple factory method for a package whose name is the same as
// the base name (e.g. last element) of its import path.
//
// If the package name varies from its import path, use a struct initializer
// instead:
//
// Package{Name: "foo", ImportPath: "some.domain.com/foo/v1"}
//
// If you do not know the package name, only the import path, then use
// a struct initializer and leave the Name field empty. An empty Name field will
// cause an alias to be used when the package is registered with an *Imports,
// to ensure that the resulting code will compile and uses a correct package
// prefix.
func NewPackage(importPath string) Package {
return Package{
Name: path.Base(importPath),
ImportPath: importPath,
}
}
// Symbol returns a symbol with the given name in this package.
func (p Package) Symbol(name string) Symbol {
return Symbol{Name: name, Package: p}
}
// String returns the package's name. While this is not always useful (the
// import path is generally more useful), it is the least surprising behavior
// if you reference the package instance from a code block:
//
// gopoet.Printf("%s.Foobar", pkg)
//
// In this example, the result is a qualified reference, such as "pkg.Foobar"
// if the given package's name were "pkg".
func (p Package) String() string {
return p.Name
}
// PackageForGoType returns a Package for the given Go types package. This is
// useful for converting between package representations.
func PackageForGoType(pkg *types.Package) Package {
return Package{
Name: pkg.Name(),
ImportPath: pkg.Path(),
}
}
// Symbol references an element in Go source. It is a const, var, function, or
// type.
type Symbol struct {
Package Package
Name string
}
// SymbolOrMethodRef is either a Symbol or a MethodReference (either of which
// can refer to an element in a Go source file).
type SymbolOrMethodRef interface {
fmt.Stringer
isSymbolOrMethodRef()
}
// NewSymbol creates a symbol for the following package and name. The given
// package path is assumed to have a name that matches its base name (e.g. last
// path element). This function is a convenient shorthand for this:
//
// NewPackage(importPath).Symbol(symName)
func NewSymbol(importPath, symName string) Symbol {
return NewPackage(importPath).Symbol(symName)
}
// SymbolForGoObject returns the given Go types object as a gopoet.Symbol or as
// a gopoet.MethodReference. If the given object is a method, it returns a
// method reference. Otherwise (const, var, type, non-method func), the returned
// value is a symbol.
func SymbolForGoObject(obj types.Object) SymbolOrMethodRef {
if fn, ok := obj.(*types.Func); ok {
sig := fn.Type().(*types.Signature)
if sig.Recv() != nil {
// it's a method
recvType := TypeNameForGoType(sig.Recv().Type())
if recvType.Kind() == KindPtr {
recvType = recvType.Elem()
}
return MethodReference{
Type: recvType.Symbol(),
Method: obj.Name(),
}
}
}
return PackageForGoType(obj.Pkg()).Symbol(obj.Name())
}
// String prints the symbol as it should appear in Go source: pkg.Name. The
// "pkg." prefix will be omitted if the symbol's Package has an empty Name.
func (s Symbol) String() string {
if s.Package.Name != "" {
return s.Package.Name + "." + s.Name
}
return s.Name
}
func (s Symbol) isSymbolOrMethodRef() {}
// GoFile represents a Go source file. It has methods for adding Go source
// declarations such as consts, vars, types, and functions. When building
// the declarations, particularly implementation code that references other
// types and packages, if all references are done using instances of
// gopoet.Package, gopoet.Symbol, and gopoet.TypeName, then the file's
// imports will be managed automatically. Code that constructs a GoFile can
// also use the Imports methods to manually register imports where necessary.
//
// To construct a GoFile, use the NewGoFile factory function.
type GoFile struct {
Imports
// The name of the file. This should not include a path, only a file
// name with a ".go" extension.
Name string
// Comment that appears at the top of the file, before any package doc. This
// is typically a copyright or other disclaimer but can be any file comments
// that should not be construed as package documentation.
FileComment string
// Doc comments that will appear before the package declaration. These will
// be used as Go package documentation by the godoc tool and website.
PackageComment string
// The package name that will be used in the package declaration.
PackageName string
// The canonical import path which, if non-empty, will be used in an
// annotation comment immediately following the package declaration.
CanonicalImportPath string
// The actual elements declared in the source file.
elements []FileElement
}
// FormatError is the kind of error returned from the WriteGoFile method (and
// its variations) when the resulting rendered code has a syntax error that
// prevents it from being formatted by the "go/format" package. Code that gets
// an instance of this kind of error can examine the unformatted code to
// associate formatting error messages (which usually contain line and column
// information) with the text that induced them.
type FormatError struct {
// The unformatted Go code.
Unformatted []byte
// The underlying error returned from the "go/format" package.
Err error
}
// Error implements the error interface, delegating to the underlying error
// returned from the "go/format" package.
func (e *FormatError) Error() string {
return e.Err.Error()
}
// WriteGoFile renders the given Go file to the given writer.
//
// This process first qualifies all elements and code in the given file, to
// ensure that all referenced packages will be correctly represented with
// import statements and that all referenced packages will be rendered with
// the correct package name or alias.
//
// Then this serializes the file elements and contained code into a buffer,
// but with no attention paid to formatting.
//
// Finally, the "go/format" package is used to convert the generated code into
// the Go canonical format, which is primarily needed to clean up whitespace and
// indentation in the output.
//
// The formatted code is then written to the given io.Writer.
func WriteGoFile(w io.Writer, f *GoFile) error {
// make sure all package references are properly qualified for
for i := range f.elements {
f.elements[i].qualify(&f.Imports)
}
// now we generate the code
var buf bytes.Buffer
if err := f.writeTo(&buf); err != nil {
return err
}
// format it
unformatted := buf.Bytes()
formatted, err := format.Source(unformatted)
if err != nil {
return &FormatError{Unformatted: unformatted, Err: err}
}
// and finally emit it
_, err = w.Write(formatted)
return err
}
// WriteGoFiles renders all of the given Go files, using the given function to
// open io.Writer instances, to which the rendered and formatted Go source is
// written. The function is given a Go file's path, which includes both the
// package path and the file's name and is expected to return a writer just for
// that file.
//
// If the function returns an error for any file, this function aborts and
// returns the error, but it makes no effort to clean up any previously written
// files that may have already been written without error.
func WriteGoFiles(outFn func(path string) (io.WriteCloser, error), files ...*GoFile) error {
for _, file := range files {
p := filepath.Join(file.Package().ImportPath, file.Name)
w, err := outFn(p)
if err != nil {
return err
}
err = func() error {
defer w.Close()
return WriteGoFile(w, file)
}()
if err != nil {
return err
}
}
return nil
}
// WriteGoFilesToFileSystem is a convenience wrapper for WriteGoFiles that uses
// os.Open as the function to open a writer for each file. A full path is first
// computed by joining the given root directory with the file's path.
func WriteGoFilesToFileSystem(rootDir string, files ...*GoFile) error {
return WriteGoFiles(func(path string) (io.WriteCloser, error) {
fullPath := filepath.Join(rootDir, path)
dir := filepath.Dir(fullPath)
if err := os.MkdirAll(dir, os.ModePerm); err != nil {
return nil, err
}
return os.OpenFile(fullPath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0666)
}, files...)
}
// WriteGoFilesToGoPath is a convenience wrapper for WriteGoFilesToFileSystem
// that inspects the GOPATH environment variable and uses the first entry
// therein as the root directory for where files are to be written. If the
// GOPATH environment variable is empty or unset, an error is returned.
func WriteGoFilesToGoPath(files ...*GoFile) error {
gopath := os.Getenv("GOPATH")
if gopath == "" {
return errors.New("GOPATH is empty")
}
paths := strings.Split(gopath, string(filepath.ListSeparator))
if len(paths) != 0 {
return errors.New("GOPATH is empty")
}
return WriteGoFilesToFileSystem(paths[0], files...)
}
// NewGoFile creates a new Go file with the given name and package information.
// The given package path is used to ensure that all referenced elements are
// correctly qualified: e.g. if other elements are in the same package they do
// not need a qualifier but other elements do need a qualifier.
//
// The given package name will be referenced in the package statement at the top
// of the rendered Go source file.
func NewGoFile(fileName, packagePath, packageName string) *GoFile {
if filepath.Base(fileName) != fileName {
panic("Go file name must be a base name with no path")
}
if filepath.Ext(fileName) != ".go" {
panic("Go file name must have a '.go' extension")
}
ret := GoFile{Name: fileName, PackageName: packageName}
ret.Imports = *NewImportsFor(packagePath)
return &ret
}
// AddElement adds the given element to this file. This method returns the file,
// for method chaining.
func (f *GoFile) AddElement(e FileElement) *GoFile {
e.setParent(f)
f.elements = append(f.elements, e)
return f
}
// AddConst adds the given const to this file. This is shorthand for wrapping
// the given const up into a *gopoet.ConstDecl and passing that to f.AddElement.
// This method returns the file, for method chaining.
func (f *GoFile) AddConst(c *ConstSpec) *GoFile {
return f.AddElement(&ConstDecl{Consts: []*ConstSpec{c}})
}
// AddVar adds the given var to this file. This is shorthand for wrapping the
// given var up into a *gopoet.VarDecl and passing that to f.AddElement. This
// method returns the file, for method chaining.
func (f *GoFile) AddVar(v *VarSpec) *GoFile {
return f.AddElement(&VarDecl{Vars: []*VarSpec{v}})
}
// AddType adds the given type to this file. This is shorthand for wrapping
// the given type up into a *gopoet.TypeDecl and passing that to f.AddElement.
// This method returns the file, for method chaining.
func (f *GoFile) AddType(t *TypeSpec) *GoFile {
return f.AddElement(&TypeDecl{Types: []*TypeSpec{t}})
}
// NumElements returns the number of top-level elements added to this Go file.
func (f *GoFile) NumElements() int {
return len(f.elements)
}
// ElementAt retrieves the top-level element at the given index. The index must
// be between zero (inclusive) and f.NumElements() (exclusive).
func (f *GoFile) ElementAt(i int) FileElement {
return f.elements[i]
}
// Package returns the package in which the file is declared.
func (f *GoFile) Package() Package {
return Package{
Name: f.PackageName,
ImportPath: f.Imports.pkgPath,
}
}
func (f *GoFile) writeTo(w *bytes.Buffer) error {
writeComment(f.FileComment, w)
if f.FileComment != "" {
// separate file comment from package doc
w.WriteRune('\n')
}
// package and imports pre-amble
writeComment(f.PackageComment, w)
if f.CanonicalImportPath != "" {
fmt.Fprintf(w, "package %s // import %q\n", f.PackageName, f.CanonicalImportPath)
} else {
fmt.Fprintf(w, "package %s\n", f.PackageName)
}
w.WriteRune('\n')
for _, i := range f.ImportSpecs() {
if i.PackageAlias != "" {
fmt.Fprintf(w, "import %s %q\n", i.PackageAlias, i.ImportPath)
} else {
fmt.Fprintf(w, "import %q\n", i.ImportPath)
}
}
// now we print all of the file elements
for _, el := range f.elements {
w.WriteRune('\n')
el.writeTo(w)
}
return nil
}
func writeComment(comment string, w *bytes.Buffer) {
if comment != "" {
lines := strings.Split(comment, "\n")
for _, line := range lines {
fmt.Fprintf(w, "// %s\n", line)
}
}
}
// FileElement is a top-level element in a Go source file. It will be a const,
// var, type, or func declaration. The concrete types that implement this
// interface are *gopoet.ConstDecl, *gopoet.VarDecl, *gopoet.TypeDecl, and
// *gopoet.FuncSpec.
type FileElement interface {
isFileElement()
writeTo(b *bytes.Buffer)
setParent(*GoFile)
qualify(imports *Imports)
}
// ConstDecl is a FileElement representing a declaration of one or more consts.
// When it has exactly one const, it is rendered like so:
//
// const name Type = initialValue
//
// When there are multiple consts, it is rendered differently:
//
// const (
// name1 Type = initialValue
// name2 Type = initialValue
// )
type ConstDecl struct {
Comment string
Consts []*ConstSpec
}
// NewConstDecl creates a new declaration for the given consts.
func NewConstDecl(cs ...*ConstSpec) *ConstDecl {
return &ConstDecl{Consts: cs}
}
// AddConst adds the given const to this declaration. This method returns the
// const declaration, for method chaining.
func (c *ConstDecl) AddConst(cs *ConstSpec) *ConstDecl {
c.Consts = append(c.Consts, cs)
return c
}
// SetComment sets the declaration comment. For declarations with multiple
// consts, this comment is rendered above the "const" keyword, and the comments
// on each ConstSpec are rendered just above each individual const. For example:
//
// // Comment from the ConstDecl
// const (
// // Comment from the first ConstSpec
// c1 = value
// // Comment from the second ConstSpec
// c2 = otherValue
// )
//
// If the declaration has only a single const, then leave this comment empty and
// instead use the Comment field on the ConstSpec only. That will then render
// like so:
//
// // Comment from the ConstSpec
// const c1 = value
//
// This method returns the const declaration, for method chaining.
func (c *ConstDecl) SetComment(comment string) *ConstDecl {
c.Comment = comment
return c
}
func (c *ConstDecl) isFileElement() {}
func (c *ConstDecl) writeTo(b *bytes.Buffer) {
if len(c.Consts) > 1 || c.Comment != "" {
writeComment(c.Comment, b)
b.WriteString("const (\n")
for _, cs := range c.Consts {
cs.writeTo(b, true)
}
b.WriteString(")\n")
return
}
writeComment(c.Consts[0].Comment, b)
b.WriteString("const ")
c.Consts[0].writeTo(b, false)
}
func (c *ConstDecl) setParent(f *GoFile) {
for _, cnst := range c.Consts {
cnst.parent = f
}
}
func (c *ConstDecl) qualify(imports *Imports) {
for _, cs := range c.Consts {
cs.Type = qualifyType(imports, cs.Type)
if cs.Initializer != nil {
cs.Initializer.qualify(imports)
}
}
}
func qualifyType(imports *Imports, t TypeNameOrSpec) TypeNameOrSpec {
switch t := t.(type) {
case nil:
return nil
case TypeName:
return imports.EnsureTypeImported(t)
case *TypeSpec:
t.qualify(imports)
return t
default:
panic(fmt.Sprintf("unrecognized type %T", t))
}
}
// ConstSpec describes a single const expression (which can actually identify
// more than one const). The Names field is not optional and must have at least
// one value. Just like in Go source, the Type field is optional but the
// Initializer is not.
//
// However, there is an exception to this rule: a const is allowed to have
// neither type nor initializer if it follows a const and is intended to re-use
// the prior const's type and initializer. This is typically used with iota
// expressions, like so:
//
// const (
// // This const has both type and initializer
// a int64 = iota+1
// // These consts have neither and will re-use the above type and
// // initializer (relying on the fact that iota is auto-incremented
// // after every reference inside of a const declaration)
// b
// c
// d
// )
type ConstSpec struct {
Comment string
Names []string
Type TypeNameOrSpec
Initializer *CodeBlock
parent *GoFile
}
// NewConst returns a new const expression with the given name(s).
func NewConst(names ...string) *ConstSpec {
return &ConstSpec{Names: names}
}
// SetComment sets the comment for this const expression. See
// ConstDecl.SetComment for more details on how comments are rendered.
//
// This method returns the const, for method chaining.
func (c *ConstSpec) SetComment(comment string) *ConstSpec {
c.Comment = comment
return c
}
// SetType sets the type of this const expression. This method returns the
// const, for method chaining.
func (c *ConstSpec) SetType(t TypeNameOrSpec) *ConstSpec {
c.Type = t
return c
}
// Initialize sets the initializer for this const to a CodeBlock with a single
// statement defined by the given format message and arguments. It is a
// convenient shorthand for this:
// c.Initializer = gopoet.Printf(fmt, args...)
// This method returns the const, for method chaining.
func (c *ConstSpec) Initialize(fmt string, args ...interface{}) *ConstSpec {
c.Initializer = Printf(fmt, args...)
return c
}
// SetInitializer sets the initializer to the given code block. This method
// returns the const, for method chaining.
func (c *ConstSpec) SetInitializer(cb *CodeBlock) *ConstSpec {
c.Initializer = cb
return c
}
// ToSymbol returns a symbol that refers to this const. This method panics if
// the const expression indicates more than one const name, in which case the
// calling code should instead use SymbolAt. This method also panics if this
// const has never been added to a file (see SymbolAt for more information about
// this).
func (c *ConstSpec) ToSymbol() Symbol {
if len(c.Names) != 1 {
panic(fmt.Sprintf("must be exactly one const to use ToSymbol(); use SymbolAt(int) instead: %v", c.Names))
}
return c.SymbolAt(0)
}
// String returns a simple string representation of the const. The string
// representation is the same as that of the symbol returned by ToSymbol,
// however this method will not panic: if the var has never been associated
// with a file, it will return just the const's name, unqualified. Also, if this
// const indicates more than one const name, the returned string will be a
// comma-separated list of all of the symbols.
func (c *ConstSpec) String() string {
if len(c.Names) != 1 {
var syms []string
if c.parent == nil {
syms = c.Names
} else {
syms = make([]string, len(c.Names))
for i := range c.Names {
syms[i] = c.SymbolAt(i).String()
}
}
return strings.Join(syms, ", ")
}
if c.parent == nil {
return c.Names[0]
}
return c.ToSymbol().String()
}
// SymbolAt returns a symbol that refers to the const name at the given index.
// This method panics if the given index is not valid (e.g. between zero,
// inclusive, and len(c.Names), exclusive). This method will also panic if this
// const has never been added to a file since, without an associated file, the
// package of the symbol is unknown. It can be added to a file directly via
// GoFile.AddConst or indirectly by first adding to a ConstDecl which is then
// added to a file.
func (c *ConstSpec) SymbolAt(i int) Symbol {
if c.parent == nil {
panic(fmt.Sprintf("cannot use const %q as symbol because it has not been associated with a file", c.Names[i]))
}
return Symbol{
Name: c.Names[i],
Package: c.parent.Package(),
}
}
func (c *ConstSpec) writeTo(b *bytes.Buffer, includeComment bool) {
if includeComment {
writeComment(c.Comment, b)
}
fmt.Fprintf(b, "%s", strings.Join(c.Names, ", "))
if c.Type != nil {
fmt.Fprintf(b, " %v", c.Type)
}
if c.Initializer != nil {
b.WriteString(" = ")
c.Initializer.writeTo(b)
}
b.WriteRune('\n')
}
// VarDecl is a FileElement representing a declaration of one or more vars. When
// it has exactly one var, it is rendered like so:
//
// var name Type = initialValue
//
// When there are multiple vars, it is rendered differently:
//
// var (
// name1 Type = initialValue
// name2 Type = initialValue
// )
type VarDecl struct {
Comment string
Vars []*VarSpec
}
// NewVarDecl creates a new declaration for the given vars.
func NewVarDecl(vs ...*VarSpec) *VarDecl {
return &VarDecl{Vars: vs}
}
// AddVar adds the given var to this declaration. This method returns the var
// declaration, for method chaining.
func (v *VarDecl) AddVar(vs *VarSpec) *VarDecl {
v.Vars = append(v.Vars, vs)
return v
}
// SetComment sets the declaration comment. For declarations with multiple
// vars, this comment is rendered above the "var" keyword, and the comments on
// each VarSpec are rendered just above each individual var. For example:
//
// // Comment from the VarDecl
// var (
// // Comment from the first VarSpec
// v1 = value
// // Comment from the second VarSpec
// v2 = otherValue
// )
//
// If the declaration has only a single var, then leave this comment empty and
// instead use the Comment field on the VarSpec only. That will then render like
// so:
//
// // Comment from the VarSpec
// var v1 = value
//
// This method returns the var declaration, for method chaining.
func (v *VarDecl) SetComment(comment string) *VarDecl {
v.Comment = comment
return v
}
func (v *VarDecl) isFileElement() {}
func (v *VarDecl) writeTo(b *bytes.Buffer) {
if len(v.Vars) > 1 || v.Comment != "" {
writeComment(v.Comment, b)
b.WriteString("var (\n")
for _, vs := range v.Vars {
vs.writeTo(b, true)
}
b.WriteString(")\n")
return
}
writeComment(v.Vars[0].Comment, b)
b.WriteString("var ")
v.Vars[0].writeTo(b, false)
}
func (v *VarDecl) setParent(f *GoFile) {
for _, vr := range v.Vars {
vr.parent = f
}
}
func (v *VarDecl) qualify(imports *Imports) {
for _, vs := range v.Vars {
vs.Type = qualifyType(imports, vs.Type)
if vs.Initializer != nil {
vs.Initializer.qualify(imports)
}
}
}
// VarSpec describes a single var expression (which can actually identify more
// than one var). The Names field is not optional and must have at least one
// value. Just like in Go source, the Type field is optional only if the
// Initializer is set (in which case, the type is inferred from the type of
// the initializer expression). One or the other, or both, must be present.
type VarSpec struct {
Comment string
Names []string
Type TypeNameOrSpec
Initializer *CodeBlock
parent *GoFile
}
// NewVar returns a new var expression that defines the given name(s).
func NewVar(names ...string) *VarSpec {
return &VarSpec{Names: names}
}
// SetComment sets the comment for this var expression. See VarDecl.SetComment
// for more details on how comments are rendered.
//
// This method returns the var, for method chaining.
func (v *VarSpec) SetComment(comment string) *VarSpec {
v.Comment = comment
return v
}
// SetType sets the type of this var. This method returns the var, for method
// chaining.
func (v *VarSpec) SetType(t TypeNameOrSpec) *VarSpec {
v.Type = t
return v
}
// Initialize sets the initializer for this var to a CodeBlock with a single
// statement defined by the given format message and arguments. It is a
// convenient shorthand for this:
// v.Initializer = gopoet.Printf(fmt, args...)
// This method returns the var, for method chaining.
func (v *VarSpec) Initialize(fmt string, args ...interface{}) *VarSpec {
v.Initializer = Printf(fmt, args...)
return v
}
// SetInitializer sets the initializer to the given code block. This method
// returns the var, for method chaining.
func (v *VarSpec) SetInitializer(cb *CodeBlock) *VarSpec {
v.Initializer = cb
return v
}
// ToSymbol returns a symbol that refers to this var. This method panics if the
// var expression indicates more than one var name, in which case calling code
// should instead use SymbolAt. This method also panics if this var has never
// been added to a file (see SymbolAt for more information about this).
func (v *VarSpec) ToSymbol() Symbol {
if len(v.Names) != 1 {
panic(fmt.Sprintf("must be exactly one var to use ToSymbol(); use SymbolAt(int) instead: %v", v.Names))
}
return v.SymbolAt(0)
}
// String returns a simple string representation of the var. The string
// representation is the same as that of the symbol returned by ToSymbol,
// however this method will not panic: if the var has never been associated
// with a file, it will return just the var's name, unqualified. Also, if this
// var indicates more than one var name, the returned string will be a
// comma-separated list of all of the symbols.
func (v *VarSpec) String() string {
if len(v.Names) != 1 {
var syms []string
if v.parent == nil {
syms = v.Names
} else {
syms = make([]string, len(v.Names))
for i := range v.Names {
syms[i] = v.SymbolAt(i).String()
}
}
return strings.Join(syms, ", ")
}
if v.parent == nil {
return v.Names[0]
}
return v.ToSymbol().String()
}
// SymbolAt returns a symbol that refers to the var name at the given index.
// This method panics if the given index is not valid (e.g. between zero,
// inclusive, and len(v.Names), exclusive). This method will also panic if this
// var has never been added to a file since, without an associated file, the
// package of the symbol is unknown. It can be added to a file directly via
// GoFile.AddVar or indirectly by first adding to a VarDecl which is then added
// to a file.
func (v *VarSpec) SymbolAt(i int) Symbol {
if v.parent == nil {
panic(fmt.Sprintf("cannot use var %s %v as symbol because it has not been associated with a file", v.Names[i], v.Type))
}
return Symbol{
Name: v.Names[i],
Package: v.parent.Package(),
}
}
func (v *VarSpec) writeTo(b *bytes.Buffer, includeComment bool) {
if includeComment {
writeComment(v.Comment, b)
}
fmt.Fprintf(b, "%s", strings.Join(v.Names, ", "))
if v.Type != nil {
fmt.Fprintf(b, " %v", v.Type)
}
if v.Initializer != nil {
b.WriteString(" = ")
v.Initializer.writeTo(b)
}
b.WriteRune('\n')
}
// TypeDecl is a FileElement representing a declaration of one or more types.
// When it has exactly one type, it is rendered like so:
//
// type Name underlyingType
//
// When there are multiple types, it is rendered differently:
//
// type (
// Name1 underlyingType1
// name2 underlyingType2
// )
type TypeDecl struct {
Comment string
Types []*TypeSpec
}
// NewTypeDecl creates a new declaration for the given types.
func NewTypeDecl(ts ...*TypeSpec) *TypeDecl {
return &TypeDecl{Types: ts}
}
// AddType adds the given type to this declaration. This method returns the type
// declaration, for method chaining.
func (t *TypeDecl) AddType(ts *TypeSpec) *TypeDecl {
t.Types = append(t.Types, ts)
return t
}
// SetComment sets the declaration comment. For declarations with multiple
// types, this comment is rendered above the "type" keyword, and the comments on
// each TypeSpec are rendered just above each individual type. For example:
//
// // Comment from the TypeDecl
// type (
// // Comment from the first TypeSpec
// T1 int
// // Comment from the second TypeSpec
// T2 string
// )
//
// If the declaration has only a single type, then leave this comment empty and
// instead use the Comment field on the TypeSpec only. That will then render
// like so:
//
// // Comment from the TypeSpec
// type T1 int
//
// This method returns the type declaration, for method chaining.
func (t *TypeDecl) SetComment(comment string) *TypeDecl {
t.Comment = comment
return t
}
func (t *TypeDecl) isFileElement() {}
func (t *TypeDecl) writeTo(b *bytes.Buffer) {
if len(t.Types) > 1 || t.Comment != "" {
writeComment(t.Comment, b)
b.WriteString("type (\n")
for _, ts := range t.Types {
ts.writeTo(b, true)
}
b.WriteString(")\n")
return
}
writeComment(t.Types[0].Comment, b)
b.WriteString("type ")
t.Types[0].writeTo(b, false)
}
func (t *TypeDecl) setParent(f *GoFile) {
for _, ts := range t.Types {
ts.setParent(f)
}
}
func (t *TypeDecl) qualify(imports *Imports) {
for _, ts := range t.Types {
ts.qualify(imports)
}
}
// TypeSpec describes a single type. The underlying type is not optional and not
// exported, so the only way to create a valid *TypeSpec is using the various
// factory methods (NewTypeSpec, NewTypeAlias, NewStructTypeSpec, and
// NewInterfaceTypeSpec).
type TypeSpec struct {
Comment, Name string
isAlias bool
underlying TypeName
structBody []*FieldSpec
interfaceBody []InterfaceElement
parent *GoFile
}
// NewTypeAlias creates a new type spec that aliases the given type to the given
// name.
func NewTypeAlias(typeName string, t TypeNameOrSpec) *TypeSpec {
ts := NewTypeSpec(typeName, t)
ts.isAlias = true
return ts
}
// NewTypeSpec creates a new type spec that declares the given name to have the
// given underlying type.
func NewTypeSpec(typeName string, t TypeNameOrSpec) *TypeSpec {
switch t := t.(type) {
case *TypeSpec:
ret := &TypeSpec{
Name: typeName,
underlying: t.ToTypeName(),
}
if t.Name == "" {
ret.structBody = append([]*FieldSpec(nil), t.structBody...)
ret.interfaceBody = append([]InterfaceElement(nil), t.interfaceBody...)
}
return ret
case TypeName:
ret := &TypeSpec{
Name: typeName,
underlying: t,
}
switch t.Kind() {
case KindStruct:
fieldTypes := t.Fields()
fields := make([]*FieldSpec, len(fieldTypes))
for i, ft := range fieldTypes {
fields[i] = &FieldSpec{
parent: ret,
Name: ft.Name,
Type: ft.Type,
Tag: ft.Tag,
}
}
ret.structBody = fields
case KindInterface:
embeds := t.Embeds()
methods := t.Methods()
elements := make([]InterfaceElement, len(embeds)+len(methods))
for i, e := range embeds {
elements[i] = &InterfaceEmbed{
parent: ret,
Type: e,
}
}
offs := len(embeds)
for i, m := range methods {
elements[i+offs] = &InterfaceMethod{
parent: ret,
Name: m.Name,
Signature: m.Signature,
}
}
ret.interfaceBody = elements
}
return ret
default:
panic(fmt.Sprintf("unknown type representation %T", t))
}