-
Notifications
You must be signed in to change notification settings - Fork 3
/
generator_executor.go
66 lines (58 loc) · 1.48 KB
/
generator_executor.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
package eapi
import (
"fmt"
"os"
"path/filepath"
"github.com/gotomicro/eapi/generators"
"github.com/gotomicro/eapi/spec"
)
type generatorExecutor struct {
cfg *GeneratorConfig
doc *spec.T
getConfig func(key string) interface{}
}
func newGeneratorExecutor(cfg *GeneratorConfig, doc *spec.T, getConfig func(key string) interface{}) *generatorExecutor {
return &generatorExecutor{cfg: cfg, doc: doc, getConfig: getConfig}
}
func (r *generatorExecutor) execute() (err error) {
var ok bool
item := r.cfg
var generator *generators.Generator
if item.File != "" {
generator = generators.NewGeneratorFromFile(item.File)
} else {
if item.Name == "" {
return fmt.Errorf("generator name or file cannot be empty")
}
generator, ok = generators.Generators[item.Name]
if !ok {
return fmt.Errorf("generator '%s' not exists", item.Name)
}
}
err = r.generate(generator)
if err != nil {
return
}
return
}
func (r *generatorExecutor) generate(t *generators.Generator) error {
result := t.Print(r.doc, &generators.PrintOptions{GetConfig: r.getConfig})
for _, item := range result {
outputFile := filepath.Join(r.cfg.Output, item.FileName)
dir := filepath.Dir(outputFile)
err := os.MkdirAll(dir, os.ModePerm)
if err != nil {
return err
}
file, err := os.OpenFile(outputFile, os.O_CREATE|os.O_TRUNC|os.O_RDWR, os.ModePerm)
if err != nil {
return err
}
_, err = file.WriteString(item.Code)
if err != nil {
return err
}
file.Close()
}
return nil
}