首页 > 解决方案 > 从 .gitlab-ci.yml 中的 JSON 中提取徽章 ID

问题描述

我在 gitlab 有一个示例项目,我想在其中获取.gitlab-ci.ymlvia 脚本中最后一个徽章的 ID。我将所有徽章的概述作为 json。有没有办法获得最后一个元素的“id”?

目前,我正在为每个项目从jsonPYLINT_BADGE_ID手动设置自定义 CI 变量。在本例中为 37777。如何通过命令行自动执行此操作?

细节:

我正在尝试解决这个问题:Pylint badge in gitlab。但他们使用 gitlab pages、anybadge、artifacts 和 readme 来显示徽章(不在标准徽章区域中)。以下方式感觉更苗条:

这是我正在使用的 .gitlab-ci.yml

lint:
  script:
  - python -m pip install setuptools
  - python -m pip install pylint pylint-exit
  - pylint src/*.py | tee pylint.txt || pylint-exit $?
  - score=$(sed -n 's/^Your code has been rated at \([-0-9.]*\)\/.*/\1/p' pylint.txt)
  - echo "Pylint score was $score"
  # To check your badge ID go to https://gitlab.com/api/v4/projects/43126475/badges
  # and insert your $CI_PROJECT_ID. Must be a quite high number!
  # Would be great to automate this!
  - badge_url=https://img.shields.io/badge/lint%20score-$score-blue.svg
  - >-
        curl https://gitlab.com/api/v4/projects/$CI_PROJECT_ID/badges/$PYLINT_BADGE_ID
        -X PUT
        -H "PRIVATE-TOKEN: $API_TOKEN"
        -H "Content-Type: application/json"
        -d '{"image_url": "'"$badge_url"'"}'

  artifacts:
    paths:
      - pylint.txt

标签: jsongitlab-cigitlab-ci-runner

解决方案


经过几个小时的正则表达式转义后,我将其添加到我的.gitlab-ci.yml

  - json_badge_info=$(curl -H "PRIVATE-TOKEN:$API_TOKEN" -X GET https://gitlab.com/api/v4/projects/$CI_PROJECT_ID/badges)
  - pylint_badge_id=$(expr match "$json_badge_info" '.*https[^"]*-blue\.svg\",\"id\":\([0-9]\+\),')

所以整个舞台是这样的:

lint:
  stage: unittest-lint

  script:
  - python -m pip install setuptools pylint pylint-exit
  - pylint src/*.py | tee pylint.txt || pylint-exit $?
  - score=$(sed -n 's/^Your code has been rated at \([-0-9.]*\)\/.*/\1/p' pylint.txt)
  - echo "Pylint score was $score"

  # get the json with all badge urls via API and regex the id of the badge with 'blue.svg' in it
  - json_badge_info=$(curl -H "PRIVATE-TOKEN:$API_TOKEN" -X GET https://gitlab.com/api/v4/projects/$CI_PROJECT_ID/badges)
  - pylint_badge_id=$(expr match "$json_badge_info" '.*https[^"]*-blue\.svg\",\"id\":\([0-9]\+\),')
  - echo $pylint_badge_id

  - badge_url=https://img.shields.io/badge/lint%20score-$score-blue.svg
  - >-
        curl https://gitlab.com/api/v4/projects/$CI_PROJECT_ID/badges/$pylint_badge_id
        -X PUT
        -H "PRIVATE-TOKEN: $API_TOKEN"
        -H "Content-Type: application/json"
        -d '{"image_url": "'"$badge_url"'"}'

  artifacts:
    paths:
      - pylint.txt

此解决方案取决于在-blue.svgjson 中查找的正则表达式中元素的顺序,该顺序需要在徽章 ID 之前。


推荐阅读