为了避免在其他操作仍在进程中时错误地合并PR,我们需要使用Github Action中的条件检查。具体来说,我们需要在Workflow文件中添加一个on条件,以检测PR的状态,只有在PR被打开但没有被merge时才允许workflow继续执行。这可以通过以下示例代码来实现:
name: Github Action to Build and Test PR
on:
pull_request:
types: [opened, synchronize, reopened]
jobs:
test:
runs-on: ubuntu-latest
steps:
- name: Check if PR is mergeable
run: |
if [[ "$(curl -s -H "Authorization: Bearer $GITHUB_TOKEN" \
-H "Content-Type: application/vnd.github.v3+json" \
-X GET $GITHUB_API_URL/pulls/$PR_NUMBER | jq '.mergeable')" == "null" ]]; then
# If mergeable is null, this means there is a merge conflict
echo "::error:: PR has merge conflicts, cannot merge"
exit 1
elif [[ "$(curl -s -H "Authorization: Bearer $GITHUB_TOKEN" \
-H "Content-Type: application/vnd.github.v3+json" \
-X GET $GITHUB_API_URL/pulls/$PR_NUMBER | jq '.mergeable')" == "false" ]]; then
# If mergeable is false, this means there are failing checks
echo "::error:: PR has failing checks, cannot merge"
exit 1
fi
- name: Run tests
run: pytest
在上述代码中,我们使用了环境变量$PR_NUMBER
和$GITHUB_API_URL
,需要在Workflow运行时推送这个环境变量,以指定要检查的PR和Github API的url。如果PR有合并冲突或失败的检查,则Workflow将失败并打印出错误信息。如果没有任何问题,Workflow将继续构建和测试PR。