gitcontinuous-integrationgithub-actionsnrwl-nxgit-fetch

fatal: ambiguous argument 'main': unknown revision or path not in the working tree


I'm using NX in my CI with GitHub Actions and I checkout the repository using actions/checkout@v4.

When I try to use nx affected:..., for example nx affected:lint or nx affected:test it fails with the following error:

fatal: ambiguous argument 'main': unknown revision or path not in the working tree. Use '--' to separate paths from revisions, like this: 'git [...] -- [...]'

The problem is that the main branch is not available. I tried to fix this problem using fetch-depth: 0 as suggested by the checkout action's documentation, but it did not solve my problem.


Solution

  • Execute the following command before your :affected command to ensure your CI environment has an unambiguous main available in your branch.

    git rev-parse --verify main || git remote set-branches origin main && git fetch --depth 1 origin main && git branch main origin/main

    What this does is

    This would, however, fail if you run the command while on main already, so you should only execute it in a branch.

    Something like this in your yml should do the trick:

    if: github.ref != 'refs/heads/main'
    run: git rev-parse --verify main || git remote set-branches origin main && git fetch --depth 1 origin main && git branch main origin/main