-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgocode.go
executable file
·173 lines (146 loc) · 4.24 KB
/
gocode.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
package gogen
import (
"bytes"
"fmt"
"github.com/randallmlough/gogen/gocode"
"github.com/randallmlough/gogen/template"
"os"
"path/filepath"
"runtime"
"github.com/pkg/errors"
"github.com/randallmlough/gogen/gocode/imports"
)
type Go struct {
// Template is a string of the entire template that
// will be parsed and rendered. If it's empty,
// the plugin processor will look for .gotpl files
// in the same directory of where you wrote the plugin.
Template string
Bundle string
// Filename is the name of the file that will be
// written to the system disk once the template is rendered.
Filename string
Funcs template.FuncMap
// PackageName is a helper that specifies the package header declaration.
// In other words, when you write the template you don't need to specify `package X`
// at the top of the file. By providing PackageName in the Options, the Generate
// function will do that for you.
PackageName string
Imports []string
packages *gocode.Packages
TemplateData interface{}
data Data
}
func (g *Go) init(cfg *Config) {
if g.packages == nil {
g.packages = &gocode.Packages{}
}
// prefetch all packages in one big packages.Load call
g.packages.LoadAll(g.Imports...)
gocode.CurrentImports = &gocode.Imports{Packages: g.packages, DestDir: filepath.Dir(g.Filename)}
funcs := gocode.Funcs()
for n, f := range cfg.TemplateFuncs {
funcs[n] = f
}
for n, f := range g.Funcs {
funcs[n] = f
}
g.Funcs = funcs
}
func (g *Go) Path() string {
return g.Filename
}
func (g *Go) Bytes() []byte {
return g.data.Bytes()
}
func (g *Go) Generate(cfg *Config) (Document, error) {
if err := cfg.check(); err != nil {
return nil, errors.Wrap(err, "config is improperly formatted")
}
if gocode.CurrentImports != nil {
panic(fmt.Errorf("recursive or concurrent call to RenderToFile detected"))
}
g.init(cfg)
var buf *bytes.Buffer
var err error
tData := cfg.TemplateData
if g.TemplateData != nil {
tData = g.TemplateData
}
if g.Template != "" {
t := template.New("").Funcs(g.Funcs)
var err error
t, err = t.Add("goTemplate" + cfg.TemplateExtensionSuffix).Parse(g.Template)
if err != nil {
return nil, errors.Wrap(err, "error with provided template")
}
buf, err = t.Execute(g.Filename, tData)
if err != nil {
return nil, errors.Wrap(err, "failed to create go file")
}
} else {
// if bundles is empty use location of calling function for template lookup
rootDir := g.Bundle
if rootDir == "" {
_, callerFile, _, _ := runtime.Caller(1)
rootDir = filepath.Dir(callerFile)
}
t := template.New("").Funcs(g.Funcs)
var err error
t, err = t.GatherBundles(rootDir, cfg.TemplateExtensionSuffix, cfg.SkipChildren)
if err != nil {
return nil, errors.Wrap(err, "failed to gather go bundle")
}
buf, err = t.ExecuteBundles(tData, cfg.RegionTags)
if err != nil {
return nil, errors.Wrap(err, "failed to build go bundle")
}
}
data := g.fileTemplate(cfg)
_, err = buf.WriteTo(&data)
if err != nil {
return nil, err
}
gocode.CurrentImports = nil
g.data = &data
return g, nil
}
func (g *Go) fileTemplate(cfg *Config) bytes.Buffer {
var header bytes.Buffer
if cfg.GeneratedHeader {
header.WriteString(cfg.generatedText)
}
if cfg.Description != "" {
header.WriteString(cfg.Description + "\n")
}
header.WriteString("package ")
pkgName := g.PackageName
if pkgName == "" {
pkgName = gocode.PackageNameFromFile(g.Filename)
}
header.WriteString(pkgName)
header.WriteString("\n\n")
if cfg.FileNotice {
header.WriteString(cfg.FileNoticeText)
header.WriteString("\n\n")
}
header.WriteString("import (\n")
header.WriteString(gocode.CurrentImports.String())
header.WriteString(")\n")
return header
}
func (g *Go) Write(file Document) error {
if err := makeDir(filepath.Dir(file.Path())); err != nil {
return errors.Wrap(err, "failed to create directory")
}
formatted, err := imports.Prune(file.Path(), file.Bytes(), g.packages)
if err != nil {
_, _ = fmt.Fprintf(os.Stderr, "gofmt failed on %s: %s\n", filepath.Base(file.Path()), err.Error())
formatted = file.Bytes()
}
if err := createFile(file.Path(), formatted); err != nil {
return errors.Wrapf(err, "failed to write %s", file.Path())
}
g.packages.Evict(gocode.ImportPathForDir(filepath.Dir(g.Filename)))
return nil
}