-
Notifications
You must be signed in to change notification settings - Fork 0
/
gogen.go
executable file
·123 lines (102 loc) · 2.26 KB
/
gogen.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
package gogen
import (
"fmt"
"github.com/pkg/errors"
"path/filepath"
"text/template"
)
type File interface {
Generate(cfg *Config) (Document, error)
}
type Option interface {
apply(cfg *Config) error
}
type optionFunc func(*Config) error
func (o optionFunc) apply(s *Config) error {
if err := o(s); err != nil {
return err
}
return nil
}
func SetDescription(desc string) Option {
return optionFunc(func(cfg *Config) error {
cfg.Description = desc
return nil
})
}
func SkipChildren(skip bool) Option {
return optionFunc(func(cfg *Config) error {
cfg.SkipChildren = skip
return nil
})
}
var ErrTemplateExtensionEmpty = errors.New("Template extension can not be empty")
func SetTemplateExtension(extension string) Option {
return optionFunc(func(cfg *Config) error {
if extension == "" {
return ErrTemplateExtensionEmpty
}
cfg.TemplateExtensionSuffix = extension
return nil
})
}
func SetGlobalTemplateData(templateData interface{}) Option {
return optionFunc(func(cfg *Config) error {
cfg.TemplateData = templateData
return nil
})
}
func SetGlobalFuncMap(funcs template.FuncMap) Option {
return optionFunc(func(cfg *Config) error {
cfg.TemplateFuncs = funcs
return nil
})
}
func Generate(file File, opts ...Option) error {
cfg := DefaultConfig
for _, opt := range opts {
if err := opt.apply(&cfg); err != nil {
return fmt.Errorf("unable to apply option %w", err)
}
}
if err := generate(file, &cfg); err != nil {
return err
}
return nil
}
func generate(file File, cfg *Config) error {
doc, err := file.Generate(cfg)
if err != nil {
return err
}
if docs, ok := isDocs(doc); ok {
for _, doc = range docs {
if err := Write(doc); err != nil {
return err
}
}
} else {
if err := Write(doc); err != nil {
return err
}
}
return nil
}
func isDocs(doc Document) ([]Document, bool) {
if docs, ok := doc.(Docs); ok {
return docs, true
}
return nil, false
}
func Write(file Document) error {
if w, ok := file.(DocWriter); ok {
return w.Write(file)
}
if err := makeDir(filepath.Dir(file.Path())); err != nil {
return errors.Wrap(err, "failed to create directory")
}
if err := createFile(file.Path(), file.Bytes()); err != nil {
return errors.Wrapf(err, "failed to write %s", file.Path())
}
return nil
}