Repository navigation
Expand file tree
/
Copy pathcodegen.go
More file actions
1012 lines (817 loc) · 27.7 KB
/
Copy pathcodegen.go
File metadata and controls
1012 lines (817 loc) · 27.7 KB
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
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package vukem
import (
"bufio"
"bytes"
"context"
"errors"
"flag"
"fmt"
"go/format"
"go/token"
"io"
"maps"
"os"
"path/filepath"
"reflect"
"regexp"
"slices"
"strconv"
"strings"
"unicode"
"unicode/utf8"
"github.com/AlexGalhardo/vukem/inertia"
"github.com/AlexGalhardo/vukem/openapi"
"github.com/AlexGalhardo/vukem/orm"
"github.com/AlexGalhardo/vukem/router"
)
const defaultRoutesTS = "resources/js/routes.ts"
func codegenRoutesCommand() Command {
var (
out *string
check *bool
)
return CommandFunc{
CommandName: "codegen:routes",
Desc: "Generate typed frontend routes (resources/js/routes.ts; -o - prints to stdout; -check fails if stale)",
DefineFlags: func(fs *flag.FlagSet) {
out = fs.String("o", defaultRoutesTS, `write to this file ("-" for stdout)`)
check = fs.Bool("check", false, "write nothing; fail if the file is not up to date")
},
Fn: func(_ context.Context, app *App, _ []string) error {
if _, err := app.Router.Handler(); err != nil {
return err
}
ts := routesTypeScript(app.Router.Routes())
if *check && *out == "-" {
return errors.New("codegen:routes: -check needs a file, not -o -")
}
if *out == "-" {
_, err := io.WriteString(app.stdout, ts)
return err
}
return writeGenerated("codegen:routes", *out, []byte(ts), *check)
},
}
}
type tsRoute struct {
name, method, path, host string
params []string
}
// routesTypeScript renders the named routes as a typed TypeScript module.
func routesTypeScript(infos []router.RouteInfo) string {
var named []tsRoute
for _, ri := range infos {
if ri.Name == "" {
continue
}
path := strings.ReplaceAll(ri.Path, "{$}", "")
if path == "" {
path = "/"
}
named = append(
named,
tsRoute{name: ri.Name, method: ri.Method, path: path, host: ri.Host, params: pathParams(path)},
)
}
slices.SortFunc(named, func(a, b tsRoute) int { return strings.Compare(a.name, b.name) })
var b strings.Builder
b.WriteString("// Code generated by vukem codegen:routes. DO NOT EDIT.\n\n")
b.WriteString("export const routes = {\n")
for _, r := range named {
fields := []string{"method: " + strconv.Quote(r.method), "path: " + strconv.Quote(r.path)}
if r.host != "" {
fields = append(fields, "host: "+strconv.Quote(r.host))
}
b.WriteString(tsObjectMember(tsPropKey(r.name), fields, ",", biomeLineWidth))
}
b.WriteString("} as const;\n\n")
b.WriteString("export type RouteName = keyof typeof routes;\n\n")
b.WriteString("export type RouteParam = string | number;\n\n")
b.WriteString("export type RouteQuery = Record<string, string | number | boolean | null | undefined>;\n\n")
b.WriteString("export interface RouteParams {\n")
for _, r := range named {
b.WriteString(tsObjectMember(tsPropKey(r.name), paramFields(r.params), ";", biomeLineWidth))
}
b.WriteString("}\n")
b.WriteString(routeFuncTS)
return b.String()
}
func paramFields(params []string) []string {
fields := make([]string, len(params))
for i, p := range params {
fields[i] = tsPropKey(p) + ": RouteParam"
}
return fields
}
// tsObjectMember writes " key: { a, b };" on one line, or one field per line
// when that is wider than width, as Biome does. end closes the member: ";" in
// a type (fields are then separated by ";") or "," in a value. Without fields
// the member is Record<string, never>.
func tsObjectMember(key string, fields []string, end string, width int) string {
if len(fields) == 0 {
return " " + key + ": Record<string, never>" + end + "\n"
}
one := " " + key + ": { " + strings.Join(fields, end+" ") + " }" + end
if len([]rune(one)) <= width {
return one + "\n"
}
var b strings.Builder
b.WriteString(" " + key + ": {\n")
for _, f := range fields {
b.WriteString(" " + f + end + "\n")
}
b.WriteString(" }" + end + "\n")
return b.String()
}
// pathParams returns the wildcard names of a ServeMux pattern path.
func pathParams(path string) []string {
var names []string
for rest := path; ; {
start := strings.IndexByte(rest, '{')
if start < 0 {
return names
}
end := strings.IndexByte(rest[start:], '}')
if end < 0 {
return names
}
names = append(names, strings.TrimSuffix(rest[start+1:start+end], "..."))
rest = rest[start+end+1:]
}
}
// routeFuncTS mirrors router.URL: "{name...}" keeps "/" and encodes each
// segment. It sticks to ES5 library calls so it type-checks under any lib.
const routeFuncTS = `
type RouteArgs<N extends RouteName> =
RouteParams[N] extends Record<string, never>
? [params?: RouteParams[N], query?: RouteQuery]
: [params: RouteParams[N], query?: RouteQuery];
/** route builds the URL of a named route, e.g. route("posts.show", { id: 7 }). */
export function route<N extends RouteName>(name: N, ...args: RouteArgs<N>): string {
const params = (args[0] ?? {}) as Record<string, RouteParam | undefined>;
const query = args[1];
const spec = routes[name] as { path: string; host?: string };
let url = spec.path.replace(/\{([^}]+)\}/g, (_match: string, wild: string): string => {
const multi = wild.slice(-3) === "...";
const key = multi ? wild.slice(0, -3) : wild;
const value = params[key];
if (value === undefined) {
throw new Error("route(" + name + "): missing param " + key);
}
const raw = String(value);
return multi ? raw.split("/").map(encodeURIComponent).join("/") : encodeURIComponent(raw);
});
if (spec.host) {
url = "//" + spec.host + url;
}
if (query) {
const parts: string[] = [];
for (const key of Object.keys(query)) {
const value = query[key];
if (value !== undefined && value !== null) {
parts.push(encodeURIComponent(key) + "=" + encodeURIComponent(String(value)));
}
}
if (parts.length > 0) {
url += "?" + parts.join("&");
}
}
return url;
}
`
const defaultPagesTS = "resources/js/page-props.ts"
func codegenPagesCommand() Command {
var (
out *string
check *bool
)
return CommandFunc{
CommandName: "codegen:pages",
Desc: "Generate TypeScript props for the typed Inertia pages " +
"(resources/js/page-props.ts; -o - prints to stdout; -check fails if stale)",
DefineFlags: func(fs *flag.FlagSet) {
out = fs.String("o", defaultPagesTS, `write to this file ("-" for stdout)`)
check = fs.Bool("check", false, "write nothing; fail if the file is not up to date")
},
Fn: func(_ context.Context, app *App, _ []string) error {
if *check && *out == "-" {
return errors.New("codegen:pages: -check needs a file, not -o -")
}
ts, err := pagePropsTypeScript(app)
if err != nil {
return fmt.Errorf("codegen:pages: %w", err)
}
if *out == "-" {
_, err := io.WriteString(app.stdout, ts)
return err
}
return writeGenerated("codegen:pages", *out, []byte(ts), *check)
},
}
}
// pagePropsTypeScript renders resources/js/page-props.ts from the typed pages
// of inertia.Config.Pages and its SharedType.
func pagePropsTypeScript(app *App) (string, error) {
if app.Inertia == nil || len(app.Inertia.Pages()) == 0 {
return "", errors.New("no typed pages: list them in inertia.Config.Pages")
}
roots := map[string]reflect.Type{}
byName := map[string]string{} // TypeScript name -> component
for _, p := range app.Inertia.Pages() {
name := pascalCase(p.Component) + "Props"
if pascalCase(p.Component) == "" || !tsIdentRe.MatchString(name) {
return "", fmt.Errorf("component %q gives %q, which is not a TypeScript name: start it with a letter",
p.Component, name)
}
if name == "SharedProps" {
return "", fmt.Errorf(
"component %q gives the name SharedProps, which the file declares itself",
p.Component,
)
}
if other, dup := byName[name]; dup {
return "", fmt.Errorf("components %q and %q both give the TypeScript name %s", other, p.Component, name)
}
byName[name] = p.Component
shape, err := p.Shape()
if err != nil {
return "", err
}
roots[name] = shape
}
var shared string
if st := app.Inertia.SharedType(); st != nil {
shape, err := inertia.SharedShape(st)
if err != nil {
return "", err
}
roots["SharedProps"] = shape
} else {
shared = "export type SharedProps = {\n errors: Record<string, string>;\n [key: string]: unknown;\n};\n\n"
}
types, err := openapi.TypeScriptTypes(roots)
if err != nil {
return "", err
}
// With X-Inertia-Error-Bag the client nests the messages under the bag name.
const flatErrors = "errors: Record<string, string>;"
bagErrors := "errors: Record<string, string | Record<string, string>>;"
types = strings.Replace(types, flatErrors, bagErrors, 1)
shared = strings.Replace(shared, flatErrors, bagErrors, 1)
var b strings.Builder
b.WriteString("// Code generated by vukem codegen:pages. DO NOT EDIT.\n\n")
b.WriteString(types)
b.WriteString("\n")
b.WriteString(shared)
b.WriteString("/** PageProps maps every typed page component to its props. */\nexport interface PageProps {\n")
for _, name := range slices.Sorted(maps.Keys(byName)) {
fmt.Fprintf(&b, " %s: %s;\n", tsPropKey(byName[name]), name)
}
b.WriteString("}\n\nexport type PageName = keyof PageProps;\n\n")
b.WriteString("/** Page is the props a page component receives: its own plus the shared ones. */\n")
b.WriteString("export type Page<N extends PageName> = PageProps[N] & SharedProps;\n")
if dups := duplicateDeclarations(b.String()); len(dups) > 0 {
return "", fmt.Errorf("the file would declare %s more than once: rename the Go type or the component",
strings.Join(dups, ", "))
}
return wrapLongUnions(b.String(), biomeLineWidth), nil
}
// biomeLineWidth is the default line width of the Biome config that vukem
// new writes (biome.json).
const biomeLineWidth = 120
var tsPlainKeyRe = regexp.MustCompile(`^[A-Za-z_$][A-Za-z0-9_$]*$`)
// tsPropKey quotes a property name only when it is not a plain identifier,
// as Biome's default "asNeeded" quoteProperties does.
func tsPropKey(k string) string {
if tsPlainKeyRe.MatchString(k) {
return k
}
return strconv.Quote(k)
}
var (
tsIdentRe = regexp.MustCompile(`^[A-Za-z][A-Za-z0-9]*$`)
tsDeclRe = regexp.MustCompile(`(?m)^export (?:type|interface) ([A-Za-z_$][A-Za-z0-9_$]*)`)
)
// duplicateDeclarations lists the type names src declares more than once.
func duplicateDeclarations(src string) []string {
seen := map[string]bool{}
var dups []string
for _, m := range tsDeclRe.FindAllStringSubmatch(src, -1) {
if seen[m[1]] && !slices.Contains(dups, m[1]) {
dups = append(dups, m[1])
}
seen[m[1]] = true
}
return dups
}
// pascalCase turns "Projects/Index" into "ProjectsIndex".
func pascalCase(s string) string {
var b strings.Builder
upper := true
for _, r := range s {
if !unicode.IsLetter(r) && !unicode.IsDigit(r) {
upper = true
continue
}
if upper {
r = unicode.ToUpper(r)
upper = false
}
b.WriteRune(r)
}
return b.String()
}
const (
defaultClientTS = "resources/js/api.ts"
defaultClientGo = "internal/apiclient/client.go"
)
// openAPIPrefixUsage documents the -prefix flag of every command that builds
// the OpenAPI document, so they stay worded alike.
const openAPIPrefixUsage = `keep only routes under this path prefix, e.g. "/api" (default OPENAPI_PREFIX)`
// openAPIPrefixFlag defines the shared -prefix flag on fs, writing into p. It
// binds an existing variable rather than returning a pointer so the zero value
// ("fall back to OPENAPI_PREFIX") also holds for a Command whose Run is called
// without Flags, instead of dereferencing a nil pointer.
func openAPIPrefixFlag(fs *flag.FlagSet, p *string) {
fs.StringVar(p, "prefix", "", openAPIPrefixUsage)
}
// openAPIDocument builds the app's OpenAPI document scoped to prefix. An
// explicit prefix overrides Config.OpenAPIPrefix (OPENAPI_PREFIX) and an empty
// one falls back to it, the precedence [OpenAPIOptions.PathPrefix] already has:
// one rule for the flag, the option and the environment variable.
func openAPIDocument(app *App, prefix string) (*openapi.Document, error) {
if prefix == "" {
return app.OpenAPI()
}
return app.openAPI(prefix)
}
func codegenClientCommand() Command {
var (
prefix string
lang, out, pkg *string
style *string
tanstack *bool
check *bool
)
return CommandFunc{
CommandName: "codegen:client",
Desc: "Generate a typed API client from the OpenAPI document " +
"(-lang ts|go; -style result|throw; -tanstack; -check; -o - prints to stdout)",
DefineFlags: func(fs *flag.FlagSet) {
style = fs.String("style", string(openapi.StyleResult),
"ts client style: result ({ data, error, status }) or throw (throws ApiError)")
tanstack = fs.Bool(
"tanstack",
false,
"ts: add createQueries, option objects for TanStack Query (style result)",
)
check = fs.Bool("check", false, "write nothing; fail if the file is not up to date")
lang = fs.String("lang", "ts", "client language: ts or go")
out = fs.String("o", "", `write to this file ("-" for stdout; default `+
defaultClientTS+" or "+defaultClientGo+")")
pkg = fs.String("package", "apiclient", "Go package name (-lang go)")
openAPIPrefixFlag(fs, &prefix)
},
Fn: func(_ context.Context, app *App, _ []string) error {
if *lang != "ts" && (*style != string(openapi.StyleResult) || *tanstack) {
return errors.New("codegen:client: -style applies to -lang ts only")
}
if *check && *out == "-" {
return errors.New("codegen:client: -check needs a file, not -o -")
}
doc, err := openAPIDocument(app, prefix)
if err != nil {
return err
}
var (
src []byte
target string
)
switch *lang {
case "ts":
ts, err := openapi.TypeScriptClientWith(doc, openapi.ClientOptions{
Style: openapi.ClientStyle(*style),
TanStack: *tanstack,
Args: clientArgs(*style, *tanstack, prefix),
})
if err != nil {
return err
}
src, target = []byte(ts), defaultClientTS
case "go":
if src, err = openapi.GoClient(doc, *pkg); err != nil {
return err
}
target = defaultClientGo
default:
return fmt.Errorf("codegen:client: unknown -lang %q (want ts or go)", *lang)
}
if *out == "-" {
_, err := app.stdout.Write(src)
return err
}
if *out != "" {
target = *out
}
return writeGenerated("codegen:client", target, src, *check)
},
}
}
// clientArgs is the text of the flags that differ from the defaults, in a fixed
// order, as the header of a generated ts client records them. -package is not
// recorded: it only applies to -lang go.
func clientArgs(style string, tanstack bool, prefix string) string {
var args []string
if style != string(openapi.StyleResult) {
args = append(args, "-style", style)
}
if tanstack {
args = append(args, "-tanstack")
}
if prefix != "" {
args = append(args, "-prefix", prefix)
}
return strings.Join(args, " ")
}
// writeGenerated writes a generated file, creating its directory, and only
// when the bytes differ, so a watcher does not see a change that is not one.
// With check it writes nothing and fails when the file is stale.
func writeGenerated(cmd, target string, src []byte, check bool) error {
path := filepath.FromSlash(target)
if cur, err := os.ReadFile(
path,
); err == nil &&
bytes.Equal(cur, src) {
return nil
}
if check {
return fmt.Errorf("%s: %s is stale: run \"vukem %s\"", cmd, target, cmd)
}
if err := os.MkdirAll(filepath.Dir(path), 0o750); err != nil {
return fmt.Errorf("%s: %w", cmd, err)
}
if err := os.WriteFile(path, src, 0o600); err != nil { //nolint:gosec,nolintlint // G703 (2.15+): own -o path
return fmt.Errorf("%s: %w", cmd, err)
}
return nil
}
// codegenTarget is a file the "codegen" command keeps up to date.
type codegenTarget struct {
path string
command func() Command
args []string // always passed, before the ones the file header records
// models marks the target that needs vukem.WithModels: an app without it
// does not use the file, so it is skipped. The header does not record
// -pkg; the package line of the file does.
models bool
}
var codegenTargets = []codegenTarget{
{path: defaultRoutesTS, command: codegenRoutesCommand},
{path: defaultPagesTS, command: codegenPagesCommand},
{path: defaultColsGo, command: codegenModelsCommand, models: true},
{path: defaultClientTS, command: codegenClientCommand},
{path: defaultClientGo, command: codegenClientCommand, args: []string{"-lang", "go"}},
}
// generatedHeader matches the first line of a generated file and captures the
// command and the flags it ran with. Only flags are accepted: nothing else
// from a file may reach a command line.
var generatedHeader = regexp.MustCompile(
`^// Code generated by vukem (codegen:[a-z]+)((?: -[a-z]+(?: [^ ]+)?)*)\. DO NOT EDIT\.$`,
)
// generatedArgs parses the first line of a generated file.
func generatedArgs(firstLine string) (command string, args []string, ok bool) {
m := generatedHeader.FindStringSubmatch(strings.TrimRight(firstLine, "\r"))
if m == nil {
return "", nil, false
}
return m[1], strings.Fields(m[2]), true
}
func codegenCommand() Command {
var check *bool
return CommandFunc{
CommandName: "codegen",
Desc: "Regenerate the generated frontend and client files that exist (-check fails if any is stale)",
DefineFlags: func(fs *flag.FlagSet) {
check = fs.Bool("check", false, "write nothing; fail if a file is not up to date")
},
Fn: func(ctx context.Context, app *App, _ []string) error {
var errs []error
for _, t := range codegenTargets {
if err := runCodegenTarget(ctx, app, t, *check); err != nil {
errs = append(errs, err)
}
}
return errors.Join(errs...)
},
}
}
// runCodegenTarget regenerates one existing file with the flags its header
// records. A file that is missing is skipped (the app does not use it); one
// whose header is not the generator's is left alone and reported.
func runCodegenTarget(ctx context.Context, app *App, t codegenTarget, check bool) error {
first, err := firstLineOf(filepath.FromSlash(t.path))
if errors.Is(err, os.ErrNotExist) {
return nil
}
if err != nil {
return fmt.Errorf("codegen: %w", err)
}
cmd := t.command()
if t.models && len(app.modelList) == 0 {
return nil
}
name, recorded, ok := generatedArgs(first)
if !ok || name != cmd.Name() {
return fmt.Errorf("codegen: %s has no %s header; remove it or run vukem %s", t.path, cmd.Name(), cmd.Name())
}
args := slices.Concat(t.args, recorded, []string{"-o", t.path})
if t.models {
args = append(args, "-pkg", packageOf(filepath.FromSlash(t.path)))
}
if check {
args = append(args, "-check")
}
fs := flag.NewFlagSet(cmd.Name(), flag.ContinueOnError)
fs.SetOutput(io.Discard)
cmd.Flags(fs)
if err := fs.Parse(args); err != nil {
return fmt.Errorf("codegen: %s: %w", t.path, err)
}
return cmd.Run(ctx, app, fs.Args())
}
func firstLineOf(path string) (string, error) {
f, err := os.Open(path)
if err != nil {
return "", err
}
defer f.Close()
line, _ := bufio.NewReader(f).ReadString('\n')
return strings.TrimRight(line, "\r\n"), nil
}
const defaultColsGo = "app/models/cols/cols_gen.go"
var errNoModels = errors.New(
"codegen:models: no models registered; pass vukem.WithModels(orm.ModelOf[T]()...)",
)
func codegenModelsCommand() Command {
var (
out *string
pkg *string
check *bool
)
return CommandFunc{
CommandName: "codegen:models",
Desc: "Generate typed column references for the models of vukem.WithModels (" + defaultColsGo + "; -check verifies)",
DefineFlags: func(fs *flag.FlagSet) {
out = fs.String("o", defaultColsGo, `write to this file ("-" for stdout)`)
pkg = fs.String("pkg", "", "package name of the generated file (default: the name of the directory of -o)")
check = fs.Bool("check", false, "write nothing; fail when the file differs from what would be generated")
},
Fn: func(_ context.Context, app *App, _ []string) error {
if len(app.modelList) == 0 {
return errNoModels
}
name := *pkg
if name == "" {
name = filepath.Base(filepath.Dir(filepath.FromSlash(*out)))
if *out == "-" {
name = "cols"
}
}
src, err := modelsGo(name, app.modelList)
if err != nil {
return err
}
switch {
case *check && *out == "-":
return errors.New("codegen:models: -check needs -o to name the file to check")
case *out == "-":
_, err := app.stdout.Write(src)
return err
case *check:
// A checkout with CRLF line endings holds the same file.
have, err := os.ReadFile(filepath.FromSlash(*out))
if err != nil || !bytes.Equal(bytes.ReplaceAll(have, []byte("\r\n"), []byte("\n")), src) {
return fmt.Errorf("codegen:models: %s is out of date; run codegen:models", *out)
}
return nil
}
path := filepath.FromSlash(*out)
if err := os.MkdirAll(filepath.Dir(path), 0o750); err != nil {
return fmt.Errorf("codegen:models: %w", err)
}
return os.WriteFile(path, src, 0o600)
},
}
}
// goInitialisms are the words a column name spells in capitals.
var goInitialisms = map[string]string{ //nolint:gochecknoglobals // read-only lookup table
"id": "ID", "url": "URL", "uri": "URI", "uuid": "UUID", "ip": "IP", "api": "API", "http": "HTTP",
"sql": "SQL", "html": "HTML", "json": "JSON",
}
// pascal turns snake_case into PascalCase ("blog_posts" is "BlogPosts").
func pascal(snake string) string {
var b strings.Builder
for w := range strings.SplitSeq(snake, "_") {
if w == "" {
continue
}
if up, ok := goInitialisms[w]; ok {
b.WriteString(up)
continue
}
b.WriteString(strings.ToUpper(w[:1]) + w[1:])
}
return b.String()
}
// colsImports hands out the import names of the packages the generated file
// uses, aliasing a package whose name is taken. Every package outside the
// standard library is imported under an explicit alias: reflect knows the
// import path of a type but not the name its package declares, so the alias
// is what the generated code relies on.
type colsImports struct {
byPath map[string]string // import path -> name used in the file
taken map[string]string // name -> import path
err error
}
var versionSuffixRe = regexp.MustCompile(`^v\d+$`)
// importAlias derives a Go identifier from an import path: its last element,
// or the one before it for a major version suffix (".../models/v2"). A
// package main cannot be imported.
func importAlias(importPath string) (string, error) {
if importPath == "main" || importPath == "" {
return "", errors.New("codegen:models: a model lives in package main, which cannot be imported; " +
"move the models to their own package")
}
parts := strings.Split(importPath, "/")
name := parts[len(parts)-1]
if versionSuffixRe.MatchString(name) && len(parts) > 1 {
name = parts[len(parts)-2]
}
name = strings.Map(func(r rune) rune {
if unicode.IsLetter(r) || unicode.IsDigit(r) || r == '_' {
return r
}
return '_'
}, name)
if name == "" || unicode.IsDigit(firstRune(name)) {
name = "pkg_" + name
}
return name, nil
}
func firstRune(s string) rune {
r, _ := utf8.DecodeRuneInString(s)
return r
}
func (c *colsImports) name(importPath, preferred string) string {
if n, ok := c.byPath[importPath]; ok {
return n
}
n := preferred
for i := 2; c.taken[n] != ""; i++ {
n = preferred + strconv.Itoa(i)
}
c.byPath[importPath], c.taken[n] = n, importPath
return n
}
// typeExpr writes the Go spelling of rt for the generated file. A generic
// instantiation (orm.JSON[T], sql.Null[T]) is "any": printing it would need
// the imports of its arguments.
func (c *colsImports) typeExpr(rt reflect.Type) string {
switch rt.Kind() { //nolint:exhaustive // the remaining kinds are basic types, named below
case reflect.Pointer:
return "*" + c.typeExpr(rt.Elem())
case reflect.Slice:
if rt.Name() == "" {
return "[]" + c.typeExpr(rt.Elem())
}
case reflect.Array:
if rt.Name() == "" {
return "[" + strconv.Itoa(rt.Len()) + "]" + c.typeExpr(rt.Elem())
}
case reflect.Map:
if rt.Name() == "" {
return "map[" + c.typeExpr(rt.Key()) + "]" + c.typeExpr(rt.Elem())
}
case reflect.Interface:
if rt.Name() == "" {
return "any"
}
}
if rt.Name() == "" || strings.Contains(rt.Name(), "[") {
// shortcut: a generic or unnamed type loses its value type check on that column; give it a named type to get it back.
return "any"
}
if rt.PkgPath() == "" {
return rt.Name()
}
alias, err := importAlias(rt.PkgPath())
if err != nil && c.err == nil {
c.err = err
}
return c.name(rt.PkgPath(), alias) + "." + rt.Name()
}
// modelsGo renders the typed column file for models: one variable per table,
// in table order, one Column per mapped field in field order.
func modelsGo(pkg string, models []orm.ModelInfo) ([]byte, error) {
// The name is written into the file as source text.
if !token.IsIdentifier(pkg) {
return nil, fmt.Errorf("codegen:models: %q is not a Go package name; pass -pkg with a plain identifier", pkg)
}
sorted := slices.SortedFunc(
slices.Values(models),
func(a, b orm.ModelInfo) int { return strings.Compare(a.Table, b.Table) },
)
imp := &colsImports{byPath: map[string]string{}, taken: map[string]string{}}
imp.name("github.com/AlexGalhardo/vukem/orm", "orm")
var body strings.Builder
seen := map[string]string{}
for _, m := range sorted {
name := pascal(m.Table)
if prev, dup := seen[name]; dup {
return nil, fmt.Errorf("codegen:models: tables %q and %q both generate the name %s", prev, m.Table, name)
}
seen[name] = m.Table
if !token.IsIdentifier(name) {
return nil, fmt.Errorf("codegen:models: table %q does not make a Go name (%q)", m.Table, name)
}
model := imp.typeExpr(m.Type)
fmt.Fprintf(&body, "// %s holds the columns of %s (table %q).\nvar %s = struct {\n", name, model, m.Table, name)
used := map[string]string{}
decl := make([]string, 0, len(m.Fields))
inits := make([]string, 0, len(m.Fields))
for _, f := range m.Fields {
field := pascal(f.Column)
if !token.IsIdentifier(field) {
return nil, fmt.Errorf(
"codegen:models: column %q of %s does not make a Go name (%q)",
f.Column,
m.Table,
field,
)
}
if prev, dup := used[field]; dup {
return nil, fmt.Errorf(
"codegen:models: columns %q and %q of %s both generate the name %s",
prev,
f.Column,
m.Table,
field,
)
}
used[field] = f.Column
typ := fmt.Sprintf("orm.Column[%s, %s]", model, imp.typeExpr(f.Type))
decl = append(decl, field+" "+typ)
inits = append(inits, fmt.Sprintf("%s: orm.Col[%s, %s](%q),", field, model, imp.typeExpr(f.Type), f.Column))
}
body.WriteString(strings.Join(decl, "\n") + "\n}{\n" + strings.Join(inits, "\n") + "\n}\n\n")
}
if imp.err != nil {
return nil, imp.err
}
var std, own, other []string
for p, n := range imp.byPath {
line := strconv.Quote(p)
if n != filepath.Base(p) || strings.Contains(strings.SplitN(p, "/", 2)[0], ".") {
line = n + " " + line
}
switch {
case p == "github.com/AlexGalhardo/vukem/orm":
own = append(own, line)
case !strings.Contains(strings.SplitN(p, "/", 2)[0], "."):
std = append(std, line)
default:
other = append(other, line)
}
}
var out strings.Builder
out.WriteString("// Code generated by vukem codegen:models. DO NOT EDIT.\n\n")
out.WriteString(
"// Package " + pkg + " holds typed column references for the app's models.\npackage " + pkg + "\n\nimport (\n",
)
for _, group := range [][]string{std, own, other} {
if len(group) == 0 {
continue
}
slices.Sort(group)
out.WriteString("\t" + strings.Join(group, "\n\t") + "\n\n")
}
out.WriteString(")\n\n" + strings.TrimRight(body.String(), "\n") + "\n")
src, err := format.Source([]byte(out.String()))
if err != nil {
return nil, fmt.Errorf("codegen:models: format generated code: %w", err)
}
return src, nil
}
var packageLineRe = regexp.MustCompile(`(?m)^package ([A-Za-z_][A-Za-z0-9_]*)`)
// packageOf is the package name a generated Go file declares, or "" (the
// command then names the package after the directory).