json - 从 .gitlab-ci.yml 中的 JSON 中提取徽章 ID
问题描述
我在 gitlab 有一个示例项目,我想在其中获取.gitlab-ci.yml
via 脚本中最后一个徽章的 ID。我将所有徽章的概述作为 json。有没有办法获得最后一个元素的“id”?
目前,我正在为每个项目从jsonPYLINT_BADGE_ID
手动设置自定义 CI 变量。在本例中为 37777。如何通过命令行自动执行此操作?
细节:
我正在尝试解决这个问题:Pylint badge in gitlab。但他们使用 gitlab pages、anybadge、artifacts 和 readme 来显示徽章(不在标准徽章区域中)。以下方式感觉更苗条:
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
解决方案
经过几个小时的正则表达式转义后,我将其添加到我的.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.svg
json 中查找的正则表达式中元素的顺序,该顺序需要在徽章 ID 之前。
推荐阅读
- javascript - 从
使用 javascript 和 puppeteer - unity3d - 禁用 Unity 2D 对象的碰撞
- c++ - 在线程之间共享 udp 套接字
- windows - 如何修复真正的 vnc 查看器中的黑屏问题?
- python - 在python中使用带有or的if语句时为什么会忽略条件
- mongodb - Mongoose Geo Near Search - 如何在给定距离内排序?
- rust - Rust:在`impl std::future::Future`中找不到方法“poll”
- html - 按下删除按钮后,我的购物车没有删除物品
- jenkins - 无法在“通过 SSH 发送文件或执行命令”上执行 sudo 命令
- java - Navigation Drawer android:登录或注销时使用不同的headerlayout xml