如何通过GitHub Pull Request触发semantic-release预查发布版本?
解决semantic-release在PR中Dry Run失败的问题
问题原因
你遇到的报错是因为semantic-release会校验当前运行的分支是否在允许发布的分支列表中。在PR触发的GitHub Action里,GITHUB_REF的值是refs/pull/23/merge(合并临时分支),而你通过--branches指定的dry-run/${GITHUB_REF}是无效分支名,且当前实际运行分支和指定分支不匹配,导致semantic-release判定不允许发布。
解决方案
不需要创建额外的dry-run分支,直接利用PR的源分支信息配置semantic-release即可,以下是两种可行方案:
方案1:允许所有分支运行Dry Run
通过--branches '*'跳过分支校验,让semantic-release直接分析当前PR的代码:
name: Version Identification on: pull_request: branches: - '**' jobs: dry_run_release: name: Dry Release runs-on: ubuntu-latest permissions: contents: write issues: write pull-requests: write steps: - name: Checkout uses: actions/checkout@v3 with: fetch-depth: 0 # 拉取完整提交历史,semantic-release需要用来分析版本 - name: Setup Node.js uses: actions/setup-node@v3 with: node-version: "lts/*" - name: Install dependencies run: | npm install -g semantic-release conventional-changelog-conventionalcommits - name: Run Semantic Release with Dry Run env: GITHUB_TOKEN: ${{ secrets.ACCESS_TOKEN }} run: | npx semantic-release --branches '*' --no-ci --dry-run > .semver-output cat .semver-output # 提取预期版本号,根据实际输出调整切割逻辑 export DRY_VERSION=$(cat .semver-output | grep "Published release" | awk '{print $9}') echo "DRY_VERSION=$DRY_VERSION" >> $GITHUB_ENV echo "The next release version would be $DRY_VERSION"
方案2:指定PR的源分支运行
利用PR触发时的GITHUB_HEAD_REF环境变量(代表PR的源分支,比如feat/pr-comment),精准指定允许运行的分支:
name: Version Identification on: pull_request: branches: - '**' jobs: dry_run_release: name: Dry Release runs-on: ubuntu-latest permissions: contents: write issues: write pull-requests: write steps: - name: Checkout uses: actions/checkout@v3 with: fetch-depth: 0 - name: Setup Node.js uses: actions/setup-node@v3 with: node-version: "lts/*" - name: Install dependencies run: | npm install -g semantic-release conventional-changelog-conventionalcommits - name: Run Semantic Release with Dry Run env: GITHUB_TOKEN: ${{ secrets.ACCESS_TOKEN }} run: | # 获取PR的源分支名 PR_SOURCE_BRANCH="${GITHUB_HEAD_REF}" npx semantic-release --branches "${PR_SOURCE_BRANCH}" --no-ci --dry-run > .semver-output cat .semver-output export DRY_VERSION=$(cat .semver-output | grep "Published release" | awk '{print $9}') echo "DRY_VERSION=$DRY_VERSION" >> $GITHUB_ENV echo "The next release version would be $DRY_VERSION"
关键注意事项
- 必须添加
fetch-depth: 0到actions/checkout步骤,确保拉取完整的Git提交历史,semantic-release需要这些历史来计算版本号。 - 如果你的semantic-release有自定义分支配置(比如在
.releaserc文件中),需要确保命令行的--branches参数能覆盖或匹配配置中的分支规则。 - 提取版本号的逻辑可能需要根据semantic-release的实际输出调整,比如预发布版本的输出格式可能略有不同。
内容的提问来源于stack exchange,提问作者kbenda
相关产品推荐
相关产品推荐

