如何获取合并到main分支的最后一个PR的标题?
获取GitHub Actions合并PR到main后的PR标题并自定义run-name
场景说明
你当前的run-name配置在PR触发时正常,但合并PR到main的push事件中,github.event.pull_request.title为空——因为push事件上下文不包含PR信息。以下是几种可行的解决方案:
方法1:解析squash合并的提交消息(简单高效)
如果你的团队使用squash合并PR,合并后的提交消息默认格式为PR标题 (#PR编号),可以直接用GitHub Actions表达式提取标题:
run-name: ${{ github.event.pull_request.title || (contains(github.event.head_commit.message, '#') ? substringBefore(github.event.head_commit.message, ' (#') : github.event.head_commit.message) }} (Run-Id ${{ github.run_id }})
- PR触发时:直接调用
github.event.pull_request.title - squash合并到main时:从提交消息中截取标题(自动去掉末尾的
(#XXX)后缀) - 普通push(非PR合并):使用提交消息作为名称
方法2:通过PR合并事件触发(通用场景)
修改工作流触发条件,新增PR合并完成的事件,直接从PR上下文中获取标题:
1. 更新触发条件
on: # 保留原有的push和PR触发 push: branches: [main] pull_request: branches: [main] # 新增PR合并完成的触发事件 pull_request_target: types: [closed] branches: [main]
2. 动态设置run-name
在工作流中添加步骤,根据事件类型设置对应的run-name:
jobs: build: runs-on: ubuntu-latest steps: # PR合并完成时设置run-name - name: Set run name for merged PR if: github.event_name == 'pull_request_target' && github.event.pull_request.merged == true run: | echo "GITHUB_RUN_NAME=${{ github.event.pull_request.title }} (PR-${{ github.event.pull_request.number }}) (Run-Id ${{ github.run_id }})" >> $GITHUB_ENV # 普通push到main时设置run-name - name: Set run name for normal push if: github.event_name == 'push' run: | echo "GITHUB_RUN_NAME=${{ github.event.head_commit.message }} (Run-Id ${{ github.run_id }})" >> $GITHUB_ENV # 你的构建步骤(如安装依赖、编译等) - name: Build project run: | # 这里写你的构建命令
这种方式覆盖所有场景:PR触发、PR合并、普通push,都能正确显示带Run-Id的名称。
方法3:用GitHub CLI查询关联PR(无需修改触发条件)
如果工作流有仓库读写权限,可通过GitHub CLI根据提交SHA查询关联的PR,动态获取标题:
jobs: build: runs-on: ubuntu-latest steps: - name: Checkout code uses: actions/checkout@v4 with: fetch-depth: 0 # 需要拉取完整提交历史 # 查询当前提交关联的PR并设置run-name - name: Get PR info for merged commit if: github.event_name == 'push' run: | # 查询提交关联的PR编号 PR_NUMBER=$(gh pr view --json number --jq '.number' ${{ github.sha }}) if [ -n "$PR_NUMBER" ]; then # 获取PR标题 PR_TITLE=$(gh pr view $PR_NUMBER --json title --jq '.title') echo "GITHUB_RUN_NAME=${PR_TITLE} (PR-${PR_NUMBER}) (Run-Id ${{ github.run_id }})" >> $GITHUB_ENV else # 无关联PR时用提交消息 echo "GITHUB_RUN_NAME=${{ github.event.head_commit.message }} (Run-Id ${{ github.run_id }})" >> $GITHUB_ENV fi env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} # 默认提供的仓库权限令牌 # 你的构建步骤 - name: Build project run: | # 构建命令
这个方法不需要调整触发条件,自动适配所有合并方式(squash、merge、rebase)。
内容的提问来源于stack exchange,提问作者g0np
相关产品推荐
相关产品推荐

