使用GitHub Actions构建NX Monorepo时出现fatal: No such ref错误
解决NX Monorepo GitHub Actions构建中
fatal: No such ref: <COMMIT_HASH>错误的思路 1. 修复仓库缓存对Git目录的覆盖
你配置的Restore repository from cache步骤会缓存除node_modules外的所有文件,这包含.git目录。如果缓存中的.git目录不包含NX需要的提交哈希,就会触发找不到ref的错误。
调整该缓存步骤的路径,排除.git目录:
- name: Restore repository from cache uses: actions/cache@v2 with: path: | ./* !./node_modules !./.git key: ${{ github.sha }}-run-${{ needs.config.outputs.run-timestamp }}
或者只缓存必要的非Git、非依赖文件(比如配置文件),避免覆盖完整的Git仓库历史。
2. 调整nx-set-shas的执行顺序
当前nx-set-shas在仓库缓存恢复前执行,缓存恢复可能会改变Git状态,导致之前注入的SHA对应的ref失效。建议将nx-set-shas移到所有Git操作和缓存恢复之后:
# 调整后的核心步骤顺序示例 - name: Pull the full git history uses: actions/checkout@v3 with: fetch-depth: 0 - name: Restore node modules from cache id: node-modules uses: actions/cache@v2 with: path: ./node_modules key: ${{ runner.os }}-node-${{ hashFiles('**/package-lock.json') }} - name: Install Node.js uses: actions/setup-node@v2 with: node-version: '16' check-latest: true - name: Restore repository from cache uses: actions/cache@v2 with: path: | ./* !./node_modules !./.git key: ${{ github.sha }}-run-${{ needs.config.outputs.run-timestamp }} - run: git fetch --all --tags --prune - name: Sets the base and head SHAs uses: nrwl/nx-set-shas@v3 - name: Install node modules if: ${{ steps.node-modules.outputs.cache-hit != 'true' }} run: npm ci # 后续步骤...
3. 确保Git拉取完整的远程引用
即使设置了fetch-depth:0,有时候远程分支或标签可能没拉全。修改git fetch命令为:
git fetch --all --tags --prune
这会拉取所有远程分支、标签,并清理本地无效的引用,确保NX需要的提交哈希存在于本地Git仓库中。
4. 手动指定nx-set-shas的SHA值
如果自动检测的base SHA有问题,可以手动指定base和head SHA,避免自动检测的偏差:
- name: Sets the base and head SHAs uses: nrwl/nx-set-shas@v3 with: base-sha: ${{ github.event.pull_request.base.sha }} head-sha: ${{ github.sha }}
对于非PR触发的工作流(比如push到主分支),可以将base-sha设置为上一次提交的哈希,或者使用github.event.before。
内容的提问来源于stack exchange,提问作者Maor agai
相关产品推荐
相关产品推荐

