-
-
Notifications
You must be signed in to change notification settings - Fork 43
/
struct.go
202 lines (176 loc) · 6.37 KB
/
struct.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
package builder
import (
"fmt"
"go/types"
"strings"
"github.com/dave/jennifer/jen"
"github.com/jmattheis/goverter/xtype"
)
// Struct handles struct types.
type Struct struct{}
// Matches returns true, if the builder can create handle the given types.
func (*Struct) Matches(source, target *xtype.Type) bool {
return source.Struct && target.Struct
}
// Build creates conversion source code for the given source and target type.
func (*Struct) Build(gen Generator, ctx *MethodContext, sourceID *xtype.JenID, source, target *xtype.Type) ([]jen.Code, *xtype.JenID, *Error) {
name := ctx.Name(target.ID())
stmt := []jen.Code{
jen.Var().Id(name).Add(target.TypeAsJen()),
}
for i := 0; i < target.StructType.NumFields(); i++ {
targetField := target.StructType.Field(i)
if _, ignore := ctx.IgnoredFields[targetField.Name()]; ignore {
continue
}
if !targetField.Exported() {
cause := unexportedStructError(targetField.Name(), source.T.String(), target.T.String())
return nil, nil, NewError(cause).Lift(&Path{
Prefix: ".",
SourceID: "???",
TargetID: targetField.Name(),
TargetType: targetField.Type().String(),
})
}
targetFieldType := xtype.TypeOf(targetField.Type())
if _, ok := ctx.IdentityMapping[targetField.Name()]; ok {
fieldStmt, fieldID, err := gen.Build(ctx, sourceID, source, targetFieldType)
if err != nil {
return nil, nil, err.Lift(&Path{
Prefix: ".",
SourceID: "<mapIdentity>",
SourceType: source.T.String(),
TargetID: targetField.Name(),
TargetType: targetField.Type().String(),
})
}
stmt = append(stmt, fieldStmt...)
stmt = append(stmt, jen.Id(name).Dot(targetField.Name()).Op("=").Add(fieldID.Code))
continue
}
nextID, nextSource, mapStmt, lift, err := mapField(gen, ctx, targetField, sourceID, source, target)
if err != nil {
return nil, nil, err
}
stmt = append(stmt, mapStmt...)
fieldStmt, fieldID, err := gen.Build(ctx, xtype.VariableID(nextID), nextSource, targetFieldType)
if err != nil {
return nil, nil, err.Lift(lift...)
}
stmt = append(stmt, fieldStmt...)
stmt = append(stmt, jen.Id(name).Dot(targetField.Name()).Op("=").Add(fieldID.Code))
}
return stmt, xtype.VariableID(jen.Id(name)), nil
}
func mapField(gen Generator, ctx *MethodContext, targetField *types.Var, sourceID *xtype.JenID, source, target *xtype.Type) (*jen.Statement, *xtype.Type, []jen.Code, []*Path, *Error) {
lift := []*Path{}
mappedName, hasOverride := ctx.Mapping[targetField.Name()]
if ctx.Signature.Target != target.T.String() || !hasOverride {
sourceMatch, err := source.StructField(targetField.Name(), ctx.MatchIgnoreCase, ctx.IgnoredFields)
if err == nil {
nextID := sourceID.Code.Clone().Dot(sourceMatch.Name)
lift = append(lift, &Path{
Prefix: ".",
SourceID: sourceMatch.Name,
SourceType: sourceMatch.Type.T.String(),
TargetID: targetField.Name(),
TargetType: targetField.Type().String(),
})
return nextID, sourceMatch.Type, []jen.Code{}, lift, nil
}
// field lookup either did not find anything or failed due to ambiquous match with case ignored
cause := fmt.Sprintf("Cannot match the target field with the source entry: %s.", err.Error())
return nil, nil, nil, nil, NewError(cause).Lift(&Path{
Prefix: ".",
SourceID: "???",
TargetID: targetField.Name(),
TargetType: targetField.Type().String(),
})
}
path := strings.Split(mappedName, ".")
var condition *jen.Statement
stmt := []jen.Code{}
nextID := sourceID.Code
nextSource := source
for i := 0; i < len(path); i++ {
if nextSource.Pointer {
addCondition := nextID.Clone().Op("!=").Nil()
if condition == nil {
condition = addCondition
} else {
condition = condition.Clone().Op("&&").Add(addCondition)
}
nextSource = nextSource.PointerInner
}
if !nextSource.Struct {
cause := fmt.Sprintf("Cannot access '%s' on %s.", path[i], nextSource.T)
return nil, nil, nil, nil, NewError(cause).Lift(&Path{
Prefix: ".",
SourceID: path[i],
SourceType: "???",
}).Lift(lift...)
}
// since we are searching for a mapped name, search for exact match, explicit field map does not ignore case
sourceMatch, err := nextSource.StructField(path[i], false, ctx.IgnoredFields)
if err == nil {
nextSource = sourceMatch.Type
nextID = nextID.Clone().Dot(sourceMatch.Name)
liftPath := &Path{
Prefix: ".",
SourceID: sourceMatch.Name,
SourceType: nextSource.T.String(),
}
if i == len(path)-1 {
liftPath.TargetID = targetField.Name()
liftPath.TargetType = targetField.Type().String()
if condition != nil && !nextSource.Pointer {
liftPath.SourceType = fmt.Sprintf("*%s (It is a pointer because the nested property in the goverter:map was a pointer)", liftPath.SourceType)
}
}
lift = append(lift, liftPath)
continue
}
cause := fmt.Sprintf("Cannot find the mapped field on the source entry: %s.", err.Error())
return nil, nil, []jen.Code{}, nil, NewError(cause).Lift(&Path{
Prefix: ".",
SourceID: path[i],
SourceType: "???",
}).Lift(lift...)
}
if condition != nil {
pointerNext := nextSource
if !nextSource.Pointer {
pointerNext = xtype.TypeOf(types.NewPointer(nextSource.T))
}
tempName := ctx.Name(pointerNext.ID())
stmt = append(stmt, jen.Var().Id(tempName).Add(pointerNext.TypeAsJen()))
if nextSource.Pointer {
stmt = append(stmt, jen.If(condition).Block(
jen.Id(tempName).Op("=").Add(nextID.Clone()),
))
} else {
stmt = append(stmt, jen.If(condition).Block(
jen.Id(tempName).Op("=").Op("&").Add(nextID.Clone()),
))
}
nextSource = pointerNext
nextID = jen.Id(tempName)
}
return nextID, nextSource, stmt, lift, nil
}
func unexportedStructError(targetField, sourceType, targetType string) string {
return fmt.Sprintf(`Cannot set value for unexported field "%s".
Possible solutions:
* Ignore the given field with:
// goverter:ignore %s
* Convert the struct yourself and use goverter for converting nested structs / maps / lists.
* Create a custom converter function (only works, if the struct with unexported fields is nested inside another struct)
func CustomConvert(source %s) %s {
// implement me
}
// goverter:extend CustomConvert
type MyConverter interface {
// ...
}
See https://github.com/jmattheis/goverter#extend-with-custom-implementation`, targetField, targetField, sourceType, targetType)
}