The Darth Mall a personal website

Find the "Date Added" in Git

Published
Tagged
Computers
Git

Until recently, I have been filing my photos under the date the photos were taken. I changed this for two reasons. First, because there is a difference semantically between the date I took a photo, and the date I published it on my site. This is perhaps not a huge deal, but it leads me to the second reason for distinguishing between the published date and the photographed date: the entries in my RSS feed and in my archives are sorted in reverse chronological order by published date. So if I add old photos to the site, they won’t likely show up for people.

tl;dr

$ git log --follow --diff-filter=A \
	--pretty="%ad" --date=short -- FILE
Prints the date that FILE was added to the git repository

Where the magic happens

The first option you need is --diff-filter=A. --diff-filter takes a single-letter argument; the A filter selects only commits that added files. This option can do quite a lot, but I’ll leave you to check the man page for all the other useful things it can do.

The other option you need is --follow so that if a file has been moved or renamed, git log will trace the chain of commits for the file across these moves. Without it, if the file has ever been moved or renamed, git log will treat the last rename as when the file was added.

These two options will get you the commit in which the file was originally added to the repository. If, like me, all you want is to know the date, you need to add a couple of options to format the commit.

Formatting

The --pretty option for git log takes a format string. There’s a lot here, so, again, I’ll leave it as an exercise for the reader to check out all of the options available to you with this flag. The %ad value represents the date the commit was authored, and it respects the format specified by the --date option, which you can also use. The above example uses --date=short which formats the date as YYYY-MM-DD — a four-digit year, two-digit month, two-digit day.

I actually wanted the date in an ISO 8601 with precision out to the seconds and the time zone. You can pass --date=iso-strict to get a timestamp like this, but you can also just pass --pretty="%aI" instead, which gives you the commit author date in a strict ISO 8601 format.

$ git log --follow --diff-filter=A \
	--pretty="%aI" -- FILE
The actual command I ran to get the timestamps for when images were added to the repository.