loading...

Auto Add Date to Git Commit Messages

serhatteker profile image Serhat Teker Originally published at tech.serhatteker.com on ・2 min read

In previous post — Auto Add Git Commit Message, we saw how to add auto text into commit messages.

Now I want to use a concrete commit message template for all Git commits. It will be like: $yearnum/$weeknum/$daynum $unix_timestamp | version:.

Yes, adding date to a commit would be unnecessary since Git already logging date and you can see them with git log.

However I am going to use this template for my Journal, therefore for lookups this template makes things easy and quick.

For message I am going to use linux's default date/bin/date. You can find below $MESSAGE that I will add to commits:

# Nums
YNUM=$(date +%y)
WNUM=$(date +%U -d "$DATE + 1 week")
DAYNUM=$(date +%w)
# Unix timestamp
UNIX_SEC=$(date +%s)

MESSAGE="Add y$YNUM:w$WNUM:d0$DAYNUM $UNIX_SEC | ver:"

To append this every commit message use below code:

COMMIT_MSG_FILE=$1

echo "$MESSAGE" >> $COMMIT_MSG_FILE

So when you git commit it appends our message and it will be like: "Add y20:w21:d02 1588701600 | ver:"

In this approach there is one thing that I want to improve: Instead of append I want prepend message so it will be on first line.

In order to prepend message to commit we will use sed and regex:

sed -i "1s/^/$MESSAGE/" $COMMIT_MSG_FILE

In the end whole solution can be found below:

.git/hooks/prepare-commit-message

#!/bin/sh
#
# A git hook script to prepare the commit log message.
#
# It adds below date message to commits:
# $yearnum/$weeknum/$daynum $unix_timestamp | version:
#
# To enable this hook, rename this file to "prepare-commit-msg".
# Add it below '.git/hooks/' and make it executable:
# chmod +x prepare-commit-msg


COMMIT_MSG_FILE=$1

# Nums
YNUM=$(date +%y)
WNUM=$(date +%U -d "$DATE + 1 week")
DAYNUM=$(date +%w)
# Unix time in milisecond
UNIX_SEC=$(date +%s)

MESSAGE="Add y$YNUM:w$WNUM:d0$DAYNUM $UNIX_SEC | ver:"


sed -i "1s/^/$MESSAGE/" $COMMIT_MSG_FILE

All done!

Discussion

pic
Editor guide