-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathgen_code.go
84 lines (72 loc) · 1.72 KB
/
gen_code.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
package fastapi
import (
"bytes"
"fmt"
"go/format"
"log"
"os"
"path/filepath"
"text/template"
"github.com/funny/fastbin"
)
func GenCode(app *App, apps ...*App) {
apps = append(apps, app)
gopath := os.Getenv("GOPATH")
if gopath == "" {
panic("GOPATH environment variable missing")
}
path, err := filepath.Abs(gopath)
if err != nil {
panic(err)
}
path = filepath.Join(path, "src")
for _, pkg := range packages(apps) {
saveCode(
filepath.Join(path, pkg.Path),
filepath.Base(pkg.Path)+".fastapi.go",
genPackage(pkg),
)
for _, msg := range pkg.Messages {
fastbin.RegisterType(msg.Type())
}
}
}
func saveCode(dir, filename string, code []byte) {
filename = filepath.Join(dir, filename)
file, err := os.Create(filename)
if err != nil {
log.Fatalf("Create file '%s' failed: %s", filename, err)
}
if _, err := file.Write(code); err != nil {
log.Fatalf("Write file '%s' failed: %s", filename, err)
}
file.Close()
}
func genPackage(pkg *packageInfo) (code []byte) {
tpl := template.Must(
template.New("fastapi").Funcs(template.FuncMap{
"Package": func() string {
return filepath.Base(pkg.Path)
},
}).Parse(appTemplate),
)
var bf bytes.Buffer
err := tpl.Execute(&bf, pkg)
if err != nil {
log.Fatalf("Generate code failed: %s", err)
}
code, err = format.Source(bf.Bytes())
if err != nil {
fmt.Print(bf.String())
log.Fatalf("Could't format source: %s", err)
}
code = bytes.Replace(code, []byte("\n\n"), []byte("\n"), -1)
code = bytes.Replace(code, []byte("n = 0\n"), []byte("\n"), -1)
code = bytes.Replace(code, []byte("+ 0\n"), []byte("\n"), -1)
code, err = format.Source(code)
if err != nil {
fmt.Print(bf.String())
log.Fatalf("Could't format source: %s", err)
}
return
}