forked from GoComply/xsd2go
/
attribute.go
103 lines (89 loc) · 2.07 KB
/
attribute.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
package xsd
import (
"encoding/xml"
"fmt"
"github.com/iancoleman/strcase"
)
// Attribute defines single XML attribute
type Attribute struct {
XMLName xml.Name `xml:"http://www.w3.org/2001/XMLSchema attribute"`
Name string `xml:"name,attr"`
Type reference `xml:"type,attr"`
Use string `xml:"use,attr"`
DuplicateCount uint `xml:"-"`
Ref reference `xml:"ref,attr"`
refAttr *Attribute `xml:"-"`
typ Type `xml:"-"`
schema *Schema `xml:"-"`
}
// Public Go Name of this struct item
func (a *Attribute) GoName() string {
name := a.Name
if a.Name == "" {
name = a.Ref.GoName()
}
if a.DuplicateCount >= 2 {
name = fmt.Sprintf("%s%d", name, a.DuplicateCount)
}
return strcase.ToCamel(name)
}
func (a *Attribute) GoType() string {
if a.typ == nil {
return "string"
}
return a.typ.GoName()
}
func (a *Attribute) isPlainString() bool {
if a.typ == nil {
return true
}
_, ok := a.typ.(staticType)
return ok
}
func (a *Attribute) GoForeignModule() string {
if a.isPlainString() {
return ""
}
foreignSchema := (*Schema)(nil)
if a.refAttr != nil {
foreignSchema = a.refAttr.schema
} else if a.typ != nil {
foreignSchema = a.typ.Schema()
}
if foreignSchema != nil && foreignSchema != a.schema &&
foreignSchema.TargetNamespace != a.schema.TargetNamespace {
return foreignSchema.GoPackageName() + "."
}
return ""
}
func (a *Attribute) Modifiers() string {
res := "attr"
if a.optional() {
res += ",omitempty"
}
return res
}
func (a *Attribute) XmlName() string {
if a.Name == "" {
return a.Ref.Name()
}
return a.Name
}
func (a *Attribute) optional() bool {
return a.Use == "optional"
}
func (a *Attribute) compile(s *Schema) {
a.schema = s
if a.Ref != "" {
a.refAttr = a.schema.findReferencedAttribute(a.Ref)
if a.refAttr == nil {
panic("Cannot resolve attribute reference: " + a.Ref)
}
}
if a.Type != "" && a.typ == nil {
a.typ = a.schema.findReferencedType(a.Type)
if a.typ == nil {
panic("Cannot resolve attribute type: " + a.Type)
}
}
}