如何在gitlab项目的分支中获取最后的提交状态?

时间:2017-03-28 16:33:09

标签: git gitlab gitlab-ci gitlab-api

我在gitlab中有很多项目。对于每个项目,我在每个gitlab项目中都有'n'个分支。我需要知道使用gitlab API最后一次提交分支的状态是成功还是失败。我已经提到了以下链接

https://docs.gitlab.com/ce/api/pipelines.html

https://gitlab.com/gitlab-org/gitlab-ce/issues/20277

但是我无法获得最后一个分支提交细节。有人可以帮我这个吗?

1 个答案:

答案 0 :(得分:2)

您可以使用Gitlab API执行此操作:

使用bash jq,您可以执行以下操作:

#!/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"