I asked for similiar things before (but with file’s metadata instead of git).
Currently I use the following pre-commit hook:
#!/usr/bin/env python3
import os
import subprocess
from datetime import datetime
updated_files = subprocess.run(['git', 'diff', '--name-only', '--cached'], stdout=subprocess.PIPE).stdout.decode('utf-8').strip()
updated_file_list = (f.strip() for f in updated_files.split("\n") if f.strip().endswith("index.md"))
for updated_file_name in updated_file_list:
with open(updated_file_name, "r") as f:
content = f.read()
temp = content.split('+++', 2)
frontmatter = temp[1]
text_content = temp[2]
# "parsing" toml manually to avoid introducing dependency
items = frontmatter.split('\n')
date_index = None
update_index = None
autoupdate = True
template_index = 0
for (index, item) in enumerate(items):
if item.startswith("template"):
# we'll insert the new created toml item after `template`
template_index = index
if item.startswith("date"):
date_index = index
if item.startswith("updated"):
update_index = index
if item.startswith("no_auto_update") and item.split("=")[1].strip(" ") != "false":
autoupdate = False
if autoupdate:
version_count = int(subprocess.run(['git', 'rev-list', 'HEAD', '--count', '--', updated_file_name], stdout=subprocess.PIPE).stdout.decode('utf-8').strip())
if version_count == 0:
# new created file, insert created datetime if necessary
if date_index is None:
items.insert(template_index + 1, "date = {}".format(datetime.now().strftime("%Y-%m-%dT%H:%M:%S.000Z")))
else:
# updated file, update the updated datetime if necessary
if update_index is None:
items.insert(template_index + 1, "update = {}".format(datetime.now().strftime("%Y-%m-%dT%H:%M:%S.000Z")))
else:
items[update_index] = "update = {}".format(datetime.now().strftime("%Y-%m-%dT%H:%M:%S.000Z"))
new_frontmatter = "\n".join(items)
new_content = "+++\n" + new_frontmatter.strip("\n") + "\n+++" + text_content
with open(updated_file_name, "w") as f:
f.write(new_content)
# re-add the updated file
subprocess.run(['git', 'add', updated_file_name])