How to make sure a file was changed with GitLab CI?

Viewed 2026

I have a small project on GitLab and I keep a CHANGELOG.md file in it. I want to update it with every merge to master, but occasionally I forget. I'm using GitLab CI and so I'd like to employ it to check if the changelog file was changed. How can I do it?

2 Answers

This was my solution after a lot of trials. Hope it helps. Basically, I only want to trigger the job when we have a new merge request. Using git, I get the list of files that changed within the merge request and if the file I want to track is inside that list, then the job is successful. If the file is not found, the job fails

update_file_check:
  stage: test
  script:
    - git fetch
    - FILES_CHANGED=$(git diff --name-only $CI_MERGE_REQUEST_DIFF_BASE_SHA...HEAD)
    - |+
      for i in $FILES_CHANGED
      do
        if [[ "$i" == "<filename>" ]]
        then
          exit 0
        fi
      done
      exit 1
  rules:
    - if: '$CI_PIPELINE_SOURCE == "merge_request_event"'

It is possible and there are several ways to achieve it. I would propose to use the same host where gitlab is located as runner with shell executor. Basically, you are opening a way in order to run a few commands into this gitlab runner. Now, there are a lot of resources in internet and even in the official docs of gitlab, but to sum up, you will need to follow the next flow:

1. .gitlab-ci.yml

This file should be in the root of your project. It is read and interpreted by gitlab when running CI CD tasks. It can be as complex as you wish, but in my opinion, I like to keep things simple, so I will just invoke an script when master branch is changed.

The content might be something like this:

Check Changelog:
  script:
    - sh .gitlab/CI-CD-Script.sh       ## Execute in the gitlab runner the script.
  only:
    - master                           ## It will run only when master branch changes.

2. .gitlab/CI-CD-Script.sh

As mentioned, I prefer to call a script which it will manage the logic of all CI CD. But as previously said, there are multiple ways to achieve same results. Below, you can build an script in the next way:

#!/bin/bash
# Download the original changelog from master branch.
wget http://<yourgitlabAddress>/<pathToProject>/-/raw/master/CHANGELOG.md /tmp/CHANGELOG.md

if cmp -s /tmp/CHANGELOG.md CHANGELOG.md; then       ## Checking if files are different.
    echo "Changelog not changed"
    exit 1                                           ## Job will fail
else
    echo "Changelog changed"
    exit 0                                           ## Job will pass
fi

That would be all so far. I can't try it in your environment, I hope it helps you.

Related