This repository has been archived by the owner on Apr 22, 2024. It is now read-only.
/
writer.go
207 lines (179 loc) · 4.32 KB
/
writer.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
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
package writer
import (
"fmt"
"go/ast"
"sort"
"strings"
"github.com/antosdaniel/dtogen/internal/generator"
"golang.org/x/tools/imports"
)
// writer Helps writing Go code.
type writer struct {
body string
currentIndent int
}
func New() generator.Writer {
return &writer{
body: "",
currentIndent: 0,
}
}
// String Returns written code.
func (w *writer) String() string {
result, err := imports.Process("", []byte(w.body), nil)
if err == nil {
return string(result)
}
return w.body
}
// In Increases indentation. Next lines will be indented by one level (tab) more.
func (w *writer) In() {
w.currentIndent += 1
}
// Out Decreases indentation. Next lines will be indented by one level (tab) less.
func (w *writer) Out() {
if w.currentIndent > 0 {
w.currentIndent -= 1
}
}
func (w *writer) indent() string {
indent := ""
for i := 0; i < w.currentIndent; i++ {
indent += "\t"
}
return indent
}
func (w *writer) Write(code string) {
w.body += w.indent() + code
}
func (w *writer) WriteLine(code string) {
if code == "" {
w.WriteEmptyLine()
return
}
w.body += w.indent() + code + "\n"
}
func (w *writer) WriteEmptyLine() {
w.body += "\n"
}
func (w *writer) WritePackage(pkg string) {
w.WriteLine(fmt.Sprintf("package %s", pkg))
}
func (w *writer) WriteImports(imports generator.Imports) {
if len(imports) == 0 {
return
}
w.WriteLine("import (")
w.In()
for _, i := range sortImports(imports) {
if i.Alias() != "" {
w.WriteLine(fmt.Sprintf("%s %q", i.Alias(), i.Path()))
} else {
w.WriteLine(fmt.Sprintf("%q", i.Path()))
}
}
w.Out()
w.WriteLine(")")
}
func sortImports(imports generator.Imports) generator.Imports {
sort.Slice(imports, func(i, j int) bool {
// First sort by path A-Z
if imports[i].Path() != imports[j].Path() {
return imports[i].Path() < imports[j].Path()
}
// Then sort by aliases A-Z
return imports[i].Alias() < imports[j].Alias()
})
return imports
}
func (w *writer) WriteStruct(structName string, fields generator.Fields) {
w.WriteLine(fmt.Sprintf("type %s struct {", structName))
w.In()
col := longestFieldNameLength(fields) + 1
for _, f := range fields {
fieldType := f.OverrideTypeTo()
if fieldType == "" {
fieldType = writeType(f.Type())
}
space := strings.Repeat(" ", col-len(f.DesiredName()))
w.WriteLine(f.DesiredName() + space + fieldType)
}
w.Out()
w.WriteLine("}")
}
func longestFieldNameLength(fields generator.Fields) int {
result := 0
for _, f := range fields {
l := len(f.DesiredName())
if l > result {
result = l
}
}
return result
}
func writeType(fieldType ast.Expr) string {
switch fieldType.(type) {
case *ast.Ident:
return fieldType.(*ast.Ident).Name
case *ast.StarExpr:
return "*" + writeType(fieldType.(*ast.StarExpr).X)
case *ast.SelectorExpr:
sel := fieldType.(*ast.SelectorExpr)
return writeType(sel.X) + "." + sel.Sel.Name
case *ast.ArrayType:
return "[]" + writeType(fieldType.(*ast.ArrayType).Elt)
case *ast.MapType:
m := fieldType.(*ast.MapType)
return "map[" + writeType(m.Key) + "]" + writeType(m.Value)
default:
return "<unsupported type>" // TODO
}
}
func (w *writer) WriteMapper(mapper generator.Mapper) {
w.WriteLine(fmt.Sprintf(
"func New%s(src %s.%s) %s {",
mapper.DestinationTypeName,
mapper.SourceImportName,
mapper.SourceTypeName,
mapper.DestinationTypeName,
))
w.In()
w.WriteLine(fmt.Sprintf("return %s{", mapper.DestinationTypeName))
w.In()
col := longestMappingDestinationLength(mapper.Mappings) + 1
for _, m := range mapper.Mappings {
space := strings.Repeat(" ", col-len(m.Destination()))
w.WriteLine(fmt.Sprintf("%s:%s%s,", m.Destination(), space, mappingSource(m)))
}
w.Out()
w.WriteLine("}")
w.Out()
w.WriteLine("}")
// TODO: Helpers should be handled in separate method
for _, h := range mapper.Helpers {
w.WriteEmptyLine()
w.WriteLine(h.Code())
}
}
func mappingSource(m generator.Mapping) string {
if m.IsFunction() {
return m.Source() + "(src." + m.Field() + ")"
}
if m.IsField() {
return "src." + m.Source()
}
if m.IsMethod() {
return "src." + m.Source() + "()"
}
return generator.HandwrittenMapperName(m.Source()) + "(src." + m.Field() + ")"
}
func longestMappingDestinationLength(mappings generator.Mappings) int {
result := 0
for _, m := range mappings {
l := len(m.Destination())
if l > result {
result = l
}
}
return result
}