Overview
This article discussed how to retrieve the last successfully built commit for a branch using CircleCI. We provided a code snippet that utilizes the CircleCI API to fetch the necessary information.
Introduction
In software development, it is crucial to keep track of the last successfully built commit for a specific branch. This information helps developers identify the stable version of the codebase and ensures that any subsequent changes are built upon a reliable foundation. In this article, we will explore how to retrieve the last successfully built commit for a branch using CircleCI.
Prerequisites
Before we dive into the code, make sure you have the following requirements in place:
Builds needs to be triggered and the branch should have some builds in the list.
A personal access token from CircleCI (referred to as
CIRCLECI_PERSONAL_TOKEN
in the code)Solution
To obtain the last successfully built commit for a branch, please use the following script and set the organization name (
org_name
), project name (prj_name
), and branch name (branch_name
) variables to specify the desired branch.org_name='circleci'
prj_name='project'
branch_name='main'
# Make an initial request to the CircleCI API to retrieve the pipeline information for the specified branch.
pip=$(curl -s -H "Circle-Token: ${CIRCLECI_PERSONAL_TOKEN}" "https://circleci.com/api/v2/project/gh/${org_name}/${prj_name}/pipeline?branch=${branch_name}")
# Extract the pipeline IDs and their corresponding commit revisions
pipeline_ids=$(echo $pip | jq -r '.items[] | {"id": .id, "revision": .vcs.revision}' )
echo ${pipeline_ids} | jq -c '.' | while read pip; do
pip_id=$(echo $pip | jq -r '.id')
pip_sha=$(echo $pip | jq -r '.revision')
workflow=$(curl -H "Circle-Token: ${CIRCLECI_PERSONAL_TOKEN}" https://circleci.com/api/v2/pipeline/$pip_id/workflow)
# Check if any workflow item has a status of "success"
result=$(echo $workflow | jq -r '.items[] | select(.status == "success")')
# If a successful status is found, print the commit SHA and exit the loop. Otherwise, indicate that a successful status was not found.
if [[ -n "$result" ]]; then
echo "Successful status found. commit sha: $pip_sha"
break
else
echo "Successful status not found."
fi
done
Retrieving the last successfully built commit for a branch is essential for maintaining a stable codebase and ensuring reliable software releases. By using the CircleCI API and the provided code snippet, you can easily obtain this information. Remember to replace the placeholders in the code with your own organization, project, and personal access token.
Comments
Article is closed for comments.