Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save zoni/d3f6a803f552cc946d3bc00447d3e051 to your computer and use it in GitHub Desktop.
Save zoni/d3f6a803f552cc946d3bc00447d3e051 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python3
import os
import subprocess
from datetime import datetime
from pathlib import Path
from zoneinfo import ZoneInfo
import frontmatter
def path_starts_with(path, prefixes):
for prefix in prefixes:
try:
path.relative_to(Path(os.environ["KNOWLEDGEBASE_PATH"]) / Path(prefix))
except ValueError:
continue
else:
return True
return False
def main():
for path in Path(os.environ["KNOWLEDGEBASE_PATH"]).glob("**/*.md"):
if path_starts_with(
path,
[
".publish",
".obsidian",
"Views",
"Templates",
],
):
continue
update_frontmatter(path)
def update_frontmatter(path):
doc = frontmatter.load(path)
stat = path.stat()
doc["created"] = file_creation_date_from_git(path)
doc["updated"] = datetime.fromtimestamp(
stat.st_mtime,
tz=ZoneInfo("Europe/Amsterdam"),
).isoformat()
if "date" in doc:
doc["created"] = doc["date"]
del doc["date"]
if "lastmod" in doc:
doc["updated"] = doc["lastmod"]
del doc["lastmod"]
path.write_text(frontmatter.dumps(doc), encoding="utf-8")
def file_creation_date_from_git(path):
return subprocess.check_output(
["git", "log", "--diff-filter=A", "--follow", "--format=%aI", "-1", path],
encoding="utf-8",
).strip()
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment