Static site generators and Git modification times

Mon May 30, 2016

One of the (mis)features of Git is that it doesn’t track file modification times, this could be a problem when using static website generators. As there isn’t any Blog/CMS running on the server, just a plain HTTP server handling static files, file modification times are important because browser will cache content using that time. If you build your site without taking this into account the result will be a website where all files times are new after each build.

In practice modifications times are primarly important for media files, for example: images, photos and videos you upload to the website. These are usually a few kilobytes in size and it is important visitors browsers are able to cache them.

Using the power of Git commands is possible to query the repository which commit was the last one that touched each file, get the commit time and use it as the date for the file. This script could help:

#!/bin/sh

git ls-tree -r --name-only HEAD | while read filename; do
  touch -d "$(git log -1 --format="%ai" -- "$filename")" "$filename"
done

  « Previous: Next: »