| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
"""Expose page Git update dates to Zensical templates.""" |
| 5 |
|
| 6 |
from __future__ import annotations |
| 7 |
|
| 8 |
import subprocess |
| 9 |
from datetime import datetime, timezone |
| 10 |
from functools import cache |
| 11 |
from pathlib import Path |
| 12 |
from shutil import which |
| 13 |
from typing import TYPE_CHECKING |
| 14 |
|
| 15 |
from markdown import Extension |
| 16 |
from markdown.preprocessors import Preprocessor |
| 17 |
from zensical.extensions.context import ContextPreprocessor |
| 18 |
|
| 19 |
if TYPE_CHECKING: |
| 20 |
from markdown import Markdown |
| 21 |
|
| 22 |
GIT_LOG_FIELD_COUNT = 3 |
| 23 |
GIT_RENAME_FIELD_COUNT = 3 |
| 24 |
GIT_COMMAND = which("git") or "git" |
| 25 |
|
| 26 |
|
| 27 |
class GitDatesPreprocessor(Preprocessor): |
| 28 |
"""Populate Material's expected Git date page metadata.""" |
| 29 |
|
| 30 |
def run(self, lines: list[str]) -> list[str]: |
| 31 |
"""Set the current page's Git revision metadata.""" |
| 32 |
context = ContextPreprocessor.from_markdown(self.md) |
| 33 |
if context is None: |
| 34 |
return lines |
| 35 |
|
| 36 |
root_dir = Path(context.config.get("root_dir", ".")).resolve() |
| 37 |
docs_dir = Path(context.config.get("docs_dir", "docs")) |
| 38 |
path = docs_dir / context.page.path |
| 39 |
if path.is_absolute(): |
| 40 |
path = path.relative_to(root_dir) |
| 41 |
date = _last_update(root_dir, path) |
| 42 |
if date is not None: |
| 43 |
context.page.meta["git_revision_date_localized"] = date |
| 44 |
|
| 45 |
return lines |
| 46 |
|
| 47 |
|
| 48 |
class GitDatesExtension(Extension): |
| 49 |
"""Register the Git date metadata preprocessor.""" |
| 50 |
|
| 51 |
def extendMarkdown(self, md: Markdown) -> None: |
| 52 |
"""Register the Git dates preprocessor with Python-Markdown.""" |
| 53 |
md.registerExtension(self) |
| 54 |
md.preprocessors.register(GitDatesPreprocessor(md), "zensical_git_dates", 5) |
| 55 |
|
| 56 |
|
| 57 |
def makeExtension(**_: object) -> GitDatesExtension: |
| 58 |
"""Create the Markdown extension instance.""" |
| 59 |
return GitDatesExtension() |
| 60 |
|
| 61 |
|
| 62 |
@cache |
| 63 |
def _last_update(root_dir: Path, path: Path) -> str | None: |
| 64 |
"""Return the latest Git date for Markdown body changes.""" |
| 65 |
relpath = path.as_posix() |
| 66 |
for commit, parents, timestamp, commit_path, parent_path in _history(root_dir, relpath): |
| 67 |
parent = parents.split(" ", 1)[0] |
| 68 |
if not parent: |
| 69 |
return _format_date(timestamp) |
| 70 |
|
| 71 |
current = _content_at(root_dir, commit, commit_path) |
| 72 |
previous = _content_at(root_dir, parent, parent_path) |
| 73 |
if current is not None and previous is None: |
| 74 |
return _format_date(timestamp) |
| 75 |
if current is None or previous is None: |
| 76 |
continue |
| 77 |
|
| 78 |
if _markdown_body(current) != _markdown_body(previous): |
| 79 |
return _format_date(timestamp) |
| 80 |
|
| 81 |
return None |
| 82 |
|
| 83 |
|
| 84 |
def _history(root_dir: Path, relpath: str) -> list[tuple[str, str, str, str, str]]: |
| 85 |
try: |
| 86 |
output = subprocess.check_output( |
| 87 |
[ |
| 88 |
GIT_COMMAND, |
| 89 |
"-C", |
| 90 |
str(root_dir), |
| 91 |
"log", |
| 92 |
"--follow", |
| 93 |
"--name-status", |
| 94 |
"--format=%H%x00%P%x00%ct", |
| 95 |
"--", |
| 96 |
relpath, |
| 97 |
], |
| 98 |
stderr=subprocess.DEVNULL, |
| 99 |
text=True, |
| 100 |
) |
| 101 |
except (FileNotFoundError, subprocess.CalledProcessError, ValueError): |
| 102 |
return [] |
| 103 |
|
| 104 |
history: list[tuple[str, str, str, str, str]] = [] |
| 105 |
commit: str | None = None |
| 106 |
parents: str | None = None |
| 107 |
timestamp: str | None = None |
| 108 |
commit_path = relpath |
| 109 |
parent_path = relpath |
| 110 |
for line in output.splitlines(): |
| 111 |
parts = line.split("\x00") |
| 112 |
if len(parts) == GIT_LOG_FIELD_COUNT: |
| 113 |
if commit is not None and parents is not None and timestamp is not None: |
| 114 |
history.append((commit, parents, timestamp, commit_path, parent_path)) |
| 115 |
commit, parents, timestamp = parts |
| 116 |
commit_path = relpath |
| 117 |
parent_path = relpath |
| 118 |
continue |
| 119 |
|
| 120 |
if line.startswith("R"): |
| 121 |
rename = line.split("\t") |
| 122 |
if len(rename) == GIT_RENAME_FIELD_COUNT: |
| 123 |
parent_path, commit_path = rename[1], rename[2] |
| 124 |
elif "\t" in line: |
| 125 |
commit_path = parent_path = line.split("\t", 1)[1] |
| 126 |
|
| 127 |
if commit is not None and parents is not None and timestamp is not None: |
| 128 |
history.append((commit, parents, timestamp, commit_path, parent_path)) |
| 129 |
return history |
| 130 |
|
| 131 |
|
| 132 |
def _content_at(root_dir: Path, commit: str, relpath: str) -> str | None: |
| 133 |
try: |
| 134 |
return subprocess.check_output( |
| 135 |
[GIT_COMMAND, "-C", str(root_dir), "show", f"{commit}:{relpath}"], |
| 136 |
stderr=subprocess.DEVNULL, |
| 137 |
text=True, |
| 138 |
) |
| 139 |
except (FileNotFoundError, subprocess.CalledProcessError, ValueError): |
| 140 |
return None |
| 141 |
|
| 142 |
|
| 143 |
def _markdown_body(content: str) -> str: |
| 144 |
"""Return Markdown content without leading metadata/license boilerplate.""" |
| 145 |
lines = [line.rstrip() for line in content.splitlines()] |
| 146 |
while lines: |
| 147 |
stripped = _strip_leading_blank_lines(lines) |
| 148 |
stripped = _strip_front_matter(stripped) |
| 149 |
stripped = _strip_leading_blank_lines(stripped) |
| 150 |
stripped = _strip_license_comment(stripped) |
| 151 |
stripped = _strip_leading_blank_lines(stripped) |
| 152 |
if stripped == lines: |
| 153 |
break |
| 154 |
lines = stripped |
| 155 |
return "\n".join(line.rstrip() for line in lines).strip() |
| 156 |
|
| 157 |
|
| 158 |
def _strip_leading_blank_lines(lines: list[str]) -> list[str]: |
| 159 |
"""Remove leading blank lines.""" |
| 160 |
for index, line in enumerate(lines): |
| 161 |
if line: |
| 162 |
return lines[index:] |
| 163 |
return [] |
| 164 |
|
| 165 |
|
| 166 |
def _strip_front_matter(lines: list[str]) -> list[str]: |
| 167 |
"""Remove leading YAML front matter.""" |
| 168 |
if lines and lines[0] == "---": |
| 169 |
for index, line in enumerate(lines[1:], start=1): |
| 170 |
if line == "---": |
| 171 |
return lines[index + 1 :] |
| 172 |
return lines |
| 173 |
|
| 174 |
|
| 175 |
def _strip_license_comment(lines: list[str]) -> list[str]: |
| 176 |
"""Remove a leading repository license HTML comment.""" |
| 177 |
if not lines or lines[0] != "<!--": |
| 178 |
return lines |
| 179 |
for index, line in enumerate(lines[1:], start=1): |
| 180 |
if line == " -->": |
| 181 |
block = "\n".join(lines[: index + 1]) |
| 182 |
if "Copyright (c)" in block and "LICENSE file" in block: |
| 183 |
return lines[index + 1 :] |
| 184 |
break |
| 185 |
return lines |
| 186 |
|
| 187 |
|
| 188 |
def _format_date(timestamp: str) -> str: |
| 189 |
"""Return a localized-style date without platform-specific strftime flags.""" |
| 190 |
date = datetime.fromtimestamp(int(timestamp), tz=timezone.utc) |
| 191 |
return f"{date:%B} {date.day}, {date:%Y}" |