/
gen.go
236 lines (214 loc) Β· 5.27 KB
/
gen.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
package main
import (
"fmt"
"io/ioutil"
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
"goa.design/goa/codegen"
"goa.design/goa/pkg"
)
// Generator is the code generation management data structure.
type Generator struct {
// Command is the name of the command to run.
Command string
// DesignPath is the Go import path to the design package.
DesignPath string
// Output is the absolute path to the output directory.
Output string
// bin is the filename of the generated generator.
bin string
// tmpDir is the temporary directory used to compile the generator.
tmpDir string
}
// NewGenerator creates a Generator.
func NewGenerator(cmd string, path, output string) *Generator {
bin := "goa"
if runtime.GOOS == "windows" {
bin += ".exe"
}
return &Generator{
Command: cmd,
DesignPath: path,
Output: output,
bin: bin,
}
}
// Write writes the main file.
func (g *Generator) Write(debug bool) error {
var tmpDir string
{
wd := "."
if cwd, err := os.Getwd(); err != nil {
wd = cwd
}
tmp, err := ioutil.TempDir(wd, "goa")
if err != nil {
return err
}
tmpDir = tmp
}
g.tmpDir = tmpDir
var sections []*codegen.SectionTemplate
{
data := map[string]interface{}{
"Command": g.Command,
"CleanupDirs": cleanupDirs(g.Command, g.Output),
}
imports := []*codegen.ImportSpec{
codegen.SimpleImport("flag"),
codegen.SimpleImport("fmt"),
codegen.SimpleImport("os"),
codegen.SimpleImport("path/filepath"),
codegen.SimpleImport("sort"),
codegen.SimpleImport("strings"),
codegen.SimpleImport("goa.design/goa/codegen/generator"),
codegen.SimpleImport("goa.design/goa/eval"),
codegen.SimpleImport("goa.design/goa/pkg"),
codegen.NewImport("_", g.DesignPath),
}
sections = []*codegen.SectionTemplate{
codegen.Header("Code Generator", "main", imports),
{
Name: "main",
Source: mainT,
Data: data,
},
}
}
f := &codegen.File{Path: "main.go", SectionTemplates: sections}
_, err := f.Render(tmpDir)
return err
}
// Compile compiles the generator.
func (g *Generator) Compile() error {
gobin, err := exec.LookPath("go")
if err != nil {
return fmt.Errorf(`failed to find a go compiler, looked in "%s"`, os.Getenv("PATH"))
}
c := exec.Cmd{
Path: gobin,
Args: []string{gobin, "build", "-o", g.bin},
Dir: g.tmpDir,
}
out, err := c.CombinedOutput()
if err != nil {
if len(out) > 0 {
return fmt.Errorf(string(out))
}
return fmt.Errorf("failed to compile generator: %s", err)
}
return nil
}
// Run runs the compiled binary and return the output lines.
func (g *Generator) Run() ([]string, error) {
var cmdl string
{
args := make([]string, len(os.Args)-1)
gopaths := filepath.SplitList(os.Getenv("GOPATH"))
for i, a := range os.Args[1:] {
for _, p := range gopaths {
if strings.Contains(a, p) {
args[i] = strings.Replace(a, p, "$(GOPATH)", -1)
break
}
}
if args[i] == "" {
args[i] = a
}
}
cmdl = " " + strings.Join(args, " ")
rawcmd := filepath.Base(os.Args[0])
// Remove .exe suffix to avoid different output on Windows.
rawcmd = strings.TrimSuffix(rawcmd, ".exe")
cmdl = fmt.Sprintf("$ %s%s", rawcmd, cmdl)
}
args := []string{"--version=" + pkg.Version(), "--output=" + g.Output, "--cmd=" + cmdl}
cmd := exec.Command(filepath.Join(g.tmpDir, g.bin), args...)
out, err := cmd.CombinedOutput()
if err != nil {
return nil, fmt.Errorf("%s\n%s", err, string(out))
}
res := strings.Split(string(out), "\n")
for (len(res) > 0) && (res[len(res)-1] == "") {
res = res[:len(res)-1]
}
return res, nil
}
// Remove deletes the package files.
func (g *Generator) Remove() {
if g.tmpDir != "" {
os.RemoveAll(g.tmpDir)
g.tmpDir = ""
}
}
// cleanupDirs returns the paths of the subdirectories under gendir to delete
// before generating code.
func cleanupDirs(cmd, output string) []string {
if cmd == "gen" {
gendirPath := filepath.Join(output, codegen.Gendir)
gendir, err := os.Open(gendirPath)
if err != nil {
return nil
}
defer gendir.Close()
finfos, err := gendir.Readdir(-1)
if err != nil {
return []string{gendirPath}
}
dirs := []string{}
for _, fi := range finfos {
if fi.IsDir() {
dirs = append(dirs, filepath.Join(gendirPath, fi.Name()))
}
}
return dirs
}
return nil
}
// mainT is the template for the generator main.
const mainT = `func main() {
var (
out = flag.String("output", "", "")
version = flag.String("version", "", "")
cmdl = flag.String("cmd", "", "")
)
{
flag.Parse()
if *out == "" {
fail("missing output flag")
}
if *version == "" {
fail("missing version flag")
}
if *cmdl == "" {
fail("missing cmd flag")
}
}
if *version != pkg.Version() {
fail("cannot run generator produced by goa version %s and compiled with goa version %s\n", *version, pkg.Version())
}
if err := eval.Context.Errors; err != nil {
fail(err.Error())
}
if err := eval.RunDSL(); err != nil {
fail(err.Error())
}
{{- range .CleanupDirs }}
if err := os.RemoveAll({{ printf "%q" . }}); err != nil {
fail(err.Error())
}
{{- end }}
outputs, err := generator.Generate(*out, {{ printf "%q" .Command }})
if err != nil {
fail(err.Error())
}
fmt.Println(strings.Join(outputs, "\n"))
}
func fail(msg string, vals ...interface{}) {
fmt.Fprintf(os.Stderr, msg, vals...)
os.Exit(1)
}
`