Reputation: 585
I need to determine the latest commit status of each of my GitLab projects' branches using the GitLab API.
I have referred to these links but I could not get the last commit's status details.
Upvotes: 4
Views: 4809
Reputation: 45352
You can use Gitlab API to do this :
With bash an jq, you can do the following :
#!/bin/bash
# edit this if needed
GITLAB_DOMAIN=gitlab.com
GITLAB_PORT=443
GITLAB_BASE_URL=https://$GITLAB_DOMAIN:$GITLAB_PORT
PER_PAGE=1000
# edit this
PRIVATE_TOKEN=YOUR_PRIVATE_TOKEN
echo "GET /projects"
projects=$(curl -s "$GITLAB_BASE_URL/api/v4/projects?private_token=$PRIVATE_TOKEN&page=1&per_page=$PER_PAGE" | \
jq -r '. | map([.name, .id|tostring ] | join("|")) | join("\n")')
echo "$projects"
while read -r project; do
IFS='|' read -ra project_t <<< "$project"
# project name : ${project_t[0]}
# project id : ${project_t[1]}
echo "GET /projects/${project_t[1]}/repository/branches for project ${project_t[0]}"
commits=$(curl -s "$GITLAB_BASE_URL/api/v4/projects/${project_t[1]}/repository/branches?private_token=$PRIVATE_TOKEN&page=1&per_page=$PER_PAGE" | \
jq -r '. | map([ .name , .commit.id|tostring ] | join("|")) | join("\n")')
while read -r commit; do
IFS='|' read -ra commits_t <<< "$commit"
# branch name : ${commits_t[0]}
# last commit sha for this branch : ${commits_t[1]}
echo "GET /projects/${project_t[1]}/repository/commits/${commits_t[1]}/statuses"
statuses=$(curl -s "$GITLAB_BASE_URL/api/v4/projects/${project_t[1]}/repository/commits/${commits_t[1]}/statuses?private_token=$PRIVATE_TOKEN" | \
jq -r '. | map([.status, .name] | join("|")) | join("\n")')
if [ ! -z "$statuses" ]; then
while read -r status; do
IFS='|' read -ra status_t <<< "$status"
# status value : ${status_t[0]}
# status name : ${status_t[1]}
echo "[PROJECT ${project_t[0]}] [BRANCH ${commits_t[0]}] [COMMIT ${commits_t[1]}] [STATUS ${status_t[1]}] : ${status_t[0]}"
done <<< "$statuses"
else
echo "[PROJECT ${project_t[0]}] [BRANCH ${commits_t[0]}] [COMMIT ${commits_t[1]}] : no status found"
fi
done <<< "$commits"
echo "------"
done <<< "$projects"
Upvotes: 2