From a563cc4c22a6cb371372db827a888ef952d0c540 Mon Sep 17 00:00:00 2001 From: Olaoluwa Osuntokun Date: Mon, 11 Nov 2024 17:36:02 -0800 Subject: [PATCH] scripts: use `trap` to make sure old files always restored In this commit, we fix an issue I observed on my machine after updating many command line/dev utilities. I observed that if the script failed for w/e reason, then the old files weren't properly restored. The repro on my machine is something like: 1. Shutdown docker, make sure the daemon isn't accessible. 2. Run `mac sqlc`. The script should fail. 3. Observe that the files in your local working tree are still altered. We fix this by using the `trap` command, [which is basically like Go's `defer`, but for bash scripts](https://tldp.org/LDP/Bash-Beginners-Guide/html/sect_12_02.html)! --- scripts/gen_sqlc_docker.sh | 43 ++++++++++++++++++++++---------------- 1 file changed, 25 insertions(+), 18 deletions(-) diff --git a/scripts/gen_sqlc_docker.sh b/scripts/gen_sqlc_docker.sh index 726a2c0b6..f63b3b108 100755 --- a/scripts/gen_sqlc_docker.sh +++ b/scripts/gen_sqlc_docker.sh @@ -2,11 +2,23 @@ set -e +# restore_files is a function to restore original schema files. +restore_files() { + echo "Restoring SQLite bigint patch..." + for file in tapdb/sqlc/migrations/*.up.sql.bak; do + mv "$file" "${file%.bak}" + done +} + +# Set trap to call restore_files on script exit. This makes sure the old files +# are always restored. +trap restore_files EXIT + # Directory of the script file, independent of where it's called from. -DIR="$(cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd)" +DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" # Use the user's cache directories -GOCACHE=`go env GOCACHE` -GOMODCACHE=`go env GOMODCACHE` +GOCACHE=$(go env GOCACHE) +GOMODCACHE=$(go env GOMODCACHE) # SQLite doesn't support "BIGINT PRIMARY KEY" for auto-incrementing primary # keys, only "INTEGER PRIMARY KEY". Internally it uses 64-bit integers for @@ -19,23 +31,18 @@ GOMODCACHE=`go env GOMODCACHE` # PRIMARY KEY". echo "Applying SQLite bigint patch..." for file in tapdb/sqlc/migrations/*.up.sql; do - echo "Patching $file" - sed -i.bak -E 's/INTEGER PRIMARY KEY/BIGINT PRIMARY KEY/g' "$file" + echo "Patching $file" + sed -i.bak -E 's/INTEGER PRIMARY KEY/BIGINT PRIMARY KEY/g' "$file" done - echo "Generating sql models and queries in go..." +# Run the script to generate the new generated code. Once the script exits, we +# use `trap` to make sure all files are restored. docker run \ - --rm \ - --user "$UID:$(id -g)" \ - -e UID=$UID \ - -v "$DIR/../:/build" \ - -w /build \ - sqlc/sqlc:1.25.0 generate - -# Restore the original schema files. -echo "Restoring SQLite bigint patch..." -for file in tapdb/sqlc/migrations/*.up.sql.bak; do - mv "$file" "${file%.bak}" -done + --rm \ + --user "$UID:$(id -g)" \ + -e UID=$UID \ + -v "$DIR/../:/build" \ + -w /build \ + sqlc/sqlc:1.25.0 generate