Monday, January 10, 2022

Print Git History Changes in Google Cloud Build


 


In previous posts we have reviewed how to use google cloud build, and how to manage dependencies of multiple build triggers. In this post we will review how can we print the list of git changes since the last successful build.

Our build is running a shell, using the predefined google builder image, and is running a shell file. We send the current build git hash as an argument to the shell. Hence the trigger configuration is the following:


name: build

triggerTemplate:
branchName: .*
projectId: my-project
repoName: my-repo

build:
timeout: 3600s
steps:
- id: main
name: gcr.io/cloud-builders/gcloud
entrypoint: bash
timeout: 3600s
args:
- /build.sh
- ${BRANCH_NAME}
- ${COMMIT_SHA}
- ${SHORT_SHA}



The build.sh file gets the arguments:



branchName=$1
commitSha=$2
shortSha=$3



and includes the following:



shaFile="${branchName}_git_commit.sha"


function printGitLog() {
set +e
gsutil -q stat gs://my-google-storge-bucket/${shaFile}
rc=$?
set -e
if [[ "${rc}" == "0" ]]; then
echo "=== changes from last successful build ==="
gsutil cp gs://my-google-storge-bucket/${shaFile} ./${shaFile}
prevSha=`cat ${shaFile}`
git fetch --depth=100

# do not fail the build if we cannot find the range in the last 100 commits
set +e
git log ${prevSha}..${commitSha}
set -e
echo "=========================================="
else
echo "no previous sha file"
fi
}

function saveGitSha() {
echo "Saving build sha to GCP storage"
echo ${commitSha} > ${shaFile}_temp
tr -d '\t\n ' < ${shaFile}_temp > ${shaFile}
rm -f ${shaFile}_temp

gsutil cp ${shaFile} gs://my-google-storge-bucket
}



We should call the saveGitSha function upon successful build. This would save the build hash to a file in google storage (you should manually create this folder in google storage). 

Also, upon build start we call to printGitLog, which retrieve the last successful hash from the folder in the google storage, fetches the git history, and then prints the changes between the current build hash to the last successful hash.




No comments:

Post a Comment