onelook 0.1.2__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
onelook/hashing.py ADDED
@@ -0,0 +1,280 @@
1
+ """Content hashes, path patterns and the combined fingerprint.
2
+
3
+ Everything onelook claims rests on three definitions, all in this file.
4
+
5
+ File hash
6
+ SHA-256 of the file's bytes. In the default newline mode ``"lf"`` every
7
+ CRLF pair (bytes 0D 0A) is replaced by a single LF (0A) before hashing;
8
+ a CR that is not followed by LF is left alone. In mode ``"exact"`` the
9
+ bytes are hashed as they are. The recorded size is the number of bytes
10
+ that were hashed.
11
+
12
+ Paths
13
+ Relative to the directory that holds the ledger, with ``/`` as the
14
+ separator on every operating system, case preserved as stored on disk.
15
+
16
+ Combined hash (set hash and engine fingerprint)
17
+ SHA-256 of the ASCII line ``onelook-fingerprint-v1`` followed by LF,
18
+ then, for each file in ascending order of its path (compared by Unicode
19
+ code point), the path in UTF-8, one NUL byte, the 64 lowercase hex
20
+ characters of the file hash, and LF.
21
+
22
+ Patterns
23
+ ``*`` matches within one path segment, ``?`` one character, ``[abc]`` a
24
+ character class (``[!abc]`` negated), and a segment that is exactly
25
+ ``**`` matches any number of segments including none. A pattern matches
26
+ a file if it matches the file's path or any directory above it, so
27
+ ``src`` selects everything under ``src``. Include patterns are anchored
28
+ at the ledger directory. An ignore pattern without ``/`` is compared
29
+ with every segment of the path, so ``__pycache__`` and ``*.pyc`` apply
30
+ at any depth. Backslashes in patterns are read as ``/``. Matching is
31
+ case-sensitive on every operating system. Directory symlinks are not
32
+ followed; file symlinks are read through.
33
+ """
34
+
35
+ from __future__ import annotations
36
+
37
+ import hashlib
38
+ import os
39
+ import re
40
+ from dataclasses import dataclass
41
+ from typing import Iterable, Sequence
42
+
43
+ from ._errors import OnelookError
44
+
45
+ NEWLINE_MODES = ("lf", "exact")
46
+ FINGERPRINT_HEADER = b"onelook-fingerprint-v1\n"
47
+ DEFAULT_IGNORE = (".git", "__pycache__", "*.pyc")
48
+
49
+ _CHUNK = 1 << 16
50
+
51
+
52
+ def check_newlines(newlines: str) -> str:
53
+ if newlines not in NEWLINE_MODES:
54
+ raise OnelookError(
55
+ f"unknown newline mode {newlines!r}; use one of {', '.join(NEWLINE_MODES)}"
56
+ )
57
+ return newlines
58
+
59
+
60
+ def hash_bytes(data: bytes, newlines: str = "lf") -> tuple[str, int]:
61
+ """Return ``(sha256 hex, number of bytes hashed)`` for in-memory data."""
62
+ check_newlines(newlines)
63
+ if newlines == "lf":
64
+ data = data.replace(b"\r\n", b"\n")
65
+ return hashlib.sha256(data).hexdigest(), len(data)
66
+
67
+
68
+ def hash_file(path: str | os.PathLike, newlines: str = "lf") -> tuple[str, int]:
69
+ """Return ``(sha256 hex, number of bytes hashed)`` for a file."""
70
+ check_newlines(newlines)
71
+ digest = hashlib.sha256()
72
+ size = 0
73
+ carry = b""
74
+ try:
75
+ with open(path, "rb") as handle:
76
+ while True:
77
+ chunk = handle.read(_CHUNK)
78
+ if not chunk:
79
+ break
80
+ if newlines == "lf":
81
+ # A CR at the end of a chunk may be the first half of a
82
+ # CRLF pair, so it is held back until the next chunk.
83
+ chunk = carry + chunk
84
+ carry = b""
85
+ if chunk.endswith(b"\r"):
86
+ chunk, carry = chunk[:-1], b"\r"
87
+ chunk = chunk.replace(b"\r\n", b"\n")
88
+ digest.update(chunk)
89
+ size += len(chunk)
90
+ except OSError as exc:
91
+ raise OnelookError(f"cannot read {os.fspath(path)}: {exc.strerror or exc}") from exc
92
+ if carry:
93
+ digest.update(carry)
94
+ size += len(carry)
95
+ return digest.hexdigest(), size
96
+
97
+
98
+ def combine(entries: Iterable[tuple[str, str]]) -> str:
99
+ """Combine ``(path, file hash)`` pairs into one hash; see the module text."""
100
+ digest = hashlib.sha256(FINGERPRINT_HEADER)
101
+ for path, file_hash in sorted(entries):
102
+ digest.update(path.encode("utf-8", "surrogateescape"))
103
+ digest.update(b"\0")
104
+ digest.update(file_hash.encode("ascii"))
105
+ digest.update(b"\n")
106
+ return digest.hexdigest()
107
+
108
+
109
+ # --------------------------------------------------------------------------
110
+ # Patterns
111
+
112
+
113
+ def clean_pattern(text: str) -> str:
114
+ """Normalise a pattern: ``/`` separators, no ``.`` or empty segments."""
115
+ segments = [s for s in text.replace("\\", "/").split("/") if s not in ("", ".")]
116
+ if ".." in segments:
117
+ raise OnelookError(f"pattern {text!r} must not contain '..'")
118
+ return "/".join(segments)
119
+
120
+
121
+ def escape_glob(path: str) -> str:
122
+ """Escape ``*``, ``?`` and ``[`` so a literal path can be used as a pattern."""
123
+ return re.sub(r"([*?\[])", r"[\1]", path)
124
+
125
+
126
+ def _segment_regex(segment: str) -> str:
127
+ out = []
128
+ i = 0
129
+ while i < len(segment):
130
+ char = segment[i]
131
+ if char == "*":
132
+ out.append("[^/]*")
133
+ elif char == "?":
134
+ out.append("[^/]")
135
+ elif char == "[":
136
+ end = segment.find("]", i + 2)
137
+ if end == -1:
138
+ out.append(re.escape(char))
139
+ else:
140
+ body = segment[i + 1 : end]
141
+ negate = body.startswith("!")
142
+ if negate:
143
+ body = body[1:]
144
+ inner = "".join(c if c == "-" else re.escape(c) for c in body)
145
+ out.append("[" + ("^/" if negate else "") + inner + "]")
146
+ i = end
147
+ else:
148
+ out.append(re.escape(char))
149
+ i += 1
150
+ return "".join(out)
151
+
152
+
153
+ class Pattern:
154
+ """One compiled include or ignore pattern."""
155
+
156
+ def __init__(self, text: str, floating: bool = False):
157
+ self.text = clean_pattern(text)
158
+ self.segments = self.text.split("/") if self.text else []
159
+ self.floating = (
160
+ floating and len(self.segments) == 1 and self.segments[0] != "**"
161
+ )
162
+ self._segment_res = [
163
+ None if s == "**" else re.compile(_segment_regex(s) + r"\Z", re.S)
164
+ for s in self.segments
165
+ ]
166
+ body = []
167
+ last = len(self.segments) - 1
168
+ for index, segment in enumerate(self.segments):
169
+ if segment == "**":
170
+ body.append(".*" if index == last else "(?:[^/]+/)*")
171
+ else:
172
+ body.append(_segment_regex(segment) + ("" if index == last else "/"))
173
+ if not self.segments:
174
+ regex = ".*"
175
+ else:
176
+ prefix = "(?:.*/)?" if self.floating else ""
177
+ regex = prefix + "".join(body) + "(?:/.*)?"
178
+ self._regex = re.compile(regex + r"\Z", re.S)
179
+
180
+ def matches(self, path: str) -> bool:
181
+ """True if the pattern selects this ``/``-separated relative path."""
182
+ return self._regex.match(path) is not None
183
+
184
+ def may_match_under(self, directory: Sequence[str]) -> bool:
185
+ """True if some path below this directory could match (used to prune)."""
186
+ if self.floating:
187
+ return True
188
+ for index, name in enumerate(directory):
189
+ if index >= len(self.segments):
190
+ return True
191
+ compiled = self._segment_res[index]
192
+ if compiled is None:
193
+ return True
194
+ if compiled.match(name) is None:
195
+ return False
196
+ return True
197
+
198
+
199
+ def expand(
200
+ root: str | os.PathLike,
201
+ include: Sequence[str],
202
+ ignore: Sequence[str] = (),
203
+ exclude: Iterable[str] = (),
204
+ ) -> list[str]:
205
+ """List the files under ``root`` selected by the patterns.
206
+
207
+ Returns ``/``-separated paths relative to ``root``, sorted. ``exclude``
208
+ holds exact relative paths that are never returned (the ledger itself).
209
+ """
210
+ root = os.fspath(root)
211
+ includes = [Pattern(p) for p in include]
212
+ ignores = [Pattern(p, floating=True) for p in ignore]
213
+ excluded = set(exclude)
214
+ found: list[str] = []
215
+
216
+ def walk(directory: str, segments: list[str]) -> None:
217
+ try:
218
+ names = sorted(os.listdir(directory))
219
+ except OSError as exc:
220
+ raise OnelookError(f"cannot list {directory}: {exc.strerror or exc}") from exc
221
+ for name in names:
222
+ here = segments + [name]
223
+ relative = "/".join(here)
224
+ if any(p.matches(relative) for p in ignores):
225
+ continue
226
+ full = os.path.join(directory, name)
227
+ if os.path.isdir(full):
228
+ if os.path.islink(full):
229
+ continue
230
+ if any(p.may_match_under(here) for p in includes):
231
+ walk(full, here)
232
+ elif os.path.isfile(full):
233
+ if relative not in excluded and any(p.matches(relative) for p in includes):
234
+ found.append(relative)
235
+
236
+ if includes:
237
+ walk(root, [])
238
+ return sorted(found)
239
+
240
+
241
+ # --------------------------------------------------------------------------
242
+ # Fingerprint
243
+
244
+
245
+ @dataclass(frozen=True)
246
+ class Fingerprint:
247
+ """The combined hash of a set of files, with the per-file hashes."""
248
+
249
+ hash: str
250
+ files: tuple[tuple[str, str], ...]
251
+ newlines: str
252
+
253
+ def __str__(self) -> str:
254
+ return self.hash
255
+
256
+
257
+ def fingerprint(
258
+ root: str | os.PathLike,
259
+ include: Sequence[str],
260
+ ignore: Sequence[str] = DEFAULT_IGNORE,
261
+ newlines: str = "lf",
262
+ exclude: Iterable[str] = (),
263
+ ) -> Fingerprint:
264
+ """Fingerprint the files under ``root`` selected by the patterns.
265
+
266
+ Raises :class:`OnelookError` when no file is selected, because a
267
+ fingerprint of nothing would compare equal to any other empty selection.
268
+ """
269
+ check_newlines(newlines)
270
+ root = os.fspath(root)
271
+ paths = expand(root, include, ignore, exclude)
272
+ if not paths:
273
+ raise OnelookError(
274
+ "no files match the engine patterns: " + ", ".join(include or ["(none)"])
275
+ )
276
+ files = tuple(
277
+ (path, hash_file(os.path.join(root, *path.split("/")), newlines)[0])
278
+ for path in paths
279
+ )
280
+ return Fingerprint(hash=combine(files), files=files, newlines=newlines)