CI/CD job - git diff

Goal

Run a code linter and check if there are any changes and fail.

linter:
  stage: test
  image: my-private-application-docker-image
  script:
    - run-code-linter
    - git diff --exit-code

Problem

$ git diff --exit-code
warning: Not a git repository. Use --no-index to compare two paths outside a working tree

Attempts

I’ve read the pinned thread called CI/CD pipeline - get list of changed files where they try to compare the current commit to the target and loop over changed files. This is not what I need, I need to check local changes (created by the linter).

All other attempts on Stack Overflow did not help either.

Can someone please explain how to run git diff --exit-code?

Working solution

I was able to get it working, but I’m sure there must be a better way.

linter:
  stage: test
  image: my-private-application-docker-image
  before_script:
    ##
    ## Install ssh-agent if not already installed. (apk add openssh-client)
    ## Run ssh-agent (inside the build environment)
    ##
    - eval $(ssh-agent -s)

    ##
    ## Add the SSH key stored in SSH_PRIVATE_KEY variable to the agent store
    ## We're using tr to fix line endings which makes ed25519 keys work
    ## without extra base64 encoding.
    ## https://gitlab.com/gitlab-examples/ssh-private-key/issues/1#note_48526556
    ##
    - echo "$SSH_PRIVATE_KEY" | tr -d '\r' | ssh-add -

    ##
    ## Create the SSH directory and give it the right permissions
    ##
    - mkdir -p ~/.ssh
    - chmod 700 ~/.ssh

    ##
    ## Prevent: Host key verification failed.
    ## https://stackoverflow.com/questions/13363553/git-error-host-key-verification-failed-when-connecting-to-remote-repository/29908140#29908140
    ##
    - ssh-keyscan -t rsa gitlab.com >> ~/.ssh/known_hosts

    ##
    ## Clone the current branch
    ##
    - git config --global --add safe.directory "*"
    - git clone --branch $CI_COMMIT_REF_NAME git@$CI_SERVER_HOST:$CI_PROJECT_PATH.git

  script:
    - run-code-linter
    - git diff --exit-code
1 Like

It can be due to CVE-2022-24765: git refuses to recognize .git as a git repository because it is not owned by the same user as the one running the command.

As a workaround, one can use:

before_script:
  - git config --global --add safe.directory "$(pwd)"
1 Like