DEV Community

Serhat Teker
Serhat Teker

Posted on • Originally published at tech.serhatteker.com on

Auto Add Git Commit Message

Add to One Commit

If you want to append the actual date to your commits you can use below script:

$ git commit -m "modified <branch> files on `date`"
Enter fullscreen mode Exit fullscreen mode

Your commit message will be like:

modified <branch> files on Tue Apr 29 17:23:02 +03 2020
Enter fullscreen mode Exit fullscreen mode

You can modify the date format as well as you like:

$ git commit -m "generated files on `date +'%Y-%m-%d %H:%M:%S'`"
Enter fullscreen mode Exit fullscreen mode

which will give:

modified <branch> files on 2020-04-29 17:23:02
Enter fullscreen mode Exit fullscreen mode

Add to All Commits

If you want to append the actual date to all your commits of a specific repository it is better to use Git Hooks:

Git Hooks

Git hooks are scripts that Git executes before or after events like:
commit, push, rebase etc.

They are a built-in feature.

Git hooks run locally.

Every Git repository has a .git/hooks repo and .samples you can use:

.git/
├── COMMIT_EDITMSG
├── config
├── description
├── FETCH_HEAD
├── HEAD
├── hooks
│   ├── applypatch-msg.sample
│   ├── commit-msg.sample
│   ├── fsmonitor-watchman.sample
│   ├── post-update.sample
│   ├── pre-applypatch.sample
│   ├── pre-commit.sample
│   ├── prepare-commit-msg.sample
│   ├── pre-push.sample
│   ├── pre-rebase.sample
│   ├── pre-receive.sample
│   └── update.sample
Enter fullscreen mode Exit fullscreen mode

Using Hooks

The hook we are going to use for our purpose is prepare-commit-msg.

  1. Make a copy of the file:

    $ cp .git/hooks/prepare-commit-msg.sample ./git/hooks/prepare-commit-message
    
  2. Delete the template content and add the script:

    #!/bin/bash
    #
    # Append current `date` to commit messages
    
    echo "`date +'%Y-%m-%d %H:%M:%S'`" >> $1
    

    where $1 is the commit message file.

  3. Make it executable:

    $ chmod +x prepare-commit-message
    

After every git commit run the date is going to be added automatically:

Update post "auto-add-git-commit-message"
# with '#' will be ignored, and an empty message aborts the commit.
#
# On branch <feature>
# Your branch is ahead of 'origin/<feature>' by 2 commits.
#   (use "git push" to publish your local commits)
#
# Changes to be committed:
#   new file:   content/post/2020-04/auto-add-git-commit-message.md
#
# Changes not staged for commit:
#   modified:   content/post/2020-04/auto-add-git-commit-message.md
#
2020-04-29 17:23:02
Enter fullscreen mode Exit fullscreen mode

Further

Adding date to a commit would be unnecessary since Git already logging date and you can see them with git log, however sometimes it would be useful.

After all of that you can use this post as an inspiration for your workflow automation.

All done!

Top comments (0)