如何在GitHub Actions工作流中获取PR关联的Git提交以更新版本?
解决GitHub Actions中获取PR合并提交记录的问题
核心问题原因
使用pull_request_target事件时,github.event.commits为空是因为该事件默认不携带提交列表;另外你直接写github.event.commits作为参数不会被GitHub Actions解析,必须用表达式语法${{ ... }}包裹上下文变量。
可行解决方案
方案1:通过GitHub API拉取PR提交记录
借助GitHub API获取PR的完整提交列表,需要用GITHUB_TOKEN做授权:
- 修改工作流步骤,传递PR编号和token给脚本:
- name: Run version update script run: node ./shell-scripts/update-version.js ${{ github.event.pull_request.number }} ${{ secrets.GITHUB_TOKEN }}
- 在Node.js脚本中发起API请求:
const [prNumber, token] = process.argv.slice(2); const apiUrl = `https://api.github.com/repos/${process.env.GITHUB_REPOSITORY}/pulls/${prNumber}/commits`; async function fetchCommits() { const response = await fetch(apiUrl, { headers: { 'Authorization': `token ${token}`, 'Accept': 'application/vnd.github.v3+json' } }); const commits = await response.json(); // 提交数组结构示例:每个元素包含sha、commit.message、commit.author等字段 // 后续可遍历message,匹配Fix/feat等关键词处理版本更新 } fetchCommits();
方案2:通过Git命令获取提交差异
拉取完整仓库历史后,对比PR基准分支与头部分支的提交:
- 修改checkout步骤,拉取全量历史:
- name: Checkout code with full history uses: actions/checkout@v4 with: fetch-depth: 0 ref: ${{ github.event.pull_request.base.ref }}
- 拉取PR头部分支并导出提交信息:
- name: Fetch PR head branch run: git fetch origin ${{ github.event.pull_request.head.ref }}:pr-head - name: Export PR commit messages run: git log --pretty=format:"%s" ${{ github.event.pull_request.base.ref }}..pr-head > commits.txt
- 在脚本中读取文件处理提交信息:
const fs = require('fs'); const commitMessages = fs.readFileSync('./commits.txt', 'utf8').split('\n').filter(Boolean); // 遍历commitMessages,匹配关键词更新版本号
关键注意点
- 所有GitHub上下文变量必须用
${{ }}包裹,否则会被当作普通字符串传递。 - 使用Git命令时,
fetch-depth: 0是必须的,默认checkout仅拉取最新一次提交,无法对比历史差异。 GITHUB_TOKEN拥有仓库默认权限,足够用于拉取PR提交记录的API请求。
内容的提问来源于stack exchange,提问作者ezg
相关产品推荐
相关产品推荐

