-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
lektor_git_timestamp.py
265 lines (216 loc) · 7.81 KB
/
lektor_git_timestamp.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
from __future__ import annotations
import datetime
import enum
import hashlib
import os
import pickle
import re
import subprocess
import sys
from contextlib import suppress
from dataclasses import dataclass
from typing import Any
from typing import Iterable
from typing import Iterator
from typing import Mapping
from typing import NamedTuple
from typing import overload
from typing import Sequence
from typing import TYPE_CHECKING
import jinja2
from lektor.context import get_ctx
from lektor.pluginsystem import get_plugin
from lektor.pluginsystem import Plugin
from lektor.sourceobj import VirtualSourceObject
from lektor.types import DateTimeType
from lektor.utils import bool_from_string
from lektorlib.recordcache import get_or_create_virtual
from werkzeug.utils import cached_property
if TYPE_CHECKING:
from _typeshed import StrPath
from lektor.builder import PathCache
from lektor.db import Record
from lektor.types.base import RawValue
VIRTUAL_PATH_PREFIX = "git-timestamp"
class ConfigurationError(ValueError):
"""Invalid configuration setting."""
def run_git(*args: str | StrPath) -> str:
cmd = ("git", *args)
try:
proc = subprocess.run(cmd, capture_output=True, text=True, check=True)
except subprocess.CalledProcessError as exc:
if exc.stderr is not None:
sys.stderr.write(exc.stderr)
raise
return proc.stdout
def _fs_mtime(filenames: Iterable[StrPath]) -> int | None:
mtimes = []
for filename in filenames:
with suppress(OSError):
mtimes.append(os.stat(filename).st_mtime)
if len(mtimes) == 0:
return None
# (truncate to one second resolution)
return int(max(mtimes))
def _is_dirty(filename: StrPath) -> bool:
status = run_git("status", "-z", "--", filename)
return status != ""
class Timestamp(NamedTuple):
ts: int
commit_message: str | None
_FOLLOW_RENAMES_NOT_ALLOWED = (
"The follow_renames option is not supported when records have"
" multiple source files (e.g. when alts are in use)."
)
def _iter_timestamps(
filenames: Sequence[StrPath], config: Mapping[str, str]
) -> Iterator[Timestamp]:
options = ["--remove-empty"]
follow_renames = bool_from_string(config.get("follow_renames", "false"))
if follow_renames:
if len(filenames) > 1:
raise ConfigurationError(_FOLLOW_RENAMES_NOT_ALLOWED)
options.append("--follow")
with suppress(LookupError, ValueError):
threshold = float(config["follow_rename_threshold"])
if 0 < threshold < 100:
options.append(f"-M{threshold:.4f}%")
output = run_git(
"log",
"--pretty=format:%at %B",
"-z",
*options,
"--",
*filenames,
)
if not output:
ts = _fs_mtime(filenames)
else:
ts = _fs_mtime(filter(_is_dirty, filenames))
if ts is not None:
yield Timestamp(ts, None)
if output:
for line in output.split("\0"):
tstamp, _, commit_message = line.partition(" ")
yield Timestamp(int(tstamp), commit_message)
class Strategy(enum.Enum):
FIRST = "first"
EARLIEST = "earliest"
LATEST = "latest"
LAST = "last"
def get_mtime(
timestamps: Iterable[Timestamp],
ignore_commits: str | re.Pattern[str] | None = None,
strategy: Strategy = Strategy.LAST,
skip_first_commit: bool = False,
) -> int | None:
def is_not_ignored(timestamp: Timestamp) -> bool:
if ignore_commits is None:
return True
message = timestamp.commit_message
if message is None:
return True
return re.search(ignore_commits, message) is None
filtered = list(filter(is_not_ignored, timestamps))
if skip_first_commit:
filtered = filtered[:-1]
if len(filtered) == 0:
return None
if strategy is Strategy.FIRST:
return filtered[-1].ts
if strategy is Strategy.EARLIEST:
return min(timestamp.ts for timestamp in filtered)
if strategy is Strategy.LATEST:
return max(timestamp.ts for timestamp in filtered)
assert strategy is Strategy.LAST
return filtered[0].ts
def _compute_checksum(data: tuple[Timestamp, ...]) -> str:
return hashlib.sha1(pickle.dumps(data, protocol=0)).hexdigest()
class GitTimestampSource(VirtualSourceObject): # type: ignore[misc]
@classmethod
def get(cls, record: Record) -> GitTimestampSource:
def creator() -> GitTimestampSource:
return cls(record)
return get_or_create_virtual(record, VIRTUAL_PATH_PREFIX, creator)
@property
def path(self) -> str:
return f"{self.record.path}@{VIRTUAL_PATH_PREFIX}"
def get_checksum(self, path_cache: PathCache) -> str:
return _compute_checksum(self.timestamps)
@cached_property
def timestamps(self) -> tuple[Timestamp, ...]:
plugin_config: Mapping[str, str] = {}
with suppress(LookupError):
plugin_config = get_plugin(GitTimestampPlugin, self.pad.env).get_config()
source_filenames = tuple(self.iter_source_filenames())
return tuple(_iter_timestamps(source_filenames, plugin_config))
def iter_source_filenames(self) -> Iterator[StrPath]:
# Compatibility: The default implementation of
# VirtualSourceObject.iter_source_filenames in Lektor < 3.4
# returns only the primary source filename.
return self.record.iter_source_filenames() # type: ignore[no-any-return]
@dataclass
class GitTimestampDescriptor:
raw: RawValue
ignore_commits: str | re.Pattern[str] | None = None
strategy: Strategy = Strategy.LAST
skip_first_commit: bool = False
@overload
def __get__(self, obj: None) -> GitTimestampDescriptor:
...
@overload
def __get__(self, obj: Record) -> datetime.datetime | jinja2.Undefined:
...
def __get__(
self, obj: Record | None, type_: object = None
) -> GitTimestampDescriptor | datetime.datetime | jinja2.Undefined:
if obj is None:
return self
ctx = get_ctx()
src = GitTimestampSource.get(obj)
if ctx:
ctx.record_virtual_dependency(src)
mtime = get_mtime(
src.timestamps,
ignore_commits=self.ignore_commits,
strategy=self.strategy,
skip_first_commit=self.skip_first_commit,
)
if mtime is None:
return self.raw.missing_value( # type: ignore[no-any-return]
"no suitable git timestamp exists"
)
return datetime.datetime.fromtimestamp(mtime)
class GitTimestampType(DateTimeType): # type: ignore[misc]
def value_from_raw(
self, raw: RawValue
) -> GitTimestampDescriptor | datetime.datetime:
value = super().value_from_raw(raw)
if not jinja2.is_undefined(value):
assert isinstance(value, datetime.datetime)
return value
options = self.options
try:
strategy = Strategy(options["strategy"])
except (KeyError, ValueError):
strategy = Strategy.LAST
return GitTimestampDescriptor(
raw,
ignore_commits=options.get("ignore_commits"),
strategy=strategy,
skip_first_commit=bool_from_string(options.get("skip_first_commit", False)),
)
class GitTimestampPlugin(Plugin): # type: ignore[misc]
name = "git-timestamp"
description = "Lektor type to deduce page modification time from git"
def on_setup_env(self, **extra: Any) -> None:
env = self.env
env.add_type(GitTimestampType)
env.virtualpathresolver(VIRTUAL_PATH_PREFIX)(self.resolve_virtual_path)
@staticmethod
def resolve_virtual_path(
record: Record, pieces: Sequence[str]
) -> GitTimestampSource | None:
if len(pieces) == 0:
return GitTimestampSource.get(record)
return None