CI/CD pipeline - get list of changed files

$CI_MERGE_REQUEST_DIFF_BASE_SHA is on available in MRs. You can’t use that logic in pipelines running on the default branch.

Just wanted to share what worked for me. In my case I always wanted the diff against the tip of origin/main.

  before_script:
    - LATEST_COMMIT=$( git ls-remote
      https://__token__:$GITLAB_TOKEN@gitlab.com/company/repo.git
      HEAD | awk '{ print $1}' )
    - CHANGES=$(git diff-tree --no-commit-id --name-only -r $LATEST_COMMIT -r $CI_COMMIT_SHA);
1 Like

Same thing.

Have you solved it?

If you have set up a shallow clone and/or use GIT_DEPTH: x you might get an unknown revision error because the commit you want to diff against, is not available.

But there’s a workaround that doesn’t require turning off the shallow clone or fetching the whole git repository (which might take minutes with large repos), so it is pretty fast and you can even set the initial clone depth to 1.

  variables:
    GIT_DEPTH: 1
  script:
    # Fetching only up to the closest merge-base to save time
    - git fetch --depth 1 origin $CI_MERGE_REQUEST_DIFF_BASE_SHA
    # Diff only changed files within MR
    - CHANGES=$(git diff-tree --name-only -r $CI_MERGE_REQUEST_DIFF_BASE_SHA $CI_COMMIT_SHA)
2 Likes

Thank you! This gave me the exact results I needed!

Hi, I want to get the path of the file changed. How can it be achieved?

pipe the result to something like rev | cut -d"/" -f2- | rev then you should have only the directory path.

Hello GitLab community,

Hi, my name is Rutvik, I am a new product manager for pipeline execution at GitLab.

We are currently working on a proposal for a view where we would visually compare all the commits of one pipeline with all the commits in another pipeline.

  1. Would you be able to use this or a similar solution in your own work? Why or why not?

Please respond by replying to this post or if you are interested in a detailed feedback, please complete this participant contact form so that we can setup 1:1 time with you.

Thanks,
Rutvik

I went through this thread and tried many solutions but only this one worked!