Gajus
Gajus

Reputation: 73828

How to list the modified files?

I am using to run scripts defined in .gitlab-ci.yml whenever a PR is raised.

I want to get the list of modified files since the last commit.

The use case is to run file-specific integration tests in a large codebases.

Upvotes: 25

Views: 31288

Answers (3)

EgurnovD
EgurnovD

Reputation: 315

This problem is discussed in this thread on gitlab forum.

My working script lines for a merge request pipeline are

- git fetch origin $CI_MERGE_REQUEST_TARGET_BRANCH_NAME
- git --no-pager diff --name-only origin/$CI_MERGE_REQUEST_TARGET_BRANCH_NAME | grep "**/*\.py$" | xargs black --check

Upvotes: 0

Ravi Ojha
Ravi Ojha

Reputation: 862

A common use case that some people will find useful. Run the job when a merge request is raised. Specifically, run lint on all the files that are changed w.r.t. target branch.

As one of the answers suggest, we can get the target branch name through CI_MERGE_REQUEST_TARGET_BRANCH_NAME variable (list of predefined variables). We can use git diff --name-only origin/$CI_MERGE_REQUEST_TARGET_BRANCH_NAME to get the list of files that were changed. Then pass them on to the linter via xargs. The example configuration may look like.

code_quality:
  only:
    - merge_requests
  script:
    - git diff --name-only origin/$CI_MERGE_REQUEST_TARGET_BRANCH_NAME | xargs <LINT_COMMAND_FOR_FILE>

Upvotes: 10

Gajus
Gajus

Reputation: 73828

If you do not need to know the paths, but you simply need to run a specific job only when a specific file is changed, then use only/changes .gitlab-ci.yml configuration, e.g.

docker build:
  script: docker build -t my-image:$CI_COMMIT_REF_SLUG .
  only:
    changes:
      - Dockerfile
      - docker/scripts/*

Alternatively, if you need to get paths of the modified scripts, you can use CI_COMMIT_BEFORE_SHA and CI_COMMIT_SHA environment variables, e.g.

> git diff --name-only $CI_COMMIT_BEFORE_SHA $CI_COMMIT_SHA
src/countries/gb/homemcr.js
src/countries/gb/kinodigital.js

Upvotes: 21

Related Questions