Prevent Gitlab pipeline fail when nothing to commit

Issue

I had realized this pipeline

send:
  image: node:latest
  before_script:
    - git config --global user.email "[email protected]"
    - git config --global user.name "Gitlab CI"
  script:
    - npm install
    - npm run start $GMAIL_PW
    - echo "Committing updated files to git"

    - git add executions.txt
    - git commit -m "Updated executions with new running date"
    - git push "https://${GITLAB_USER_NAME}:${CI_ACCESS_TOKEN}@${CI_REPOSITORY_URL#*@}" "HEAD:${CI_COMMIT_REF_NAME}" -o skip-ci
  only:
    - schedules

Sometimes there is nothing to commit and the pipeline fails with this error

$ git add executions.txt
$ git commit -m "Updated executions with new running date"
HEAD detached at 0fa2f4d
nothing to commit, working tree clean
Cleaning up project directory and file based variables
00:00
ERROR: Job failed: exit code 1

How I can prevent the pipeline to fail when there is nothing to commit?

Solution

You could check for the git status and only commit and push if there is something to commit:

send:
  image: node:latest
  before_script:
    - git config --global user.email "[email protected]"
    - git config --global user.name "Gitlab CI"
  script:
    - npm install
    - npm run start $GMAIL_PW
    - |     
      CHANGES=$(git status --porcelain | wc -l)
      if [[ "${CHANGES}" -gt 0 ]]; then
        echo "Committing updated files to git"
        git add executions.txt
        git commit -m "Updated executions with new running date"
        git push "https://${GITLAB_USER_NAME}:${CI_ACCESS_TOKEN}@${CI_REPOSITORY_URL#*@}" "HEAD:${CI_COMMIT_REF_NAME}" -o skip-ci
      else
        echo "Nothing to commit"
      fi
  only:
    - schedules

Answered By – danielnelz

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published