forked from volatiletech/sqlboiler
-
Notifications
You must be signed in to change notification settings - Fork 0
/
imports.go
376 lines (317 loc) · 8.29 KB
/
imports.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
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
// Package importers helps with dynamic imports for templating
package importers
import (
"bytes"
"fmt"
"sort"
"strings"
"github.com/spf13/cast"
"github.com/friendsofgo/errors"
"github.com/volatiletech/sqlboiler/strmangle"
)
// Collection of imports for various templating purposes
// Drivers add to any and all of these, and is completely responsible
// for populating BasedOnType.
type Collection struct {
All Set `toml:"all" json:"all,omitempty"`
Test Set `toml:"test" json:"test,omitempty"`
Singleton Map `toml:"singleton" json:"singleton,omitempty"`
TestSingleton Map `toml:"test_singleton" json:"test_singleton,omitempty"`
BasedOnType Map `toml:"based_on_type" json:"based_on_type,omitempty"`
}
// Set defines the optional standard imports and
// thirdParty imports (from github for example)
type Set struct {
Standard List `toml:"standard"`
ThirdParty List `toml:"third_party"`
}
// Format the set into Go syntax (compatible with go imports)
func (s Set) Format() []byte {
stdlen, thirdlen := len(s.Standard), len(s.ThirdParty)
if stdlen+thirdlen < 1 {
return []byte{}
}
if stdlen+thirdlen == 1 {
var imp string
if stdlen == 1 {
imp = s.Standard[0]
} else {
imp = s.ThirdParty[0]
}
return []byte(fmt.Sprintf("import %s", imp))
}
buf := &bytes.Buffer{}
buf.WriteString("import (")
for _, std := range s.Standard {
fmt.Fprintf(buf, "\n\t%s", std)
}
if stdlen != 0 && thirdlen != 0 {
buf.WriteString("\n")
}
for _, third := range s.ThirdParty {
fmt.Fprintf(buf, "\n\t%s", third)
}
buf.WriteString("\n)\n")
return buf.Bytes()
}
// SetFromInterface creates a set from a theoretical map[string]interface{}.
// This is to load from a loosely defined configuration file.
func SetFromInterface(intf interface{}) (Set, error) {
s := Set{}
setIntf, ok := intf.(map[string]interface{})
if !ok {
return s, errors.New("import set should be map[string]interface{}")
}
standardIntf, ok := setIntf["standard"]
if ok {
standardsIntf, ok := standardIntf.([]interface{})
if !ok {
return s, errors.New("import set standards must be an slice")
}
s.Standard = List{}
for i, intf := range standardsIntf {
str, ok := intf.(string)
if !ok {
return s, errors.Errorf("import set standard slice element %d (%+v) must be string", i, s)
}
s.Standard = append(s.Standard, str)
}
}
thirdPartyIntf, ok := setIntf["third_party"]
if ok {
thirdPartysIntf, ok := thirdPartyIntf.([]interface{})
if !ok {
return s, errors.New("import set third_party must be an slice")
}
s.ThirdParty = List{}
for i, intf := range thirdPartysIntf {
str, ok := intf.(string)
if !ok {
return s, errors.Errorf("import set third party slice element %d (%+v) must be string", i, intf)
}
s.ThirdParty = append(s.ThirdParty, str)
}
}
return s, nil
}
// Map of file/type -> imports
// Map's consumers do not understand windows paths. Always specify paths
// using forward slash (/).
type Map map[string]Set
// MapFromInterface creates a Map from a theoretical map[string]interface{}
// or []map[string]interface{}
// This is to load from a loosely defined configuration file.
func MapFromInterface(intf interface{}) (Map, error) {
m := Map{}
iter := func(i interface{}, fn func(string, interface{}) error) error {
switch toIter := intf.(type) {
case []interface{}:
for _, intf := range toIter {
obj := cast.ToStringMap(intf)
name := obj["name"].(string)
if err := fn(name, intf); err != nil {
return err
}
}
case map[string]interface{}:
for k, v := range toIter {
if err := fn(k, v); err != nil {
return err
}
}
default:
panic("import map should be map[string]interface or []map[string]interface{}")
}
return nil
}
err := iter(intf, func(name string, value interface{}) error {
s, err := SetFromInterface(value)
if err != nil {
return err
}
m[name] = s
return nil
})
if err != nil {
return nil, err
}
return m, nil
}
// List of imports
type List []string
// Len implements sort.Interface.Len
func (l List) Len() int {
return len(l)
}
// Swap implements sort.Interface.Swap
func (l List) Swap(i, j int) {
l[i], l[j] = l[j], l[i]
}
// Less implements sort.Interface.Less
func (l List) Less(i, j int) bool {
res := strings.Compare(strings.TrimLeft(l[i], "_ "), strings.TrimLeft(l[j], "_ "))
if res <= 0 {
return true
}
return false
}
// NewDefaultImports returns a default Imports struct.
func NewDefaultImports() Collection {
var col Collection
col.All = Set{
Standard: List{
`"database/sql"`,
`"fmt"`,
`"reflect"`,
`"strings"`,
`"sync"`,
`"time"`,
},
ThirdParty: List{
`"github.com/friendsofgo/errors"`,
`"github.com/volatiletech/sqlboiler/boil"`,
`"github.com/volatiletech/sqlboiler/queries"`,
`"github.com/volatiletech/sqlboiler/queries/qm"`,
`"github.com/volatiletech/sqlboiler/queries/qmhelper"`,
`"github.com/volatiletech/sqlboiler/strmangle"`,
},
}
col.Singleton = Map{
"boil_queries": {
ThirdParty: List{
`"github.com/volatiletech/sqlboiler/drivers"`,
`"github.com/volatiletech/sqlboiler/queries"`,
`"github.com/volatiletech/sqlboiler/queries/qm"`,
},
},
"boil_types": {
Standard: List{
`"strconv"`,
},
ThirdParty: List{
`"github.com/friendsofgo/errors"`,
`"github.com/volatiletech/sqlboiler/boil"`,
`"github.com/volatiletech/sqlboiler/strmangle"`,
},
},
}
col.Test = Set{
Standard: List{
`"bytes"`,
`"reflect"`,
`"testing"`,
},
ThirdParty: List{
`"github.com/volatiletech/sqlboiler/boil"`,
`"github.com/volatiletech/sqlboiler/queries"`,
`"github.com/volatiletech/sqlboiler/randomize"`,
`"github.com/volatiletech/sqlboiler/strmangle"`,
},
}
col.TestSingleton = Map{
"boil_main_test": {
Standard: List{
`"database/sql"`,
`"flag"`,
`"fmt"`,
`"math/rand"`,
`"os"`,
`"path/filepath"`,
`"strings"`,
`"testing"`,
`"time"`,
},
ThirdParty: List{
`"github.com/spf13/viper"`,
`"github.com/volatiletech/sqlboiler/boil"`,
},
},
"boil_queries_test": {
Standard: List{
`"bytes"`,
`"fmt"`,
`"io"`,
`"io/ioutil"`,
`"math/rand"`,
`"regexp"`,
},
ThirdParty: List{
`"github.com/volatiletech/sqlboiler/boil"`,
},
},
"boil_suites_test": {
Standard: List{
`"testing"`,
},
},
}
return col
}
// AddTypeImports takes a set of imports 'a', a type -> import mapping 'typeMap'
// and a set of column types that are currently in use and produces a new set
// including both the old standard/third party, as well as the imports required
// for the types in use.
func AddTypeImports(a Set, typeMap map[string]Set, columnTypes []string) Set {
tmpImp := Set{
Standard: make(List, len(a.Standard)),
ThirdParty: make(List, len(a.ThirdParty)),
}
copy(tmpImp.Standard, a.Standard)
copy(tmpImp.ThirdParty, a.ThirdParty)
for _, typ := range columnTypes {
for key, imp := range typeMap {
if typ == key {
tmpImp.Standard = append(tmpImp.Standard, imp.Standard...)
tmpImp.ThirdParty = append(tmpImp.ThirdParty, imp.ThirdParty...)
}
}
}
tmpImp.Standard = strmangle.RemoveDuplicates(tmpImp.Standard)
tmpImp.ThirdParty = strmangle.RemoveDuplicates(tmpImp.ThirdParty)
sort.Sort(tmpImp.Standard)
sort.Sort(tmpImp.ThirdParty)
return tmpImp
}
// Merge takes two collections and creates a new one
// with the de-duplication contents of both.
func Merge(a, b Collection) Collection {
var c Collection
c.All = mergeSet(a.All, b.All)
c.Test = mergeSet(a.Test, b.Test)
c.Singleton = mergeMap(a.Singleton, b.Singleton)
c.TestSingleton = mergeMap(a.TestSingleton, b.TestSingleton)
c.BasedOnType = mergeMap(a.BasedOnType, b.BasedOnType)
return c
}
func mergeSet(a, b Set) Set {
var c Set
c.Standard = strmangle.RemoveDuplicates(combineStringSlices(a.Standard, b.Standard))
c.ThirdParty = strmangle.RemoveDuplicates(combineStringSlices(a.ThirdParty, b.ThirdParty))
sort.Sort(c.Standard)
sort.Sort(c.ThirdParty)
return c
}
func mergeMap(a, b Map) Map {
m := make(Map)
for k, v := range a {
m[k] = v
}
for k, toMerge := range b {
exist, ok := m[k]
if !ok {
m[k] = toMerge
}
m[k] = mergeSet(exist, toMerge)
}
return m
}
func combineStringSlices(a, b []string) []string {
c := make([]string, len(a)+len(b))
if len(a) > 0 {
copy(c, a)
}
if len(b) > 0 {
copy(c[len(a):], b)
}
return c
}