Dennis A. Boanini
Dennis A. Boanini

Reputation: 497

Prevent Gitlab pipeline fail when nothing to commit

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?

Upvotes: 4

Views: 1814

Answers (2)

Kevin Pastor
Kevin Pastor

Reputation: 801

The git commit command has an option that allows empty commits.

git commit --allow-empty --message "My message"

In your specific case, it would simplify the bash conditional script call.

Upvotes: 2

danielnelz
danielnelz

Reputation: 5136

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

Upvotes: 4

Related Questions