5

I want to check by pre-commit files that was changed in git branch in Gitlab CI. What arg for --from-ref I need to use?

pre-commit run --from-ref=? --to-ref=HEAD

Example from pre-commit documentation raises error.

$ pre-commit run --from-ref=origin/HEAD --to-ref HEAD
An unexpected error has occurred: CalledProcessError: command: ('/usr/bin/git', 'diff', '--name-only', '--no-ext-diff', '-z', 'origin/HEAD...HEAD')
return code: 128
expected return code: 0
stdout: (none)
stderr:
    fatal: ambiguous argument 'origin/HEAD...HEAD': unknown revision or path not in the working tree.
    Use '--' to separate paths from revisions, like this:
    'git <command> [<revision>...] -- [<file>...]'
voronin
  • 659
  • 6
  • 8
  • It took me so long to find this exactly question, specifically for GitLab CICD. Thank you! – MrDuk Sep 22 '22 at 16:59

4 Answers4

3

I came across the same issue while developing a pre-commit stage for a GitLab CI/CD pipeline. It seems that the GitLab CI/CD runner does not automatically fetch the origin/master branch, leading to the fatal: ambiguous argument 'origin/HEAD...HEAD': unknown revision or path not in the working tree. error.

My workaround was to manually fetch origin:

git fetch origin;
pre-commit run --from-ref "origin/$CI_DEFAULT_BRANCH" --to-ref "$CI_COMMIT_SHA";
Dharman
  • 30,962
  • 25
  • 85
  • 135
1

I hope this is helpful for anyone looking for the GitHub Actions version of this. This post inspired me, and I ended up setting up pre-commit on GitHub Actions with the following setup and arguments (run as a bash script):

pip install pre-commit
git fetch origin
pre-commit run --from-ref origin/${{ github.event.pull_request.base.ref }} --to-ref ${{ github.event.pull_request.head.sha }}
alxhbly
  • 456
  • 4
  • 6
0

I was battling this, too, and I finally got the answer.

  1. Before running pre-commit at all, fetch the origin/$CI_MERGE_REQUEST_TARGET_BRANCH_NAME. In most cases, this will be origin/master, but we want to stay flexible.
  2. Then, run pre-commit from the fetched target branch to $CI_COMMIT_SHA.

This is what your script should look like:

script:
  - git fetch origin $CI_MERGE_REQUEST_TARGET_BRANCH_NAME
  - pre-commit run --from-ref origin/"$CI_MERGE_REQUEST_TARGET_BRANCH_NAME" --to-ref "$CI_COMMIT_SHA"
Nikita Karamov
  • 517
  • 1
  • 5
  • 18
-1

To answer the question:

variables:
  GIT_FETCH_EXTRA_FLAGS: $CI_DEFAULT_BRANCH --prune
script:
  - pre-commit run --from-ref origin/$CI_DEFAULT_BRANCH --to-ref $CI_COMMIT_SHORT_SHA

==============

In addition to this answer:

Since GitLab 13.1 theres the GIT_FETCH_EXTRA_FLAGS variable to control behavior of git fetch command. Default is

git fetch origin $REFSPECS --depth $GIT_DEPTH  --prune --quiet

(see https://docs.gitlab.com/ee/ci/runners/configure_runners.html#git-fetch-extra-flags)

So theres no need to add git fetch.

jda91
  • 1
  • 1