-
Notifications
You must be signed in to change notification settings - Fork 10
/
slicewriter.go
139 lines (108 loc) · 2.37 KB
/
slicewriter.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
package slice
import (
"io"
"regexp"
"strings"
"github.com/clipperhouse/typewriter"
)
func init() {
err := typewriter.Register(NewSliceWriter())
if err != nil {
panic(err)
}
}
func SliceName(typ typewriter.Type) string {
return typ.Name + "Slice"
}
type SliceWriter struct{}
func NewSliceWriter() *SliceWriter {
return &SliceWriter{}
}
func (sw *SliceWriter) Name() string {
return "slice"
}
func (sw *SliceWriter) Imports(typ typewriter.Type) (result []typewriter.ImportSpec) {
// typewriter uses golang.org/x/tools/imports, depend on that
return
}
func (sw *SliceWriter) Write(w io.Writer, typ typewriter.Type) error {
tag, found := typ.FindTag(sw)
if !found {
return nil
}
if includeSortImplementation(tag.Values) {
s := `// Sort implementation is a modification of http://golang.org/pkg/sort/#Sort
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found at http://golang.org/LICENSE.
`
w.Write([]byte(s))
}
// start with the slice template
tmpl, err := templates.ByTag(typ, tag)
if err != nil {
return err
}
m := model{
Type: typ,
SliceName: SliceName(typ),
}
if err := tmpl.Execute(w, m); err != nil {
return err
}
for _, v := range tag.Values {
var tp typewriter.Type
if len(v.TypeParameters) > 0 {
tp = v.TypeParameters[0]
}
m := model{
Type: typ,
SliceName: SliceName(typ),
TypeParameter: tp,
TagValue: v,
}
tmpl, err := templates.ByTagValue(typ, v)
if err != nil {
return err
}
if err := tmpl.Execute(w, m); err != nil {
return err
}
}
if includeSortInterface(tag.Values) {
tmpl, err := sortInterface.Parse()
if err != nil {
return err
}
if err := tmpl.Execute(w, m); err != nil {
return err
}
}
if includeSortImplementation(tag.Values) {
tmpl, err := sortImplementation.Parse()
if err != nil {
return err
}
if err := tmpl.Execute(w, m); err != nil {
return err
}
}
return nil
}
func includeSortImplementation(values []typewriter.TagValue) bool {
for _, v := range values {
if strings.HasPrefix(v.Name, "SortBy") {
return true
}
}
return false
}
func includeSortInterface(values []typewriter.TagValue) bool {
reg := regexp.MustCompile(`^Sort(Desc)?$`)
for _, v := range values {
if reg.MatchString(v.Name) {
return true
}
}
return false
}