如何在 GitHub Action 中捕获curl http状态代码以确定成功/失败?

kfr*_*anz 6 curl github github-actions

我对 GitHub Actions 非常陌生,所以请耐心等待...我正在尝试创建一个 GitHub Action,其中步骤之一是对 GitHub API 进行curl 调用。我想捕获该curl 调用的HTTP 状态代码,以确定该操作是否确实失败。现在,因为curl 成功完成,所以它总是返回成功运行,即使curl 响应可能有错误的状态代码(例如405、404、403 等)。

这是我的卷曲调用:

- name: Squash And Merge After Approval of PR
        run: |
          curl --request PUT \
          --header 'authorization: Bearer ${{ secrets.GITHUB_TOKEN }}' \
          --header 'content-type: application/json' \
          --url https://api.github.com/repos/${{ github.repository }}/pulls/${{ github.event.inputs.pr_num }}/merge \
          --data '{
           "merge_method": "squash",
           "commit_title": "Squash and Merge for Pull Request ${{ github.event.inputs.pr_num }}",
           "commit_message": "expected sha value = ${{ github.event.inputs.pr_head_sha }}",
           "sha":"${{ github.event.inputs.pr_head_sha }}"
           }'
Run Code Online (Sandbox Code Playgroud)

我想我必须以某种方式包装我的curl 命令才能在变量中输出响应,或者?但我不知道如何捕获curl响应,解析它,并检查状态代码以确定curl是否成功。

TIA。

PS:这是一个手动运行的操作,因此当操作运行时,我从输入表单中提供“sha”和“pr 编号”。

dua*_*ity 5

这个答案与你的curl问题有关——一种可以将代码响应捕获为字符串的方法。

CODE=`curl --write-out '%{http_code}' \
    --silent \
    --output /dev/null \
    --request PUT \
    --header 'authorization: Bearer ${{ secrets.GITHUB_TOKEN }}' \
    --header 'content-type: application/json' \
    --url 'https://api.github.com/repos/${{ github.repository }}/pulls/${{ github.event.inputs.pr_num }}/merge' \
    --data '{ \
    "merge_method": "squash", \
    "commit_title": "Squash and Merge for Pull Request ${{ github.event.inputs.pr_num }}", \
    "commit_message": "expected sha value = ${{ github.event.inputs.pr_head_sha }}", \
    "sha":"${{ github.event.inputs.pr_head_sha }}" \
    }'`

if [ $CODE!="200" ] 
then
    echo "FAILURE"
else
    echo "SUCCESS"
fi
Run Code Online (Sandbox Code Playgroud)

但是,如果请求失败,curl 命令应返回失败代码

前任:

if curl "..."
then echo "SUCCESS"
else echo "FAILURE"
fi
Run Code Online (Sandbox Code Playgroud)