-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathproject
executable file
·3106 lines (2597 loc) · 101 KB
/
project
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
#!/usr/bin/env bash
# shellcheck disable=1091,2155,2068,2086,2031,2048,2178,2120
#
#
# Main s̶c̶r̶i̶p̶t program to manage the entire project stack.
#
#
source ".helpers.sh"
starting_cwd=$(pwd)
ensure_pwd_is_top_level
declare X_FORCE_REGEN X_NO_CONFIRMATION X_NO_GEN X_NO_BACKUP X_ENV X_DEBUG X_NO_EXIT_CLEANUP
declare BUILD_VERSION
readonly CURRENT_BRANCH=$(git rev-parse --abbrev-ref HEAD)
readonly SPEC_PATH="openapi.yaml"
readonly BUILD_DIR="bin/build"
readonly TOOLS_DIR="bin/tools"
readonly PROTO_DIR="internal/pb"
readonly MIGRATIONS_DIR="db/migrations"
readonly MIGRATIONS_TABLE="schema_migrations"
readonly POST_MIGRATIONS_DIR="db/post-migrations"
readonly POST_MIGRATIONS_TABLE="schema_post_migrations"
readonly CERTIFICATES_DIR="certificates"
readonly GOWRAP_TEMPLATES_DIR="internal/gowrap-templates"
readonly REPOS_DIR="internal/repos"
readonly PG_REPO_DIR="$REPOS_DIR/postgresql"
readonly XO_TEMPLATES_DIR="$PG_REPO_DIR/xo-templates"
readonly BIN_TEMPLATES_DIR="bin/templates"
readonly POSTGRES_TEST_DB="postgres_test"
readonly DUMPS_DIR="$HOME/openapi_go_gin_postgres_dumps"
pkg="$(head -1 go.mod)"
readonly GOMOD_PKG="${pkg#module *}"
# can only run with count=1 at most
readonly XO_TESTS_PKG="$GOMOD_PKG/internal/repos/postgresql/xo-templates/tests"
readonly OPID_AUTH_PATH="operationAuth.gen.json"
readonly REST_MODELS="internal/rest/models.spec.go"
readonly PG_REPO_GEN="$PG_REPO_DIR/gen"
readonly RUN_CACHE=".run.cache"
readonly GEN_CACHE=".generate.cache"
readonly GEN_CACHE_BACKUP="$GEN_CACHE-backup"
readonly SWAGGER_UI_DIR="internal/static/swagger-ui"
readonly FRONTEND_GEN="frontend/src/gen"
readonly MAX_FNAME_LOG_LEN=13
readonly GEN_SCHEMA_PATH="db/schema.sql"
readonly TMP="${TMPDIR:-"/tmp"}"
GEN_POSTGRES_DB="gen_db"
failed_tool_build_marker="$TMP/failed_tool_build_marker"
rm -f "$failed_tool_build_marker"
go_test_flags=()
# shuffle disables go test caching. Definitely don't want in dev.
test -n "$CI" && go_test_flags+=("-shuffle=on")
# determines whether gen cache should be restored at program exit, i.e. failed commands.
# cache folder must be cleaned at exit if true.
# only restores if true.
declare need_backup_restore
# stores the first executing function of xsetup.backup to track if caching gen is already running,
# to allow for nested xsetup.backup and cache-cleanup inside multiple functions.
xsetup_backup_gen_caller=""
# stores the first executing function to determine if a migration
# is needed when running gen* functions which call each other
xsetup_gen_migrated=""
# stores the first executing function to determine if tools have been built
xsetup_tools_built=""
# log for any function output.
xlog() {
local fname="${FUNCNAME[1]#*.}"
local color="$BLUE"
local max_len=$MAX_FNAME_LOG_LEN
[[ "$CMD" = "$fname" ]] && cat && return
if [[ "${FUNCNAME[1]%%.*}" != "x" ]]; then
fname="${FUNCNAME[1]}" # show non-x funcs
color="$MAGENTA"
fi
if [[ "${FUNCNAME[1]}" =~ ^.*(check\.bin|install\.bin).* ]]; then
max_len=100
fi
if [[ ${#fname} -gt $max_len ]]; then
fname="${fname:0:$max_len}…"
fi
local _=$(printf "%*s |\n" $((max_len + 1)) "$fname")
sed -ue "s/^/${color}$fname >${OFF} /"
}
# log stderr for any function output.
# sed is buffering by default (without -u) so streams dont preserve order
# > >(one) 2> >(two) are background processes so it will break our parallel code.
xerr() {
local fname="${FUNCNAME[1]#*.}"
local max_len=$MAX_FNAME_LOG_LEN
[[ "$CMD" = "$fname" ]] && cat && return
if [[ ${#fname} -gt $max_len ]]; then
fname="${fname:0:$max_len}…"
fi
local _=$(printf "%*s |\n" $((max_len + 1)) "$fname")
sed -ue "s/^/${RED}$fname >${OFF} /" >&2
}
kill_descendants() {
# air and vite spawn processes as well, need to kill those (whose parent is pid), kill $pid will not kill children. pkill -P would also work
kill $pids || true
kill "$(list_descendants $pids)" || true
pids=""
}
######################### x-functions setup #########################
xsetup.build-tools() {
test -n "$xsetup_tools_built" && return
xsetup_tools_built="${FUNCNAME[1]}"
x.gen.build-tools || err Could not rebuild gen tools
}
backup_branch="backup-gen-$(uuidgen)"
# TODO: when running gen and then stashing changes, or switching branches,
# cache should be removed.
gen-cache.backup() {
rm -rf "$GEN_CACHE_BACKUP" || true
cp -r "$GEN_CACHE" "$GEN_CACHE_BACKUP" || true
}
gen-cache.restore() {
rm -rf "$GEN_CACHE"
mv "$GEN_CACHE_BACKUP" "$GEN_CACHE" || true
}
# Create a backup stash with current changes.
# Uncommitted changes are restored on error unless --x-no-backup flag is passed.
xsetup.backup() {
test -n "$xsetup_backup_gen_caller" && return
xsetup_backup_gen_caller="${FUNCNAME[1]}"
mkdir -p "$GEN_CACHE"
backup_stash_name="backup-stash-$backup_branch"
echo "$backup_branch" >backup-gen-stash-dummy.txt # make sure something unique and not gitignored is in the current branch
gen-cache.backup
git stash push -m "$backup_stash_name" --include-untracked || err "Could not backup untracked changes before codegen"
git checkout -b "$backup_branch" &>/dev/null
git stash apply "stash^{/$backup_stash_name}" &>/dev/null
need_backup_restore=true # unless
}
xsetup.backup.cleanup() {
# only accept gen if the main function that backed it up in the first place
# finishes successfully, i.e. this very function was called
if [[ "$xsetup_backup_gen_caller" = "${FUNCNAME[1]}" ]]; then
need_backup_restore=false
fi
}
xsetup.backup.restore() {
echo "
Backup branch: $backup_branch
${RED}Restoring previous uncommitted changes to current branch (${YELLOW}${CURRENT_BRANCH}${RED})${OFF}"
wait # for any pending job
git reset --hard &>/dev/null && git clean -df &>/dev/null
# if not removing the whole cache folder we get `already exists, no checkout` upon stash apply since we have just reset gitignore
# IMPORTANT: we do want to delete regardless since we are restoring the cache folder on stash apply so we
# don't need complex cache invalidation based on what's been run
rm -rf "$GEN_CACHE"
git stash apply "stash^{/$backup_stash_name}" &>/dev/null
}
xsetup.drop-and-migrate-gen-db() {
test -n "$xsetup_gen_migrated" && return
xsetup_gen_migrated=1
{ { {
cache_all "$GEN_CACHE/db.md5" db/ --exclude "db/schema.sql" && return 0
POSTGRES_DB="$GEN_POSTGRES_DB"
x.db.drop
x.migrate up
export_gen_db_schema
} 2>&4 | xlog >&3; } 4>&1 | xerr >&3; } 3>&1
}
######################### x-functions #########################
# Check build dependencies are met and prompt to install if missing.
x.check-build-deps() {
{ { {
mkdir -p $TOOLS_DIR
while IFS= read -r line; do
[[ $line =~ ^declare\ -f\ check\.bin\. ]] && BIN_CHECKS+=("${line##declare -f check.bin.}")
[[ $line =~ ^declare\ -f\ install\.bin\. ]] && BIN_INSTALLS+=("${line##declare -f install.bin.}")
done < <(declare -F)
echo "Checking dependency minimum versions..."
for bin in "${BIN_CHECKS[@]}"; do
# local r
# r="$(...)" # redirect to var while also streaming unbuffered output with | tee /dev/tty
if "check.bin.$bin"; then
continue
fi
if ! element_in_array "$bin" "${BIN_INSTALLS[@]}"; then
echo "No automatic installation available. Please install $bin manually and retry"
exit 1
fi
with_tty confirm "Do you want to install $bin now?" || exit 1
echo "Installing $bin..."
if ! "install.bin.$bin"; then
err "$bin installation failed"
fi
if ! "check.bin.$bin"; then
err "$bin check failed after installation"
fi
echo "Installed $bin..."
done
} 2>&4 | xlog >&3; } 4>&1 | xerr >&3; } 3>&1
}
# Check dependencies and fetch required tools.
x.bootstrap() {
{ { {
git submodule update --init --recursive # sync later on with git `git submodule update --force --recursive --remote`
x.check-build-deps
x.backend.sync-deps
x.install-tools
x.setup.swagger-ui
x.gen.build-tools
cd frontend
pnpm i --frozen-lockfile
cd -
cd e2e
pnpm i --frozen-lockfile
cd -
traefik_dir="$HOME/traefik-bootstrap"
with_tty confirm "Do you want to setup and run traefik (install dir: $traefik_dir)?" && x.setup.traefik "$traefik_dir"
echo "${RED}Make sure to add \`complete -o nospace -C project project\` to your ~/.bashrc for completion.${OFF}"
} 2>&4 | xlog >&3; } 4>&1 | xerr >&3; } 3>&1
}
# Install miscellaneous tool binaries locally.
x.install-tools() {
{ { {
declare -A jobs
local pids=() failed_jobs=()
# install node libs with --prefix $TOOLS_DIR, if any
# ...
# TODO: abstract to function that just accepts commands to run
# as it is we might just use parallel but may use own functions later.
commands=(
"go install -tags 'postgres' github.com/golang-migrate/migrate/v4/cmd/migrate@v4.15.2"
"go install github.com/sqlc-dev/sqlc/cmd/sqlc@v1.24.0"
"go install github.com/golangci/golangci-lint/cmd/golangci-lint@v1.63.4"
"go install github.com/tufin/oasdiff@v1.10.9"
"go install golang.org/x/tools/cmd/goimports@latest"
"go install mvdan.cc/gofumpt@latest"
"go install mvdan.cc/sh/v3/cmd/shfmt@latest"
"go install github.com/air-verse/air@latest"
"go install github.com/danicc097/xo/v5@v5.6.0"
"go install github.com/mikefarah/yq/v4@v4.34.2"
"go install github.com/hexdigest/gowrap/cmd/gowrap@v1.4.0"
"go install golang.org/x/tools/cmd/stringer@latest"
"go install github.com/maxbrunsfeld/counterfeiter/v6@latest"
"go install google.golang.org/protobuf/cmd/protoc-gen-go@v1.28.1"
"go install google.golang.org/grpc/cmd/protoc-gen-go-grpc@v1.2"
# vacuum lint openapi.exploded.yaml -ed
"go install github.com/daveshanley/vacuum@latest"
)
for command in "${commands[@]}"; do
$command &
pids+=($!)
jobs[$!]="$command"
done
for pid in "${pids[@]}"; do
wait -fn "$pid" || failed_jobs+=("${jobs[$pid]}")
done
# For failing installs for no apparent reason, try running 'go clean -cache' and retry. Else install with ' -mod=readonly' flag.
if [[ ${#failed_jobs[@]} -gt 0 ]]; then
err "Could not install all tools. Failed jobs:
$(join_by $'\n' "${failed_jobs[@]}")"
fi
} 2>&4 | xlog >&3; } 4>&1 | xerr >&3; } 3>&1
}
# Fetch latest Swagger UI bundle.
x.setup.swagger-ui() {
{ { {
local name
name="$(curl --retry 10 --user-agent "$GOMOD_PKG" -fsSL "https://api.github.com/repos/swagger-api/swagger-ui/releases/latest" | jq -r ".. .tag_name? // empty")"
curl --retry 10 -fsSL "github.com/swagger-api/swagger-ui/archive/refs/tags/$name.tar.gz" -o swagger-ui.tar.gz
tar xf swagger-ui.tar.gz swagger-ui-"${name#*v}"/dist --one-top-level=swagger-ui --strip-components=2
rm swagger-ui.tar.gz
mkdir -p $SWAGGER_UI_DIR
mv swagger-ui/* $SWAGGER_UI_DIR
rm -r swagger-ui
} 2>&4 | xlog >&3; } 4>&1 | xerr >&3; } 3>&1
}
# Run pre-generation scripts in the internal package.
x.gen.pregen() {
xsetup.backup
xsetup.drop-and-migrate-gen-db
xsetup.build-tools
{ { {
POSTGRES_DB="$GEN_POSTGRES_DB"
echo "Running generation"
# NOTE: swaggest won't generate for arrays of structs. use a struct with array fields instead.
generate_structs_map # spec structs or their content in rest package might have changed
go build -o $BUILD_DIR/codegen cmd/codegen/main.go || mark_failed_tool_build
local rest_structs=() refs=() spec_schemas=()
generate_missing_spec_schemas
codegen validate-spec -env=".env.$X_ENV"
# useless after merging models and db
# ast-parser verify-no-import --imports "$GOMOD_PKG/internal/repos/postgresql/gen/models" "$REST_MODELS" || err Please use generated rest package OpenAPI types instead.
sync_spec_with_db
######## Ensure consistent style for future codegen
pascal_case_spec_operation_ids
update_roles_and_scopes
validate_spec
codegen pre -env=".env.$X_ENV" -op-id-auth="$OPID_AUTH_PATH"
update_spec_with_structs
remove_schemas_marked_for_deletion
} 2>&4 | xlog >&3; } 4>&1 | xerr >&3; } 3>&1
xsetup.backup.cleanup
}
pascal_case_spec_operation_ids() {
echo "Applying PascalCase to operation IDs"
# outputs safe double-quoted paths for yq
# https://github.com/mikefarah/yq/issues/1295
mapfile -t opid_paths < <(yq e '
.paths[][].operationId
| path
| with(.[] | select(contains(".") or contains("/") or contains("{")); . = "\"" + . + "\"")
| join(".")
' $SPEC_PATH)
mapfile -t opids < <(yq e ".paths[][].operationId" $SPEC_PATH)
local ops=""
for i in ${!opids[@]}; do
local new_opid=""
to_pascal new_opid "${opids[$i]}"
ops+=".${opid_paths[$i]}=\"${new_opid}\" |" # cant have space
done
yq_op="${ops%"|"}"
yq e "$yq_op" -i "$SPEC_PATH"
}
# ext vars: spec_schemas, rest_structs
generate_missing_spec_schemas() {
declare -A rest_schema_lookup spec_schema_lookup
go-utils.find_structs rest_structs "$REST_MODELS"
for schema in "${rest_structs[@]}"; do # only interested in generating rest models.spec.go schemas. let the rest fail normally.
rest_schema_lookup["$schema"]=1
done
mapfile -t spec_schemas < <(yq eval '.components.schemas[] | key' "$SPEC_PATH")
for schema in "${spec_schemas[@]}"; do # only interested in generating rest models.spec.go schemas. let the rest fail.
spec_schema_lookup["$schema"]=1
done
local missing_rest_models=()
mapfile -t refs < <(sed -nr "s/[^#]?.*\\$ref: '#\/components\/schemas\/(.*)'/\1/p" $SPEC_PATH | sort | uniq)
for ref in "${refs[@]}"; do
if [[ -n "${rest_schema_lookup["$ref"]}" && -z "${spec_schema_lookup["$ref"]}" ]]; then
missing_rest_models+=("$ref")
fi
done
if [[ ${#missing_rest_models[@]} -gt 0 ]]; then
echo "${YELLOW}Generating missing rest package \$ref's:"
printf "${YELLOW} - %s\n" "${missing_rest_models[@]}"
echo "${OFF}"
local new_schemas=""
for ref in "${missing_rest_models[@]}"; do
new_schemas+="\"$ref\": {
\"x-gen-struct\": \"$ref\",
\"x-is-generated\": true
},"
done
yq eval-all ".components.schemas += {
${new_schemas%,}
}" -i "$SPEC_PATH"
fi
}
validate_spec() {
echo "Validating spec $SPEC_PATH"
mapfile -t invalid_schemas < <(yq e '.components.schemas[] | select(has("x-gen-struct") and (has("x-is-generated") | not)) | key' $SPEC_PATH)
[[ ${#invalid_schemas[@]} -gt 0 ]] && err "x-gen-struct can only be used in generated schemas (x-is-generated). Found in:
$(join_by $'\n' "${invalid_schemas[@]}")"
mapfile -t invalid_schemas < <(yq e '.components.schemas[] | select(has("x-gen-struct") and key != .x-gen-struct) | key' $SPEC_PATH)
[[ ${#invalid_schemas[@]} -gt 0 ]] && err "x-gen-struct must match schema name. Please rename:
$(join_by $'\n' "${invalid_schemas[@]}")"
local clashes=() services_prefix_clashes=() db_prefix_clashes=()
for custom_schema in $(yq ".components.schemas[] | select((.x-is-generated == true) | not) | key" $SPEC_PATH); do
if [[ " ${rest_structs[*]} " =~ " ${custom_schema} " ]]; then
line_number=$(yq ".components.schemas.$custom_schema | line" $SPEC_PATH)
clashes+=(" $custom_schema (${SPEC_PATH}:${line_number})")
fi
if [[ $custom_schema =~ ^Services[A-Z].*$ ]]; then
services_prefix_clashes+=(" $custom_schema (${SPEC_PATH}:${line_number})")
fi
if [[ $custom_schema =~ ^Models[A-Z].*$ ]]; then
db_prefix_clashes+=(" $custom_schema (${SPEC_PATH}:${line_number})")
fi
done
if [[ ${#clashes[@]} -gt 0 ]]; then
err "The following non-generated schemas would have been overridden by internal/rest/models.spec.go structs. Please rename or delete:
$(join_by $'\n' "${clashes[@]}")"
fi
if [[ ${#services_prefix_clashes[@]} -gt 0 ]]; then
err "Services prefix is restricted to generated structs. Please rename or delete:
$(join_by $'\n' "${services_prefix_clashes[@]}")"
fi
if [[ ${#db_prefix_clashes[@]} -gt 0 ]]; then
err "Models prefix is restricted to generated structs. Please rename or delete:
$(join_by $'\n' "${db_prefix_clashes[@]}")"
fi
}
update_roles_and_scopes() {
echo "Updating roles and scopes"
######## Sync spec enums with external policy sources and validate existing schema enums.
######## External json files are the source of truth, indexed by enum name
# arrays can't be nested in bash
declare -A enum_src_files=(
[Scope]="$SCOPE_POLICY_PATH"
[Role]="$ROLE_POLICY_PATH"
)
declare -A enum_vext=(
[Scope]="x-required-scopes"
[Role]="x-required-role"
)
declare -A enum_values=()
for enum in ${!enum_src_files[@]}; do
[[ $(yq e ".components.schemas | has(\"$enum\")" $SPEC_PATH) = "false" ]] &&
yq e ".components.schemas.$enum.type = \"string\"" -i $SPEC_PATH
local src_file="${enum_src_files[$enum]}"
vendor_ext="${enum_vext[$enum]}"
enums=$(yq -P --output-format=yaml '.[] | key' $src_file)
mapfile -t enums <<<$enums
src_comment="$src_file keys"
replace_enum_in_spec "$enum" enums "$src_comment"
mapfile spec_enums < <(yq e ".paths[][].$vendor_ext | select(length > 0)" $SPEC_PATH)
spec_enums=("${spec_enums[*]//- /}")
mapfile -t spec_enums < <(printf "\"%s\"\n" ${spec_enums[*]})
mapfile -t clean_enums < <(printf "\"%s\"\n" ${enums[*]})
# ensure only existing enums from src_file are used
for spec_enum in "${spec_enums[@]}"; do
[[ ! " ${clean_enums[*]} " =~ " ${spec_enum} " ]] && err "$spec_enum is not a valid '$enum'"
done
enum_list=$(printf ",\"%s\"" "${enums[@]}")
enum_list="[${enum_list:1}]"
enum_values[$enum]=$enum_list
done
######## IDE intellisense/validation
yq -e ".definitions.Operation.properties +=
{
\"${enum_vext[Role]}\": {
\"type\": \"string\",
\"enum\": ${enum_values[Role]}
},
\"${enum_vext[Scope]}\": {
\"type\": \"array\",
\"items\": {\"enum\": ${enum_values[Scope]}}
}
}" -i -oj .vscode/openapi-schema.json
######## Generate shared policies once the spec has been validated
echo "Writing shared auth policies"
yq -o=json e "
.paths[][]
| explode(.)
| {
.operationId: {
\"scopes\": .x-required-scopes,
\"role\": .x-required-role,
\"requiresAuthentication\": has(\"security\")
}
}
| select(.[]) as \$i ireduce ({}; . + \$i)
" $SPEC_PATH >$OPID_AUTH_PATH
}
sync_spec_with_db() {
cache_all "$GEN_CACHE/models.md5" ${base_cache_deps[@]} db/ $SPEC_PATH && return 0
sync_db_enums_with_spec
# TODO: repo specific changes should all be abstracted to their own standalone functions
# to be easily replaced in other repos
######## Sync projects and related project info
mapfile -t db_projects < <(docker.postgres.psql -d $POSTGRES_DB -c "select name from projects;" 2>/dev/null)
[[ ${#db_projects[@]} -gt 0 ]] || err "No projects found in database $POSTGRES_DB"
replace_enum_in_spec "ProjectName" db_projects "projects table"
for project in ${db_projects[@]}; do
### kanban steps
mapfile -t kanban_steps < <(docker.postgres.psql -d $POSTGRES_DB -c "
select name from kanban_steps where project_id = (
select project_id from projects where name = '$project'
);" 2>/dev/null)
[[ ${#kanban_steps[@]} -gt 0 ]] || {
echo "${YELLOW}[WARNING] No kanban steps found for project '$project' in database $POSTGRES_DB${OFF}" && continue
}
local pascal_project=""
to_pascal pascal_project "$project"
schema_name="${pascal_project}KanbanSteps"
replace_enum_in_spec "$schema_name" kanban_steps "kanban_steps table"
### work item types
mapfile -t work_item_types < <(docker.postgres.psql -d $POSTGRES_DB -c "
select name from work_item_types where project_id = (
select project_id from projects where name = '$project'
);" 2>/dev/null)
[[ ${#work_item_types[@]} -gt 0 ]] || {
echo "${YELLOW}[WARNING] No work item types found for project '$project' in database $POSTGRES_DB${OFF}" && continue
}
schema_name="${pascal_project}WorkItemTypes"
replace_enum_in_spec "$schema_name" work_item_types "work_item_types table"
done
generate_models_mappings
}
generate_repo_constructor() {
local out_path="internal/repos/repos.gen.go"
local repos="$REPOS_DIR/repos.go"
local repo_interfaces=()
go-utils.find_interfaces repo_interfaces $repos
for iface in "${repo_interfaces[@]}"; do
local struct_fields+=("${iface} ${iface}")
done
cat <<EOF >$out_path
// Code generated by project. DO NOT EDIT.
package repos
type Repos struct {
$(join_by $'\n' "${struct_fields[@]}")
}
EOF
gofumpt -w $out_path
}
# for manually inserted elements via migrations, e.g. projects, kanban_steps, work_item_type,
# generate 2-way maps id<- ->name to save up useless db calls and make logic switching
# and repos usage much easier
generate_models_mappings() {
local model_mappings_path="internal/models_mappings.gen.go"
cat <<EOF >$model_mappings_path
// Code generated by project. DO NOT EDIT.
package internal
import (
"$GOMOD_PKG/$PG_REPO_GEN/models"
)
EOF
mapfile -t projects_rows < <(docker.postgres.psql -d $POSTGRES_DB -c "select project_id,name from projects;" 2>/dev/null)
generate_model_mappings_dicts "Project" models.ProjectID projects_rows "Name"
for project in ${db_projects[@]}; do
local pascal_project=""
to_pascal pascal_project "$project"
mapfile -t kanban_steps_rows < <(docker.postgres.psql -d $POSTGRES_DB -c "
select kanban_step_id,name from kanban_steps where project_id = (
select project_id from projects where name = '$project'
);" 2>/dev/null)
[[ ${#kanban_steps_rows[@]} -gt 0 ]] || continue
prefix="${pascal_project}KanbanSteps"
generate_model_mappings_dicts $prefix models.KanbanStepID kanban_steps_rows
{
kanban_steps_order_rows=()
mapfile -t kanban_steps_order_rows < <(docker.postgres.psql -d $POSTGRES_DB -c "
select kanban_step_id,step_order from kanban_steps where project_id = (
select project_id from projects where name = '$project'
);" 2>/dev/null)
[[ ${#kanban_steps_order_rows[@]} -gt 0 ]] || continue
echo "var (
${prefix}StepOrderByID = map[models.KanbanStepID]int{
"
for row in "${kanban_steps_order_rows[@]}"; do
first=$(cut_first "$row" "|") # always safe
mapfile -t arr <<<"${first}"
local id="${arr[0]}"
local kanban_step="${arr[1]}"
echo "${id}: ${kanban_step},"
done
echo "})"
} >>$model_mappings_path
mapfile -t work_item_types_rows < <(docker.postgres.psql -d $POSTGRES_DB -c "
select work_item_type_id,name from work_item_types where project_id = (
select project_id from projects where name = '$project'
);" 2>/dev/null)
[[ ${#work_item_types_rows[@]} -gt 0 ]] || continue
prefix="${pascal_project}WorkItemTypes"
generate_model_mappings_dicts $prefix models.WorkItemTypeID work_item_types_rows
done
gofumpt -w $model_mappings_path
}
# generates dictionaries for existing database elements, meant for those
# inserted exclusively via migrations
generate_model_mappings_dicts() {
local prefix="$1"
local id_type="$2"
local -n __arr="$3" # db rows
local prefix_suffix="$4"
{
echo "var ("
echo "${prefix}NameByID = map[${id_type}]models.${prefix}${prefix_suffix}{"
for row in "${__arr[@]}"; do
first=$(cut_first "$row" "|") # always safe
mapfile -t arr <<<"${first}"
local id="${arr[0]}" name="${arr[1]}" pascal_name=""
to_pascal pascal_name "$name"
echo "${id}: models.${prefix}${prefix_suffix}${pascal_name},"
done
echo "}"
echo "${prefix}IDByName = map[models.${prefix}${prefix_suffix}]${id_type}{"
for row in "${__arr[@]}"; do
first=$(cut_first "$row" "|") # always safe
mapfile -t arr <<<"${first}"
local id="${arr[0]}" name="${arr[1]}" pascal_name=""
to_pascal pascal_name "$name"
echo "models.${prefix}${prefix_suffix}${pascal_name}: ${id},"
done
echo "})"
} >>"$model_mappings_path"
}
clean_yq_array() {
local -n __arr="$1"
__arr=("${__arr[*]//- /}")
mapfile -t __arr < <(printf "\"%s\"\n" ${__arr[*]})
echo ${__arr[@]}
}
go_test() {
local cache_opt="-count=1" exit_code=1
cache_all "$GEN_CACHE/go-test.md5" .env.$X_ENV db/ >/dev/null && cache_opt=""
set -x
APP_ENV="$X_ENV" go test ${go_test_flags[@]} $cache_opt $@
exit_code=$?
set +x
return $exit_code
}
# Run post-generation scripts in the internal package.
x.gen.postgen() {
xsetup.backup
xsetup.drop-and-migrate-gen-db
xsetup.build-tools
{ { {
POSTGRES_DB="$GEN_POSTGRES_DB"
echo "Running generation"
} 2>&4 | xlog >&3; } 4>&1 | xerr >&3; } 3>&1
xsetup.backup.cleanup
}
# Generate type-safe Go code from SQL.
x.gen.sqlc() {
xsetup.backup
xsetup.drop-and-migrate-gen-db
{ { {
echo "Running generation"
rm -f "$PG_REPO_GEN"/models/*.sqlc.go
x.lint.sql
sqlc generate --experimental -f "$PG_REPO_DIR"/sqlc.yaml || err "Failed sqlc generation"
rm -f "$PG_REPO_GEN"/models/models.go # sqlc enums
sed -i 's/\bdb DBTX\b/d DBTX/g' "$PG_REPO_GEN"/models/querier.go # consistent with repo gowrap gen so we can use reposwrappers
gowrap gen \
-g \
-p "$GOMOD_PKG/$PG_REPO_GEN/models" \
-i Querier \
-t "$GOWRAP_TEMPLATES_DIR/sqlc.tmpl" \
-o "$PG_REPO_DIR/sqlc_querier_wrapper.gen.go"
} 2>&4 | xlog >&3; } 4>&1 | xerr >&3; } 3>&1
xsetup.backup.cleanup
}
# Automatically generate CRUD and index queries with joins based on existing indexes from a Postgres schema.
x.gen.xo() {
xsetup.backup
xsetup.drop-and-migrate-gen-db
{ { {
cache_all "$GEN_CACHE/xo.md5" ${base_cache_deps[@]} go.mod db/ $XO_TEMPLATES_DIR/ \
--exclude "$XO_TEMPLATES_DIR/tests/*" && return 0
echo "Running generation"
rm -rf "$PG_REPO_GEN"/models/*.xo.go
mkdir -p "$PG_REPO_GEN"/models
xo_schema -o "$PG_REPO_GEN"/models --debug \
--schema public \
--ignore "*.created_at" \
--ignore "*.updated_at" || err "Failed xo public schema generation" &
xo_schema -o "$PG_REPO_GEN"/models --debug \
--schema extra_schema \
--ignore "*.created_at" \
--ignore "*.updated_at" ||
err "Failed xo extra_schema schema generation" &
mkdir -p "$PG_REPO_GEN"/models
xo_schema -o "$PG_REPO_GEN"/models \
--schema cache ||
err "Failed xo cache schema generation" &
wait_without_error
files=$(find "$PG_REPO_GEN/models" \
-name "*.go")
goimports -w $files
xo_generate_spec_helpers
} 2>&4 | xlog >&3; } 4>&1 | xerr >&3; } 3>&1
xsetup.backup.cleanup
}
# Generate a type-safe SQL builder.
x.gen.jet() {
xsetup.backup
xsetup.drop-and-migrate-gen-db
xsetup.build-tools
{ { {
# results may be combined with xo's *Public structs and not reinvent the wheel for jet.
# should not be hard to generate all adapters at once jet->xo *Public in a new file alongside jet gen.
# in the end fields are the same name if goName conventions are followed (configurable via custom jet cmd)
# if it gives problems for some fields (ID, API and the like)
echo "Running generation"
local gen_path="$PG_REPO_GEN/jet"
local schema=public
rm -rf "$gen_path"
{
jet -dbname="$GEN_POSTGRES_DB" --env=.env."$X_ENV" --out=./"$gen_path" \
--schema="$schema" \
--ignore-tables="$MIGRATIONS_TABLE,$POST_MIGRATIONS_TABLE"
mv "./$gen_path"/$GEN_POSTGRES_DB/* "$gen_path"
rm -r "./$gen_path/$GEN_POSTGRES_DB/"
}
} 2>&4 | xlog >&3; } 4>&1 | xerr >&3; } 3>&1
xsetup.backup.cleanup
}
# Generate repo interface wrappers with common logic: tracing, timeout...
# Args: [name]
x.gen.gowrap() {
xsetup.backup
{ { {
local name="$1" # optional to force regen on an interface
local repos="$REPOS_DIR/repos.go"
echo "Running generation"
local cache="$GEN_CACHE/gowrap"
local suffixes=(
"retry-repo:with_retry"
"timeout:with_timeout"
"otel:with_otel"
"prometheus:with_prometheus" # TODO: https://last9.io/blog/native-support-for-opentelemetry-metrics-in-prometheus/ https://github.com/open-telemetry/opentelemetry-collector-contrib/tree/main/pkg/translator/prometheus
)
local repo_interfaces=()
go-utils.find_interfaces repo_interfaces $repos
mkdir -p "$cache"
if test -n "$name"; then
repo_interfaces=("$name")
fi
local updated_ifaces=()
for iface in "${repo_interfaces[@]}"; do
iface_content="$(go-utils.get_interface_methods $iface $repos)"
if diff "$cache/$iface" <(echo "$iface_content") &>/dev/null && [[ "$iface" != "$name" ]]; then
[[ $X_FORCE_REGEN -eq 0 ]] && continue
fi
for suffix in ${suffixes[@]}; do
{
IFS=":" read -r -a arr <<<${suffix}
local tmpl="${arr[0]}"
local suffix="${arr[1]}"
gowrap gen \
-g \
-p $GOMOD_PKG/$REPOS_DIR \
-i $iface \
-t "$GOWRAP_TEMPLATES_DIR/$tmpl.tmpl" \
-o "$REPOS_DIR/reposwrappers/${iface,,}_$suffix.gen.go"
} &
done
echo "$iface_content" >"$cache/$iface"
updated_ifaces+=("$iface")
done
wait_without_error || err Failed jobs
if [[ ${#updated_ifaces[@]} -gt 0 ]]; then
echo "Updated repo interfaces: ${updated_ifaces[*]}"
fi
} 2>&4 | xlog >&3; } 4>&1 | xerr >&3; } 3>&1
xsetup.backup.cleanup
}
# Generate Go client and server from spec.
x.gen.client-server() {
xsetup.build-tools
xsetup.backup
{ { {
echo "Running generation"
paths_file=".openapi.paths.yaml"
local all_types=()
# mapfile -t all_types < <(ast-parser find-types --exclude-generics --public-only "$REST_MODELS")
go-utils.find_all_types all_types "$REST_MODELS"
rest_types_list=$(join_by "," ${all_types[*]})
mapfile -t spec_rest_types < <(yq e '.components.schemas[] | select(.x-spec-rest-type == true) | key' $SPEC_PATH)
spec_rest_types_list=$(join_by "," ${spec_rest_types[*]})
# hack to get separate types generation
sed "s/\$ref: '\#\//\$ref: '$SPEC_PATH\#\//g" $SPEC_PATH >"$paths_file"
# yq e 'del(.components)' -i "$paths_file" # dont delete since recent oapi-codegen does some checks even if we are not generating types
go build -o $BUILD_DIR/oapi-codegen cmd/oapi-codegen/main.go || mark_failed_tool_build # templates are embedded, required rebuild
mapfile -t exclude_schemas_arr < <(yq e '.components.schemas[] | select(.x-oapi-ignore == true) | key' $SPEC_PATH)
exclude_schemas=$(printf ",\"%s\"" "${exclude_schemas_arr[@]}")
exclude_schemas="[${exclude_schemas:1}]"
local models_config=$(
cat <<EOF
package: models
generate:
models: true
embedded-spec: true
mode: models
output: internal/repos/postgresql/gen/models/openapi_types.gen.go
compatibility:
always-prefix-enum-values: true
output-options:
skip-prune: true
exclude-schemas: $exclude_schemas
EOF
)
local server_config=$(
cat <<EOF
package: rest
generate:
gin-server: true
strict-server: true
embedded-spec: true
output: internal/rest/openapi_server.gen.go
mode: server
exclude-rest-types: true
skip-discriminator-utils: true
is-rest-server-gen: true
import-mapping:
"openapi.yaml": github.com/danicc097/openapi-go-gin-postgres-sqlc/internal/repos/postgresql/gen/models
# additional-imports:
# - alias: .
# package: github.com/danicc097/openapi-go-gin-postgres-sqlc/internal/models
output-options:
skip-prune: true
compatibility:
always-prefix-enum-values: true
EOF
)
local test_client_config=$(
cat <<EOF
package: resttesting
generate:
client: true
output: internal/rest/resttesting/openapi_client_gen.go
test-client: true
additional-imports:
- alias: .
package: github.com/danicc097/openapi-go-gin-postgres-sqlc/internal/repos/postgresql/gen/models
- alias: models
package: github.com/danicc097/openapi-go-gin-postgres-sqlc/internal/repos/postgresql/gen/models
EOF
)
# IMPORTANT: additional-imports packages affect x-go extensions
# see https://github.com/oapi-codegen/oapi-codegen?tab=readme-ov-file#openapi-extensions
# TODO: we already have structs.gen.go indexed by "Models(models struct)" or plain rest type...
# however this might be faster if the build is cached (templates unchanged). could construct internally as map set anyway
oapi-codegen --config <(echo "$models_config") --types "$rest_types_list" "$SPEC_PATH" || err "Failed types generation" &
oapi-codegen --config <(echo "$server_config") --spec-rest-types "$spec_rest_types_list" --types "$rest_types_list" "$paths_file" || err "Failed server generation" &
oapi-codegen --config <(echo "$test_client_config") --types "$rest_types_list" --spec-rest-types "$spec_rest_types_list" "$SPEC_PATH" || err "Failed client generation" &
# not used now. may be useful for a cli at some point
# oapi-codegen --config internal/client/oapi-codegen-client.yaml "$SPEC_PATH" || err "Failed client generation" &
wait_without_error
# TODO: remove once x-go-type in use for all db types.
# models gen cannot be done if we have x-go-type...
# sed -i 's/ \*Models\([A-Z]\)/ \*db\.\1/g; s/\[\]Models\([A-Z]\)/\[\]db\.\1/g; s/ Models\([A-Z]\)/ db\.\1/g; s/ \(\(externalRef0\.\)\?Models\)\([A-Z]\)/ db\.\3/g' internal/rest/openapi_server.gen.go
# sed -i 's/ \*Models\([A-Z]\)/ \*db\.\1/g; s/\[\]Models\([A-Z]\)/\[\]db\.\1/g; s/ Models\([A-Z]\)/ db\.\1/g; s/ \(\(externalRef0\.\)\?Models\)\([A-Z]\)/ db\.\3/g' internal/rest/resttesting/openapi_client_gen.go
# db already imports models pkg
# sed -i 's/ \*Models\([A-Z]\)/ \*db\.\1/g; s/\[\]Models\([A-Z]\)/\[\]db\.\1/g; s/ Models\([A-Z]\)/ db\.\1/g; s/ \(\(externalRef0\.\)\?Models\)\([A-Z]\)/ db\.\3/g' internal/repos/postgresql/gen/models/openapi_types.gen.go
# ast-parser find-redeclared --delete "$REST_MODELS" # for duplicates in rest. depends on oapi-codegen output
codegen implement-server # depends on oapi-codegen output
files=$(find "internal/rest/" -name "api_*[^_test].go" -o -name "openapi_*.go")
goimports -w $files
gofumpt -w $files