git/list[1] front-page[2] threads[3] people[4] search[5] about
 

Implementing $Date$ substitution - solution using pre-commit

From
Peter Krefting <peter@softwolves.pp.se>
Date
Aug 13, 2009, 06:47 UTC
Message-ID
<alpine.DEB.2.00.0908130742470.18241@ds9.cixit.se>
In-Reply-To
<alpine.DEB.2.00.0908092127420.17141@perkele.intern.softwolves.pp.se>
Hi!

So, my filter-based approach at doing RCS-like $Date$ expansion didn't work out. Since I wanted to have the Date expand on check-in, not on check-out, and be expanded in history, I had made it into a "clean" filter. But due to how Git internally checks if files are clean, that did not work properly.

The solution to this was instead to make the Date expansion into a pre-commit hook. Using .gitattributes, I set "datereplace=true" on all the files I want to have "$Date$" expand in, and then install the following file as .git/hooks/pre-commit:

===8< pre-commit >8=== #!/bin/bash -e

# Find base commit
if git-rev-parse --verify HEAD >/dev/null 2>&1
then
 	against=HEAD
else
 	# Initial commit: diff against an empty tree object
 	against=4b825dc642cb6eb9a060e54bf8d69288fbee4904
fi
# Set up Date substitution
export NOW=$(date +"%Y-%m-%d %H:%M:%S")
for file in $(git diff-index --cached --diff-filter=AM --name-only $against); do
   if git check-attr datereplace -- "$file" | grep 'datereplace: true' > /dev/null; then
     perl -w -i.bak -e 'my $now = $ENV{"NOW"};
$now =~ s/[^-:0-9 ]//g;
while (<>)
{
  if (/\$Date:?[^\$]*\$/)
  {
    s/\$Date:?[^\$]*\$/\$Date: ${now} \$/;
  }
  print
}' "$file"
     git update-index --add "$file"
   fi
done

exit 0 ===8< pre-commit >8===

This has the added bonus over a filter that it all files committed at the same time will have the same date stamp, whereas the filter would expand on the time "git add" is executed.

-- 
\\// Peter - http://www.softwolves.pp.se/
Previous: Peter Krefting
Message 8 of 8 in “Implementing $Date$ substitution - problem with git status”
  1. Peter KreftingAug 9, 2009
  2. Johannes SixtAug 9, 2009
  3. Peter KreftingAug 10, 2009
  4. Peter KreftingAug 12, 2009
  5. Problems with filters and git status - reproduction stepsPeter Krefting, Aug 12, 2009
  6. Michael J GruberAug 12, 2009
  7. Peter KreftingAug 12, 2009
  8. Implementing $Date$ substitution - solution using pre-commitPeter Krefting, Aug 13, 2009

Read the whole thread, see it on lore, or plain text.

$ cat FOOTERMessages come from the public archive at lore.kernel.org/git, fetched every hour. The front page is chosen and written each morning by an AI editor and can be wrong; the threads themselves are the record. About and API. For agents: an MCP server at https://gitlist.dev/mcp, and any thread, story or person page as Markdown by adding .md to its URL (or sending Accept: text/markdown). Details in /llms.txt.