forked from xo/usql
-
Notifications
You must be signed in to change notification settings - Fork 0
/
gen.go
477 lines (438 loc) · 12.8 KB
/
gen.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
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
//go:build tools
package main
import (
"bytes"
"errors"
"flag"
"fmt"
"go/format"
"go/parser"
"go/token"
"io/fs"
"io/ioutil"
"os"
"path/filepath"
"regexp"
"sort"
"strings"
"time"
"github.com/mattn/go-runewidth"
"github.com/xo/dburl"
)
type DriverInfo struct {
// Tag is the build Tag / name of the directory the driver lives in.
Tag string
// Driver is the Go SQL Driver Driver (parsed from the import tagged with //
// DRIVER: <Driver>), otherwise same as the tag / directory Driver.
Driver string
// Pkg is the imported driver package, taken from the import tagged with
// DRIVER.
Pkg string
// Desc is the descriptive text of the driver, parsed from doc comment, ie,
// "Package <tag> defines and registers usql's <Desc>."
Desc string
// URL is the driver's reference URL, parsed from doc comment's "See: <URL>".
URL string
// CGO is whether or not the driver requires CGO, based on presence of
// 'Requires CGO.' in the comment
CGO bool
// Aliases are the parsed Alias: entries.
Aliases [][]string
// Wire indicates it is a Wire compatible driver.
Wire bool
// Group is the build Group
Group string
}
// baseDrivers are drivers included in a build with no build tags listed.
var baseDrivers = map[string]DriverInfo{}
// mostDrivers are drivers included with the most tag. Populated below.
var mostDrivers = map[string]DriverInfo{}
// allDrivers are drivers forced to 'all' build tag.
var allDrivers = map[string]DriverInfo{}
// wireDrivers are the wire compatible drivers.
var wireDrivers = map[string]DriverInfo{}
func main() {
licenseStart := flag.Int("license-start", 2016, "license start year")
licenseAuthor := flag.String("license-author", "Kenneth Shaw", "license author")
flag.Parse()
if err := run(*licenseStart, *licenseAuthor); err != nil {
fmt.Fprintf(os.Stderr, "error: %v\n", err)
os.Exit(1)
}
}
func run(licenseStart int, licenseAuthor string) error {
wd, err := os.Getwd()
if err != nil {
return err
}
if err := loadDrivers(filepath.Join(wd, "drivers")); err != nil {
return err
}
if err := writeInternal(filepath.Join(wd, "internal"), baseDrivers, mostDrivers, allDrivers); err != nil {
return err
}
if err := writeReadme(wd); err != nil {
return err
}
if err := writeLicenseFiles(licenseStart, licenseAuthor); err != nil {
return err
}
return nil
}
var dirRE = regexp.MustCompile(`^([^/]+)/([^\./]+)\.go$`)
// loadDrivers loads the driver descriptions.
func loadDrivers(wd string) error {
skipDirs := []string{"completer", "metadata"}
err := fs.WalkDir(os.DirFS(wd), ".", func(n string, d fs.DirEntry, err error) error {
switch {
case err != nil:
return err
case d.IsDir():
return nil
}
m := dirRE.FindAllStringSubmatch(n, -1)
if m == nil || m[0][1] != m[0][2] || contains(skipDirs, m[0][1]) {
return nil
}
tag, dest := m[0][1], mostDrivers
driver, err := parseDriverInfo(tag, filepath.Join(wd, n))
switch {
case err != nil:
return err
case driver.Group == "base":
dest = baseDrivers
case driver.Group == "most":
case driver.Group == "all":
dest = allDrivers
default:
return fmt.Errorf("driver %s has invalid group %q", tag, driver.Group)
}
dest[tag] = driver
if dest[tag].Aliases != nil {
for _, alias := range dest[tag].Aliases {
wireDrivers[alias[0]] = DriverInfo{
Tag: tag,
Driver: alias[0],
Pkg: dest[tag].Pkg,
Desc: alias[1],
Wire: true,
}
}
}
return nil
})
if err != nil {
return err
}
return nil
}
func parseDriverInfo(tag, filename string) (DriverInfo, error) {
f, err := parser.ParseFile(token.NewFileSet(), filename, nil, parser.ParseComments)
if err != nil {
return DriverInfo{}, err
}
name := tag
var pkg string
for _, imp := range f.Imports {
if imp.Comment == nil || len(imp.Comment.List) == 0 || !strings.Contains(imp.Comment.List[0].Text, "DRIVER") {
continue
}
pkg = imp.Path.Value[1 : len(imp.Path.Value)-1]
if i := strings.Index(imp.Comment.List[0].Text, ":"); i != -1 {
name = strings.TrimSpace(imp.Comment.List[0].Text[i+1:])
}
break
}
// parse doc comment
comment := f.Doc.Text()
prefix := "Package " + tag + " defines and registers usql's "
if !strings.HasPrefix(comment, prefix) {
return DriverInfo{}, fmt.Errorf("invalid doc comment prefix for driver %q", tag)
}
desc := strings.TrimPrefix(comment, prefix)
i := strings.Index(desc, " driver.")
if i == -1 {
return DriverInfo{}, fmt.Errorf("cannot find description suffix for driver %q", tag)
}
desc = strings.TrimSpace(desc[:i])
if desc == "" {
return DriverInfo{}, fmt.Errorf("unable to parse description for driver %q", tag)
}
// parse alias:
var aliases [][]string
aliasesm := aliasRE.FindAllStringSubmatch(comment, -1)
for _, m := range aliasesm {
s := strings.Split(m[1], ",")
aliases = append(aliases, []string{
strings.TrimSpace(s[0]),
strings.TrimSpace(s[1]),
})
}
// parse see: url
urlm := seeRE.FindAllStringSubmatch(comment, -1)
if urlm == nil {
return DriverInfo{}, fmt.Errorf("missing See: <URL> for driver %q", tag)
}
// parse group:
group := "most"
if groupm := groupRE.FindAllStringSubmatch(comment, -1); groupm != nil {
group = strings.TrimSpace(groupm[0][1])
}
return DriverInfo{
Tag: tag,
Driver: name,
Pkg: pkg,
Desc: cleanRE.ReplaceAllString(desc, ""),
URL: strings.TrimSpace(urlm[0][1]),
CGO: strings.Contains(cleanRE.ReplaceAllString(comment, ""), "Requires CGO."),
Aliases: aliases,
Group: group,
}, nil
}
var (
aliasRE = regexp.MustCompile(`(?m)^Alias:\s+(.*)$`)
seeRE = regexp.MustCompile(`(?m)^See:\s+(.*)$`)
groupRE = regexp.MustCompile(`(?m)^Group:\s+(.*)$`)
cleanRE = regexp.MustCompile(`[\r\n]`)
)
func writeInternal(wd string, drivers ...map[string]DriverInfo) error {
// build known build tags
var known []DriverInfo
for _, m := range drivers {
for _, v := range m {
known = append(known, v)
}
}
sort.Slice(known, func(i, j int) bool {
return known[i].Tag < known[j].Tag
})
knownStr := ""
for _, v := range known {
knownStr += fmt.Sprintf("\n%q: %q, // %s", v.Tag, v.Driver, v.Pkg)
}
// format and write internal.go
buf, err := format.Source([]byte(fmt.Sprintf(internalGo, knownStr)))
if err != nil {
return err
}
if err := ioutil.WriteFile(filepath.Join(wd, "internal.go"), buf, 0644); err != nil {
return err
}
// write <tag>.go
for _, v := range known {
var tags string
switch v.Group {
case "base":
tags = "(!no_base || " + v.Tag + ")"
case "most":
tags = "(all || most || " + v.Tag + ")"
case "all":
tags = "(all || " + v.Tag + ")"
default:
panic(v.Tag)
}
tags += " && !no_" + v.Tag
buf, err := format.Source([]byte(fmt.Sprintf(internalTagGo, tags, "github.com/xo/usql/drivers/"+v.Tag, v.Desc)))
if err != nil {
return err
}
if err := ioutil.WriteFile(filepath.Join(wd, v.Tag+".go"), buf, 0644); err != nil {
return err
}
}
return nil
}
const internalTagGo = `//go:build %s
package internal
// Code generated by gen.go. DO NOT EDIT.
import (
_ %q // %s driver
)`
const internalGo = `// Package internal provides a way to obtain information about which database
// drivers were included at build.
package internal
// Code generated by gen.go. DO NOT EDIT.
// KnownBuildTags returns a map of known driver names to its respective build
// tags.
func KnownBuildTags() map[string]string{
return map[string]string{%s
}
}`
const (
driverTableStart = "<!-- DRIVER DETAILS START -->"
driverTableEnd = "<!-- DRIVER DETAILS END -->"
)
func writeReadme(wd string) error {
readme := filepath.Join(wd, "README.md")
buf, err := ioutil.ReadFile(readme)
if err != nil {
return err
}
start := bytes.Index(buf, []byte(driverTableStart))
end := bytes.Index(buf, []byte(driverTableEnd))
if start == -1 || end == -1 {
return errors.New("unable to find driver table start/end in README.md")
}
b := new(bytes.Buffer)
if _, err := b.Write(append(buf[:start+len(driverTableStart)], '\n')); err != nil {
return err
}
if _, err := b.Write([]byte(buildDriverTable())); err != nil {
return err
}
if _, err := b.Write(buf[end:]); err != nil {
return err
}
return ioutil.WriteFile(readme, b.Bytes(), 0644)
}
func buildDriverTable() string {
hdr := []string{"Database", "Scheme / Tag", "Scheme Aliases", "Driver Package / Notes"}
widths := []int{len(hdr[0]), len(hdr[1]), len(hdr[2]), len(hdr[3])}
baseRows, widths := buildRows(baseDrivers, widths)
mostRows, widths := buildRows(mostDrivers, widths)
allRows, widths := buildRows(allDrivers, widths)
wireRows, widths := buildRows(wireDrivers, widths)
s := tableRows(widths, ' ', hdr)
s += tableRows(widths, '-')
s += tableRows(widths, ' ', baseRows...)
s += tableRows(widths, ' ')
s += tableRows(widths, ' ', mostRows...)
s += tableRows(widths, ' ')
s += tableRows(widths, ' ', allRows...)
s += tableRows(widths, ' ')
s += tableRows(widths, ' ', wireRows...)
s += tableRows(widths, ' ')
s += tableRows(widths, ' ',
[]string{"**NO DRIVERS**", "`no_base`", "", "_no base drivers (useful for development)_"},
[]string{"**MOST DRIVERS**", "`most`", "", "_all stable drivers_"},
[]string{"**ALL DRIVERS**", "`all`", "", "_all drivers_"},
[]string{"**NO <TAG>**", "`no_<tag>`", "", "_exclude driver with `<tag>`_"},
)
return s + "\n" + buildTableLinks(baseDrivers, mostDrivers, allDrivers)
}
func buildRows(m map[string]DriverInfo, widths []int) ([][]string, []int) {
var drivers []DriverInfo
for _, v := range m {
drivers = append(drivers, v)
}
sort.Slice(drivers, func(i, j int) bool {
return strings.ToLower(drivers[i].Desc) < strings.ToLower(drivers[j].Desc)
})
var rows [][]string
for i, v := range drivers {
notes := ""
if v.CGO {
notes = "<sup>[†][f-cgo]</sup>"
}
if v.Wire {
notes = "<sup>[‡][f-wire]</sup>"
}
rows = append(rows, []string{
v.Desc,
"`" + v.Tag + "`",
buildAliases(v),
fmt.Sprintf("[%s][d-%s]%s", v.Pkg, v.Tag, notes),
})
// calc max
for j := 0; j < len(rows[i]); j++ {
widths[j] = max(runewidth.StringWidth(rows[i][j]), widths[j])
}
}
return rows, widths
}
func buildAliases(v DriverInfo) string {
name := v.Tag
if v.Wire {
name = v.Driver
}
_, aliases := dburl.SchemeDriverAndAliases(name)
if v.Wire {
aliases = append(aliases, name)
}
for i := 0; i < len(aliases); i++ {
if !v.Wire && aliases[i] == v.Tag {
aliases[i] = v.Driver
}
}
if len(aliases) > 0 {
return "`" + strings.Join(aliases, "`, `") + "`"
}
return ""
}
func tableRows(widths []int, c rune, rows ...[]string) string {
padding := string(c)
if len(rows) == 0 {
rows = [][]string{make([]string, len(widths))}
}
var s string
for _, row := range rows {
for i := 0; i < len(row); i++ {
s += "|" + padding + row[i] + strings.Repeat(padding, widths[i]-runewidth.StringWidth(row[i])) + padding
}
s += "|\n"
}
return s
}
func buildTableLinks(drivers ...map[string]DriverInfo) string {
var d []DriverInfo
for _, m := range drivers {
for _, v := range m {
d = append(d, v)
}
}
sort.Slice(d, func(i, j int) bool {
return d[i].Tag < d[j].Tag
})
var s string
for _, v := range d {
s += fmt.Sprintf("[d-%s]: %s\n", v.Tag, v.URL)
}
return s
}
func writeLicenseFiles(licenseStart int, licenseAuthor string) error {
s := fmt.Sprintf(license, licenseStart, time.Now().Year(), licenseAuthor)
if err := ioutil.WriteFile("LICENSE", append([]byte(s), '\n'), 0644); err != nil {
return err
}
textGo := fmt.Sprintf(licenseTextGo, s)
if err := ioutil.WriteFile("text/license.go", []byte(textGo), 0644); err != nil {
return err
}
return nil
}
const license = `The MIT License (MIT)
Copyright (c) %d-%d %s
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.`
const licenseTextGo = `package text
// Code generated by gen.go. DO NOT EDIT.
// License contains the license text for usql.
const License = ` + "`%s`" + `
`
func contains(v []string, n string) bool {
for _, s := range v {
if s == n {
return true
}
}
return false
}
func max(a, b int) int {
if a > b {
return a
}
return b
}