/
file.go
124 lines (105 loc) · 2.11 KB
/
file.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
124
package srcgen
import (
"go/build"
"io/ioutil"
"os"
"path"
"path/filepath"
"strings"
"unsafe"
"github.com/wzshiming/namecase"
"golang.org/x/tools/imports"
)
type File struct {
srcgen
filename string
packname string
imports map[string]string
buildIgnore bool
}
func NewFile() *File {
return &File{}
}
func (f *File) Save() error {
if f.filename == "" {
f.filename = "auto_gen.go"
}
if f.packname == "" {
dir := filepath.Dir(f.filename)
b, err := build.ImportDir(dir, 0)
if err != nil {
_, dir = filepath.Split(dir)
if dir == "." || dir == ".." || dir == "" {
f.packname = "main"
} else {
f.packname = dir
}
} else {
f.packname = b.Name
}
f.packname = namecase.ToLowerSnake(f.packname)
}
err := os.MkdirAll(filepath.Dir(f.filename), 0755)
if err != nil {
return err
}
return ioutil.WriteFile(f.filename, f.Bytes(), 0666)
}
func (f *File) WithPackname(packname string) *File {
f.packname = packname
return f
}
func (f *File) WithFilename(filename string) *File {
f.filename = filename
return f
}
func (f *File) AddImport(aliase, importpath string) *File {
if f.imports == nil {
f.imports = map[string]string{}
}
if aliase == "" {
_, aliase = path.Split(importpath)
aliase = strings.SplitN(aliase, ".", 2)[0]
}
if aliase == "_" {
_, ok := f.imports[importpath]
if ok {
return f
}
}
f.imports[importpath] = aliase
return f
}
func (f *File) SetBuildIgnore(b bool) *File {
f.buildIgnore = b
return f
}
func (f *File) Bytes() []byte {
buf := srcgen{}
if f.buildIgnore {
buf.WriteFormat(`// +build ignore
`)
}
buf.WriteFormat(`// Code generated; DO NOT EDIT.
// file %s
package %s
`, f.filename, f.packname)
if len(f.imports) != 0 {
buf.WriteFormat("import(\n")
for path, aliase := range f.imports {
buf.WriteFormat("%s \"%s\"\n", aliase, path)
}
buf.WriteFormat(")\n\n")
}
buf.WriteString(f.srcgen.String())
data := buf.Bytes()
dataf, err := imports.Process(f.filename, data, nil)
if err != nil {
return data
}
return dataf
}
func (f *File) String() string {
data := f.Bytes()
return *(*string)(unsafe.Pointer(&data))
}