I had an idea yesterday to pull the last commit detail from the git repo for this site and put it as an HTML
comment so I can identify deploy issues quickly. A little bit of googling later I had a couple of extra lines hidden away in the generated HTML. (Go on, right click, view source, and scroll to the bottom)…
The implementation was pretty simple:
- Get the latest commit message with the git command:
git rev-parse --short HEAD
- Add the output to 11ty’s data cascade
- Expose it in the base template
Which got me thinking… would it be possible to use something similar to get a changelog for each blog post on the site?
Yes it is, here’s the related commit. Or keep reading for a step-by-step explainer.
Get the changelog for a file in git
Git has a log method which shows the changes across the repo. Just type git log
and you’ll get a full history of the changes made:
It’s much more powerful than that though– by putting a specific filepath after that command you can narrow it down to just display the commits made on that file. Handy.
However, as you can see from the output above, there is a lot of fluff in there that we don’t need. This is where the pretty format modifier comes in. For the changelog I want to display the date of the commit and the subject line, behind the scenes I also want the commit hash so I can link to it. This can be achieved with:
This outputs something like
The pipes (|
) are going to be important in a second.
Running the git log command in Eleventy
Now that we have a git command that will get the history of a file, we now need to run that for each page that we’re building[1]. To do this we’re going to create a filter in 11ty which accepts a file path.
If you were to log this out to the console, for each file that is fed into the filter you would get an array formatted like this:
With this as an array, we can now format it as we want on the frontend.
Handing on the frontend
Because I only want to display this changelog on blog posts, I am updating the post layout file (read about layout in 11ty. 11ty provides a bunch of data at build time about the current page from which we can pull page.inputPath
. This enables sending it through the filter that we have just created with page.inputPath | changelog
. And from there we can format this as you want.
Add some CSS to make it all pretty, and job is a good ‘un.
Caveat
There are times where you may not want to display that you updated a post– e.g. you may not want to admit how many typos you corrected in a post, etc… for that rewriting your git history is an amend
or a rebase
away.
Footnotes
- The health warning here is that for each page you run this on you’re going to be extending your build time. If you are doing this over a lot of pages you may only want to run this on production builds only, cache the result, or something else. ↩︎