From efe12456877866efad198c12c5674ecbeb14678a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Chris=20Suszy=C5=84ski?= Date: Wed, 3 Jul 2024 19:21:15 +0200 Subject: [PATCH] Better clean up of codegen --- codegen-library.sh | 24 +++++++++++++++++++++--- library.sh | 12 ++++++------ 2 files changed, 27 insertions(+), 9 deletions(-) diff --git a/codegen-library.sh b/codegen-library.sh index c3cb80a9..623c40b2 100755 --- a/codegen-library.sh +++ b/codegen-library.sh @@ -22,7 +22,7 @@ oldstate="$(set +o)" set -Eeuo pipefail export repodir kn_hack_dir kn_hack_library \ - MODULE_NAME GOPATH GOBIN \ + MODULE_NAME TMP_GOPATH GOPATH GOBIN \ CODEGEN_PKG KNATIVE_CODEGEN_PKG kn_hack_dir="$(realpath "$(dirname "${BASH_SOURCE[0]:-$0}")")" @@ -67,7 +67,8 @@ if ! KNATIVE_CODEGEN_PKG="${KNATIVE_CODEGEN_PKG:-"$(go-resolve-pkg-dir knative.d fi popd > /dev/null -GOPATH=$(go_mod_gopath_hack) +TMP_GOPATH=$(go_mod_gopath_hack) +GOPATH="${TMP_GOPATH}" GOBIN="${GOPATH}/bin" # Set GOBIN explicitly as k8s-gen' are installed by go install. if [[ -n "${CODEGEN_PKG}" ]] && ! [ -x "${CODEGEN_PKG}/generate-groups.sh" ]; then @@ -119,8 +120,14 @@ function generate-knative() { --go-header-file "$(boilerplate)" } -# Cleanup generated code if it differs only in the boilerplate year +# Cleanup after generating code function cleanup-codegen() { + restore-changes-if-its-copyright-year-only + restore-gopath +} + +# Restore changes if the file contains only the change in the copyright year +function restore-changes-if-its-copyright-year-only() { local difflist log "Cleaning up generated code" difflist="$(mktemp)" @@ -137,6 +144,17 @@ function cleanup-codegen() { rm -f "$difflist" } +# Restore the GOPATH and clean up the temporary directory +function restore-gopath() { + if [ -n "$TMP_GOPATH" ] && [ -d "$TMP_GOPATH" ]; then + chmod -R u+w "${TMP_GOPATH}" + rm -rf "${TMP_GOPATH}" + unset TMP_GOPATH + fi + unset GOBIN + unset GOPATH +} + add_trap cleanup-codegen EXIT # Restore Bash options diff --git a/library.sh b/library.sh index 1d131dba..798abc27 100755 --- a/library.sh +++ b/library.sh @@ -827,19 +827,19 @@ function go_mod_module_name() { # Intended to be used like: # export GOPATH=$(go_mod_gopath_hack) function go_mod_gopath_hack() { - # Skip this if the directory is already checked out onto the GOPATH. - if [[ "${REPO_ROOT_DIR##$(go env GOPATH)}" != "$REPO_ROOT_DIR" ]]; then + # Skip this if the directory is already checked out onto the GOPATH. + if ! [ "${REPO_ROOT_DIR##"$(go env GOPATH)"}" = "$REPO_ROOT_DIR" ]; then go env GOPATH return fi - local TMP_DIR TMP_REPO_PATH - TMP_DIR="$TMPDIR/go" - TMP_REPO_PATH="${TMP_DIR}/src/$(go_mod_module_name)" + local TMP_GOPATH TMP_REPO_PATH + TMP_GOPATH="$TMPDIR/go" + TMP_REPO_PATH="${TMP_GOPATH}/src/$(go_mod_module_name)" mkdir -p "$(dirname "${TMP_REPO_PATH}")" ln -s "${REPO_ROOT_DIR}" "${TMP_REPO_PATH}" - echo "${TMP_DIR}" + echo "${TMP_GOPATH}" } # Run kntest tool