-
Notifications
You must be signed in to change notification settings - Fork 0
/
template.go
101 lines (83 loc) · 1.69 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
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
package main
import (
"bytes"
"embed"
"fmt"
"go/format"
"os"
"path/filepath"
"text/template"
_ "github.com/lib/pq"
)
//go:embed templates/*
var gotemplates embed.FS
type dbInfo struct {
PkgName string
}
type tableInfo struct {
FileName string
CustomFileName string
PkgName string
StructName string
ShortStructName string
StdPkgs []string
NonStdPkgs []string
Name string
Columns []columnInfo
PrimaryKeys []primaryKeyInfo
HasPrimaryKey bool
HasManyPrimaryKey bool
HasBaseModel bool
ForeignTables []foreignTableInfo
HasForeignTable bool
}
type primaryKeyInfo struct {
ColumnName string
ArgName string
GoType string
}
type foreignTableInfo struct {
FieldName string
StructName string
Nullable bool
}
type columnInfo struct {
Name string
DBType string
IsPrimaryKey bool
FieldName string
GoType string
Nullable bool
OmitJson bool
}
func writeGoTmpl(tmplFile, file string, overwrite bool, data interface{}) error {
path := filepath.Join(*outDir, file)
if !overwrite {
if _, err := os.Stat(path); err == nil {
return nil
}
}
content, err := gotemplates.ReadFile("templates/" + tmplFile)
if err != nil {
return err
}
tmpl, err := template.New(tmplFile).Parse(string(content))
if err != nil {
return err
}
f, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0666)
if err != nil {
return err
}
defer f.Close()
var buf bytes.Buffer
if err := tmpl.Execute(&buf, data); err != nil {
return err
}
source, err := format.Source(buf.Bytes())
if err != nil {
return fmt.Errorf("%s\n\n%w", buf.String(), err)
}
_, err = f.Write(source)
return err
}