Empty Git commits for CI

In this short post, we will be talking about every developer's favourite git command.
Ta-da! It's git commit!

We commit & push changes multiple times a day using the below commands.

git commit -m "This should fix it" 😜
git push origin HEAD

Nothing new, right?! However, sometimes our work involves working with other tools like CI/CD.

Let's say you're working on a feature branch, and you pushed some changes which broke the CI/CD build. Oopsie! You go ahead and check logs like a good citizen! In several instances, you might have seen your build fail because it failed to download your project dependencies from artifact repositories like npm, bintray, etc., or you messed up something in config when working on that feature.

You can fix such issues without having to update your code. But remember, once you resolve the issue, we need to rerun our CI with the latest commit on your feature branch for CI builds to be green again.

There are two ways to do it.

  • Go to the CI/CD page of your failed build. A giant nice-looking button on that screen might allow you to re-rerun the build.
  • Do it directly from the terminal 😎

The second approach looks more interesting. Isn't it? Let's look at how we can do it.

How to do it from terminal?

I'll first tell you how I've seen people do it, which IMO is an incorrect way.

Incorrect approach:

  1. Add a comment or white space somewhere in the code
  2. Commit it
  3. Push it
  4. CI gets re-triggered by listening to those hooks you've set up.

However, there is another way to do it by using a built-in commit flag in Git.

Correct way:

git commit --allow-empty -m "Trigger CI"
git push origin HEAD

That's it — no need to add unnecessary whitespaces or comments to the file to create a commit. You can create an empty commit like this by running a single command & push it to trigger the CI process again.

Bonus tip

If you're lazy like me and love setting aliases for every long command you've to type frequently, you can set an alias for this command in your default shell's config file(.bashrc or .zshrc)

alias gitci="git commit --allow-empty -m 'Trigger CI'"

Then use it like below:

gitci

If you want to use the alias but want an option to write a different commit message every time you want to do an empty commit? You can set the git alias in the .gitconfig file like the following.

.gitconfig file:

...
...
[alias]
    ...
    ci = "!f() { git commit --allow-empty -m \"$1\"; return 1;}; f"

Usage:

git ci 'Finally fixed it 😅'

I've been using this for quite a while, so I decided to share it. I hope that was useful!