【问题标题】:How to capture a curl http status code in a GitHub Action to determine success/failure?如何在 GitHub Action 中捕获 curl http 状态代码以确定成功/失败?
【发布时间】:2021-04-20 01:26:06
【问题描述】:

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

这是我的 curl 调用:

- 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 }}"
           }'

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

TIA。

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

【问题讨论】:

    标签: github curl github-actions


    【解决方案1】:

    此答案与您的 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
    

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

    前:

    if curl "..."
    then echo "SUCCESS"
    else echo "FAILURE"
    fi
    

    【讨论】:

      猜你喜欢
      • 2021-11-26
      • 1970-01-01
      • 2018-01-01
      • 2018-11-05
      • 2022-06-23
      • 2020-07-18
      • 2020-11-12
      • 2019-08-28
      • 2019-09-18
      相关资源
      最近更新 更多