Skip to content

Instantly share code, notes, and snippets.

@bensteinberg
Last active January 2, 2023 21:41
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save bensteinberg/1359f6da5e182dacd1de358737524bc4 to your computer and use it in GitHub Desktop.
Save bensteinberg/1359f6da5e182dacd1de358737524bc4 to your computer and use it in GitHub Desktop.
pre-commit hook for adding a timestamp to the frontmatter of markdown files
#!/usr/bin/perl
use POSIX qw(strftime);
# this is a pre-commit hook for setting a timestamp in the frontmatter
# of markdown files
my $date = strftime "%Y-%m-%dT%H:%M:%SZ", gmtime;
my @files = `git diff-index --cached --name-only HEAD`;
foreach (@files) {
if (/\.md$/) { # maybe HTML, too?
open FILE, $_ or die $!;
my @lines = <FILE>;
close FILE or die $!;
my $file = join('', @lines);
if ($file =~ m/---\n(.*)---\n(.*)/s) {
my $frontmatter = $1;
my $body = $2;
if (!($frontmatter =~ s/^date: .*$/date: $date/m)) {
$frontmatter = $frontmatter . "date: $date\n"
}
open FILE, ">$_" or die $!;
print FILE "---\n$frontmatter---\n$body";
close FILE or die $!;
system "git add $_";
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment