In this post I will explain how to use the pre-commit Git hook to automate the input of the created (pubDatetime) and modified (modDatetime) in the AstroPaper blog theme frontmatter.
Table of contents
Open Table of contents
Have them Everywhere
Git hooks are great for automating tasks like adding or checking the branch name to your commit messages or stopping you committing plain text secrets. Their biggest flaw is that client-side hooks are per machine.
You can get around this by having a hooks directory and manually copy them to the .git/hooks directory or set up a symlink, but this all requires you to remember to set it up, and that is not something I am good at doing.
As this project uses npm, we are able to make use of a package called Husky to automatically install the hooks for us.
Update! In AstroPaper v4.3.0, the pre-commit hook has been removed in favor of GitHub Actions. However, you can easily install Husky yourself.
The Hook
The pre-commit hook runs before a commit is finalized, making it the perfect place to update dates in our frontmatter. Here’s how the hook works:
Setting the Created Date
For new files (files being added to git for the first time), we want to set the pubDatetime to the current date and time:
#!/bin/bash
# Get newly added files
new_files=$(git diff --cached --name-only --diff-filter=A -- 'src/data/blog/*.md')
for file in $new_files; do
# Set pubDatetime for new posts
current_date=$(date -u +"%Y-%m-%dT%H:%M:%SZ")
sed -i "s/pubDatetime:.*/pubDatetime: $current_date/" "$file"
git add "$file"
done
Setting the Modified Date
For existing files that have been modified, we want to update the modDatetime:
# Get modified files
modified_files=$(git diff --cached --name-only --diff-filter=M -- 'src/data/blog/*.md')
for file in $modified_files; do
current_date=$(date -u +"%Y-%m-%dT%H:%M:%SZ")
# Add or update modDatetime
if grep -q "modDatetime:" "$file"; then
sed -i "s/modDatetime:.*/modDatetime: $current_date/" "$file"
else
sed -i "/pubDatetime:/a modDatetime: $current_date" "$file"
fi
git add "$file"
done
Setting Up Husky
Install Husky and set up the hook:
npm install -D husky
npx husky init
Then add your pre-commit script to .husky/pre-commit.
Conclusion
Using Git hooks to automatically set dates removes the manual work of updating timestamps every time you create or modify a blog post. Combined with Husky, these hooks are automatically installed for anyone who clones the repository.