/
plugin_generator.go
79 lines (59 loc) · 1.35 KB
/
plugin_generator.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
package vm
import (
"bytes"
"text/template"
)
type importSection struct {
HasLib bool
Pkgs []*pkg
}
type pluginSections struct {
ImportSection, VarSection string
}
type pkg struct {
Prefix string
Name string
}
type function struct {
Prefix string
Name string
}
func compileTemplate(obj interface{}, sn, tn string) string {
buffer := &bytes.Buffer{}
t := template.Must(template.New(sn).Parse(tn))
err := t.Execute(buffer, obj)
if err != nil {
panic(err.Error())
}
return buffer.String()
}
func compilePluginTemplate(pkgs []*pkg, funcs []*function) string {
is := compileImportSection(pkgs)
vs := compileVarsSection(funcs)
p := pluginSections{ImportSection: is, VarSection: vs}
return compileTemplate(p, "pluginSections", pluginTemplate)
}
func compileImportSection(pkgs []*pkg) string {
return compileTemplate(pkgs, "importSection", importSectionTemplate)
}
func compileVarsSection(funcs []*function) string {
return compileTemplate(funcs, "functionSection", functionSectionTemplate)
}
const importSectionTemplate = `
import(
{{- range $pkg := .}}
{{printf "%s \"%s\"\n" $pkg.Prefix $pkg.Name -}}
{{- end}}
)
`
const functionSectionTemplate = `
{{- range $f := . }}
{{printf "var %s = %s.%s\n" $f.Name $f.Prefix $f.Name -}}
{{- end}}
`
const pluginTemplate = `
package main
{{ .ImportSection -}}
{{- .VarSection -}}
func main() {}
`