/
template.go
73 lines (63 loc) · 1.29 KB
/
template.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
package inject
import (
"fmt"
"github.com/americanas-go/annotation"
"text/template"
)
const moduleTemplate = `// Code generated by inject; DO NOT EDIT.
package {{.PackageName}}
import (
{{.Alias}} "{{.ImportPath}}"
{{- range .Imports}}
{{.Alias}} "{{.Path}}"
{{- end}}
"sync"
"go.uber.org/fx"
)
var {{.FunctionName}}Once sync.Once
func {{.FunctionName}}Module() fx.Option {
options := fx.Options()
{{.FunctionName}}Once.Do(func() {
{{if eq .Type "PROVIDE"}}
options = fx.Module("{{.FunctionName}}",
{{else}}
options = fx.Options(
{{end}}
{{- range .Modules}}
{{if .Alias}}{{.Alias}}.{{end}}{{.Entry.Func.Name}}Module(),
{{- end}}
{{if eq .Type "PROVIDE"}}
fx.Provide(
{{.Alias}}.{{.FunctionName}},
{{else}}
fx.Invoke(
{{.Alias}}.{{.FunctionName}},
{{end}}
),
)
})
return options
}
`
type ModuleData struct {
PackageName string
FunctionName string
ImportPath string
Modules []ImportData
Imports []ImportData
Alias string
Entry annotation.Entry
Type string
}
type ImportData struct {
Alias string
Path string
Entry annotation.Entry
}
func NewTemplate() (*template.Template, error) {
tmpl, err := template.New("module").Parse(moduleTemplate)
if err != nil {
return nil, fmt.Errorf("error parsing template: %v", err)
}
return tmpl, nil
}