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
doneexit 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/