Vishnu
Vishnu

Reputation: 67

How to insert git commit date into a file being committed?

I am working on task in which I need the git commit date to be written into one of the files being committed. I need it to happen in a couple of scenarios:

Specifically, the change should look like this:

Before commit: private String DATE="$DATE$"

After commit: private String DATE="$DATE: 2020-05-08 18:19:25 $"

Here's what I've tried so far:

I have followed https://git-scm.com/book/en/v2/Customizing-Git-Git-Attributes#Keyword-Expansion and added .gitattributes, .gitconfig, .git_filters(which has smudge and clean filter) into my project.

Below are the things which i configured in proj:

    clean  = .git_filters/dater.clean
    smudge = .git_filters/dater.smudge %f 
*.java filter=dater 

dater.clean:

#!/usr/bin/sh

sed s/$Date$/`date +%Y%m%d`/g 

dater.smudge:

#! /usr/bin/env ruby
data = STDIN.read
last_date = `git log --pretty=format:"%ad" -1`
puts data.gsub('$Date$', '$Date: ' + last_date.to_s + '$')

When i tried with the above configuration.. it doesn't work..Looking for help to fix this issue plz...

Upvotes: 6

Views: 1467

Answers (1)

bk2204
bk2204

Reputation: 76509

Smudge and clean filters are the right way to go here, but you're going to have to use a filter process as described in gitattributes(7). The reason this is required is that when smudging commits during a checkout, HEAD has not been updated, so it's not possible to query the date of the given revision.

In very recent versions of Git (definitely 2.26, but possibly 2.25), you can use the filter process to get the commit if it's available. If the commit ID is available, you can query treeish in the metadata passed to the filter process. That will be a commit if it's available, and a tree (or absent) if not. If it's not a commit, you should be able to use HEAD instead.

This metadata is not passed along using smudge and clean, only when using filter-process, so you really need to create a small process filter if you need this functionality.

Also, be aware that your clean filter should strip the date out and not actually include it in the commit. If you store the date in the actual commit, then you'll run into merge conflicts every time you merge branches.

Finally, all of this can be avoided and you can go with a much simpler solution if you don't need this DATE field in every class. If your project contains a single static class with metadata in it, you can put the DATE field there, create it as part of one of your build steps by invoking Git, and dispense with the filters altogether. This will be easier, faster, and simpler. If you need to produce a tarball, you can generate this file at tarball generation time.

Upvotes: 4

Related Questions