Using inherited environment variables in CI rules (better only:changes)

The behaviour of only:changes does not suit me as it only takes changes since the last push instead of changes since the merge-base between target branch and pushed branch.

I tried to implement a better one with if rules and environment variables but I can’t make it work.

The gitlab-ci code I use is something like:

stages:
- build
- test

checkmodifiedfiles:
      stage: build
  script:
  - touch modified.env
  - git fetch --unshallow origin master
  - git fetch origin $CI_COMMIT_REF_NAME
  - git diff --name-only $(git merge-base origin/master $CI_COMMIT_SHA)..$CI_COMMIT_SHA >modified_files.txt
  - egrep -q '^path/with/changes/to/check' modified_files.txt && echo "MODIFIED=true" >>modified.env || true
  artifacts:
    reports:
      dotenv: modified.env

testonlywhenmodified:
  stage: test
  script:
  - echo "only when path/with/changes/to/check is modified"
  dependencies:
  - checkmodifiedfiles
  rules:
  - if: $MODIFIED == "true"

Variable “MODIFIED” is correctly inherited by testonlywhenmodified job when I deactivate the rule but when I activate it the job is never run even when the variable is true.

Any idea how to make this work ?

Hey, @francoisj

How are you diffing between changes to check if something was changed?

git diff --name-only $(git merge-base origin/master $CI_COMMIT_SHA)..$CI_COMMIT_SHA