MCPcopy Create free account
hub / github.com/goadesign/goa / transformObject

Function transformObject

codegen/go_transform.go:120–378  ·  view source on GitHub ↗

transformObject generates Go code to transform source object to target object.

(source, target *expr.AttributeExpr, sourceVar, targetVar string, newVar bool, ta *TransformAttrs)

Source from the content-addressed store, hash-verified

118// transformObject generates Go code to transform source object to target
119// object.
120func transformObject(source, target *expr.AttributeExpr, sourceVar, targetVar string, newVar bool, ta *TransformAttrs) (string, error) {
121 var (
122 initCode string
123 postInitCode string
124 err error
125 )
126 {
127 // walk through primitives first to initialize the struct
128 walkMatches(source, target, func(srcMatt, tgtMatt *expr.MappedAttributeExpr, srcc, tgtc *expr.AttributeExpr, n string) {
129 if !expr.IsPrimitive(srcc.Type) {
130 return
131 }
132 // Source and/or target could be primitive user type. Make sure the
133 // aliased type is compatible for transformation.
134 if err = IsCompatible(srcc.Type, tgtc.Type, sourceVar, targetVar); err != nil {
135 return
136 }
137 var (
138 exp string
139
140 srcPtr = ta.SourceCtx.IsPrimitivePointer(n, srcMatt.AttributeExpr)
141 tgtPtr = ta.TargetCtx.IsPrimitivePointer(n, tgtMatt.AttributeExpr)
142 srcField = sourceVar + "." + GoifyAtt(srcc, srcMatt.ElemName(n), true)
143 tgtField = GoifyAtt(tgtc, tgtMatt.ElemName(n), true)
144 _, isSrcUT = srcc.Type.(expr.UserType)
145 _, isTgtUT = tgtc.Type.(expr.UserType)
146 )
147 {
148 switch {
149 case isSrcUT || isTgtUT:
150 deref := ""
151 if srcPtr {
152 deref = "*"
153 }
154 exp = fmt.Sprintf("%s(%s%s)", ta.TargetCtx.Scope.Ref(tgtc, ta.TargetCtx.Pkg(tgtc)), deref, srcField)
155 if srcPtr && !srcMatt.IsRequired(n) {
156 postInitCode += fmt.Sprintf("if %s != nil {\n", srcField)
157 if tgtPtr {
158 tmp := Goify(tgtMatt.ElemName(n), false)
159 postInitCode += fmt.Sprintf("%s := %s\n%s.%s = &%s\n", tmp, exp, targetVar, tgtField, tmp)
160 } else {
161 postInitCode += fmt.Sprintf("%s.%s = %s\n", targetVar, tgtField, exp)
162 }
163 postInitCode += "}\n"
164 return
165 } else if tgtPtr {
166 tmp := Goify(tgtMatt.ElemName(n), false)
167 postInitCode += fmt.Sprintf("%s := %s\n%s.%s = &%s\n", tmp, exp, targetVar, tgtField, tmp)
168 return
169 }
170 case srcPtr && !tgtPtr:
171 exp = "*" + srcField
172 if !srcMatt.IsRequired(n) {
173 postInitCode += fmt.Sprintf("if %s != nil {\n\t%s.%s = %s\n}\n", srcField, targetVar, tgtField, exp)
174 return
175 }
176 case !srcPtr && tgtPtr:
177 exp = "&" + srcField

Callers 1

transformAttributeFunction · 0.70

Calls 15

IsPrimitiveFunction · 0.92
IsArrayFunction · 0.92
AsArrayFunction · 0.92
IsMapFunction · 0.92
AsMapFunction · 0.92
IsUnionFunction · 0.92
IsObjectFunction · 0.92
IsAliasFunction · 0.92
IsCompatibleFunction · 0.85
GoifyAttFunction · 0.85
GoifyFunction · 0.85
transformUnionFunction · 0.85

Tested by

no test coverage detected