-
Notifications
You must be signed in to change notification settings - Fork 0
/
file.go
109 lines (88 loc) · 1.87 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
package di
import (
"bytes"
"go/format"
)
type PackageType int
const (
unknownPackage PackageType = iota
PublicPackage
InternalPackage
DefinitionsPackage
FactoriesPackage
LookupPackage
lastPackage
)
var packageDirs = [lastPackage]string{
InternalPackage: "internal",
DefinitionsPackage: "internal/definitions",
FactoriesPackage: "internal/factories",
LookupPackage: "internal/lookup",
}
type File struct {
Package PackageType
Name string
Content []byte
}
func (f *File) Path() string {
path := packageDirs[f.Package]
if path != "" {
path += "/"
}
return path + f.Name
}
type FileBuilder struct {
fileName string
packageName string
packageType PackageType
imports []string
body bytes.Buffer
}
func NewFileBuilder(filename, packageName string, packageType PackageType) *FileBuilder {
return &FileBuilder{
fileName: filename,
packageName: packageName,
packageType: packageType,
}
}
func (b *FileBuilder) AddImport(imp string) {
if imp == "" {
return
}
for _, existingImport := range b.imports {
if existingImport == imp {
return
}
}
b.imports = append(b.imports, imp)
}
func (b *FileBuilder) Write(p []byte) (n int, err error) {
return b.body.Write(p)
}
func (b *FileBuilder) WriteString(s string) (n int, err error) {
return b.body.WriteString(s)
}
func (b *FileBuilder) IsEmpty() bool {
return b.body.Len() == 0
}
func (b *FileBuilder) GetFile() *File {
var buffer bytes.Buffer
buffer.WriteString("package " + b.packageName + "\n\n")
if len(b.imports) > 0 {
buffer.WriteString("import (\n")
for _, imp := range b.imports {
buffer.WriteString("\t" + imp + "\n")
}
buffer.WriteString(")\n")
}
b.body.WriteTo(&buffer)
content, err := format.Source(buffer.Bytes())
if err != nil {
content = buffer.Bytes()
}
return &File{
Package: b.packageType,
Name: b.fileName,
Content: content,
}
}