stepup-data 4.3.0a0__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.
@@ -0,0 +1,515 @@
1
+ # SPDX-FileCopyrightText: 2024 Toon Verstraelen <Toon.Verstraelen@UGent.be>
2
+ # SPDX-License-Identifier: LGPL-3.0-or-later
3
+ """Format of inventory files, with the computation, comparison and reading of their records.
4
+
5
+ An inventory is a JSON Lines file, see `docs/tutorials/inventory_files.md`.
6
+ The first line is a header and every other line is the record of one file.
7
+ """
8
+
9
+ import contextlib
10
+ import hashlib
11
+ import json
12
+ import os
13
+ import re
14
+ import stat
15
+ from collections.abc import Iterator
16
+ from pathlib import PureWindowsPath
17
+ from typing import Any, BinaryIO
18
+
19
+ import attrs
20
+
21
+ from stepup.core.path import Path, StrPath
22
+ from stepup.core.platform.oscompat import file_modes_available
23
+ from stepup.core.utils import open_regular_file
24
+
25
+ __all__ = (
26
+ "HASH_ALGORITHMS",
27
+ "FileRecord",
28
+ "InventoryHeader",
29
+ "InventoryReader",
30
+ "LinkRecord",
31
+ "check_record",
32
+ "compute_record",
33
+ "format_header",
34
+ "format_record",
35
+ "open_inventory",
36
+ )
37
+
38
+
39
+ INVENTORY_FORMAT = "stepup-inventory"
40
+ """The value of the `format` key in the header, which tells an inventory apart from other files."""
41
+
42
+ INVENTORY_VERSION = 1
43
+ """The value of the `version` key in the header,
44
+ which changes with every incompatible change of the format."""
45
+
46
+ HEADER_KEYS = frozenset(["fields", "format", "version"])
47
+ """The keys of the header on the first line of an inventory."""
48
+
49
+ LINK_KEYS = frozenset(["link", "path"])
50
+ """The keys of the record of a symbolic link."""
51
+
52
+ HASH_ALGORITHMS = tuple(
53
+ sorted(name for name in hashlib.algorithms_guaranteed if not name.startswith("shake_"))
54
+ )
55
+ """The hash algorithms that can digest the regular files in an inventory.
56
+
57
+ The `shake_*` algorithms are left out, because their digests have no fixed length.
58
+ """
59
+
60
+ MAX_LINE_LENGTH = 65536
61
+ """The length in bytes of the longest line that is read from an inventory.
62
+
63
+ A record is much shorter, so a longer line means that the file is not an inventory,
64
+ e.g. a data file given where the inventory belongs, which is then rejected without loading it.
65
+ """
66
+
67
+ MODE_PATTERN = re.compile("[r-][w-][xsS-][r-][w-][xsS-][r-][w-][xtT-]")
68
+ """The permission bits of a file, as formatted by `stat.filemode` without the file type."""
69
+
70
+
71
+ @attrs.define(frozen=True)
72
+ class InventoryHeader:
73
+ """The properties of an inventory that apply to all of its records."""
74
+
75
+ hash_algorithm: str | None = attrs.field(
76
+ validator=attrs.validators.optional(attrs.validators.in_(HASH_ALGORITHMS))
77
+ )
78
+ """The name of the `hashlib` algorithm that digests the regular files,
79
+ or `None` when no digests are recorded."""
80
+
81
+ mode: bool = attrs.field(default=False)
82
+ """Whether the permission bits of the regular files are recorded."""
83
+
84
+ @property
85
+ def fields(self) -> list[str]:
86
+ """The sorted keys of the record of a regular file."""
87
+ fields = ["path", "size"]
88
+ if self.hash_algorithm is not None:
89
+ fields.append(self.hash_algorithm)
90
+ if self.mode:
91
+ fields.append("mode")
92
+ return sorted(fields)
93
+
94
+
95
+ @attrs.define(frozen=True)
96
+ class FileRecord:
97
+ """The record of a regular file in an inventory."""
98
+
99
+ path: str = attrs.field()
100
+ """The file, relative to the parent of the inventory, with `/` separators."""
101
+
102
+ digest: str | None = attrs.field()
103
+ """The digest of the file contents, in lowercase hexadecimal digits,
104
+ or `None` when digests are not recorded."""
105
+
106
+ size: int = attrs.field()
107
+ """The size of the file in bytes."""
108
+
109
+ mode: str | None = attrs.field(default=None)
110
+ """The permission bits of the file, e.g. `rw-r--r--`, or `None` when they are not recorded."""
111
+
112
+
113
+ @attrs.define(frozen=True)
114
+ class LinkRecord:
115
+ """The record of a symbolic link in an inventory.
116
+
117
+ The link is not followed, so the record only describes the link itself.
118
+ """
119
+
120
+ path: str = attrs.field()
121
+ """The link, relative to the parent of the inventory, with `/` separators."""
122
+
123
+ target: str = attrs.field()
124
+ """The target as stored in the link."""
125
+
126
+
127
+ Record = FileRecord | LinkRecord
128
+
129
+
130
+ def compute_record(
131
+ path: StrPath, root: StrPath, hash_algorithm: str | None = "md5", mode: bool = False
132
+ ) -> Record:
133
+ """Compute the record of a file for an inventory.
134
+
135
+ Parameters
136
+ ----------
137
+ path
138
+ The file to describe, relative to the current working directory.
139
+ A symbolic link is described as a link and is never followed.
140
+ root
141
+ The parent of the inventory, to which the path in the record is relative.
142
+ hash_algorithm
143
+ The name of the `hashlib` algorithm that digests a regular file,
144
+ or `None` to leave out the digest, so that the contents of the file are not read.
145
+ mode
146
+ Whether to record the permission bits of a regular file.
147
+
148
+ Returns
149
+ -------
150
+ record
151
+ The record of the regular file or of the symbolic link.
152
+
153
+ Raises
154
+ ------
155
+ NotARegularFileError
156
+ When the file is neither a regular file nor a symbolic link, e.g. a directory or a FIFO.
157
+ """
158
+ path = Path(path)
159
+ relpath = str(path.relpath(root).normpath())
160
+ reason = _check_record_path(relpath)
161
+ if reason is not None:
162
+ raise ValueError(f"Cannot write {path} in an inventory, because its path {reason}.")
163
+ if stat.S_ISLNK(path.stat(follow_symlinks=False).st_mode):
164
+ return LinkRecord(relpath, str(path.readlink()))
165
+ with open(path, "rb", opener=open_regular_file) as fh:
166
+ st = os.fstat(fh.fileno())
167
+ digest = None
168
+ if hash_algorithm is not None:
169
+ digest = hashlib.file_digest(fh, hash_algorithm).hexdigest()
170
+ return FileRecord(relpath, digest, st.st_size, stat.filemode(st.st_mode)[1:] if mode else None)
171
+
172
+
173
+ def check_record(new: Record, ref: Record):
174
+ """Verify that a newly computed record is consistent with the reference.
175
+
176
+ The paths of the two records are not compared.
177
+ The digests are only compared when the reference has one.
178
+ The permission bits are only compared when the reference has them
179
+ and when files have permission bits on this platform,
180
+ see `file_modes_available()` in `stepup.core.platform.oscompat`.
181
+
182
+ Raises
183
+ ------
184
+ TypeError
185
+ When one is a symbolic link and the other is not.
186
+ ValueError
187
+ When the size, the digest, the permission bits or the link target differ.
188
+ """
189
+ if isinstance(ref, LinkRecord):
190
+ if not isinstance(new, LinkRecord):
191
+ raise TypeError(f"Expected a symbolic link but got a regular file: {ref.path}")
192
+ if new.target != ref.target:
193
+ raise ValueError(f"Link target should be {ref.target} but got {new.target}: {ref.path}")
194
+ return
195
+ if not isinstance(new, FileRecord):
196
+ raise TypeError(f"Expected a regular file but got a symbolic link: {ref.path}")
197
+ if new.size != ref.size:
198
+ raise ValueError(f"File size should be {ref.size} but got {new.size}: {ref.path}")
199
+ if ref.mode is not None and file_modes_available() and new.mode != ref.mode:
200
+ raise ValueError(f"File mode should be {ref.mode} but got {new.mode}: {ref.path}")
201
+ if ref.digest is not None and new.digest != ref.digest:
202
+ raise ValueError(f"File digest mismatch: {ref.path}")
203
+
204
+
205
+ def _dump_line(data: dict[str, Any]) -> str:
206
+ """Format one line of an inventory, without the trailing newline."""
207
+ return json.dumps(data, sort_keys=True, separators=(",", ":"), ensure_ascii=False)
208
+
209
+
210
+ def format_header(header: InventoryHeader) -> str:
211
+ """Format the first line of an inventory, without the trailing newline."""
212
+ return _dump_line(
213
+ {"fields": header.fields, "format": INVENTORY_FORMAT, "version": INVENTORY_VERSION}
214
+ )
215
+
216
+
217
+ def format_record(record: Record, header: InventoryHeader) -> str:
218
+ """Format the line of one record in an inventory, without the trailing newline.
219
+
220
+ Raises
221
+ ------
222
+ ValueError
223
+ When the presence of the digest or the permission bits in a file record
224
+ does not match the header.
225
+ """
226
+ if isinstance(record, LinkRecord):
227
+ return _dump_line({"link": record.target, "path": record.path})
228
+ if (record.digest is not None) != (header.hash_algorithm is not None):
229
+ raise ValueError(f"The digest does not match the inventory header: {record.path}")
230
+ if (record.mode is not None) != header.mode:
231
+ raise ValueError(f"The permission bits do not match the inventory header: {record.path}")
232
+ data = {"path": record.path, "size": record.size}
233
+ if header.hash_algorithm is not None:
234
+ data[header.hash_algorithm] = record.digest
235
+ if header.mode:
236
+ data["mode"] = record.mode
237
+ return _dump_line(data)
238
+
239
+
240
+ @attrs.define
241
+ class InventoryReader:
242
+ """Iterate over the records of an open inventory, validating each one.
243
+
244
+ Create it with `open_inventory()`, which reads and validates the header first.
245
+ """
246
+
247
+ path: Path = attrs.field()
248
+ """The inventory file, used in the messages."""
249
+
250
+ header: InventoryHeader = attrs.field()
251
+ """The header on the first line of the inventory."""
252
+
253
+ _fh: BinaryIO = attrs.field()
254
+ """The inventory file, open in binary mode, of which the header has been read."""
255
+
256
+ def __iter__(self) -> Iterator[Record]:
257
+ """Read and validate the remaining lines, one record at a time.
258
+
259
+ Raises
260
+ ------
261
+ ValueError
262
+ When a line is not a valid record, or when two records have the same path.
263
+ """
264
+ seen = set()
265
+ iline = 2
266
+ while True:
267
+ data = _read_line(self.path, self._fh, iline)
268
+ if data is None:
269
+ return
270
+ record = _load_record(self.path, self.header, iline, data)
271
+ if record.path in seen:
272
+ raise _not_an_inventory(self.path, f"line {iline} repeats the path {record.path!r}")
273
+ seen.add(record.path)
274
+ yield record
275
+ iline += 1
276
+
277
+
278
+ @contextlib.contextmanager
279
+ def open_inventory(path_inventory: StrPath) -> Iterator[InventoryReader]:
280
+ """Open an inventory and validate its header.
281
+
282
+ The records are read one line at a time while iterating over the reader,
283
+ so an inventory is never loaded as a whole.
284
+
285
+ Parameters
286
+ ----------
287
+ path_inventory
288
+ The inventory to read.
289
+
290
+ Returns
291
+ -------
292
+ reader
293
+ The reader, of which `header` is the validated header
294
+ and which yields the records when iterating over it.
295
+
296
+ Raises
297
+ ------
298
+ ValueError
299
+ When the file does not exist or when it is not an inventory in a supported version.
300
+ The message is the complete diagnosis.
301
+
302
+ Examples
303
+ --------
304
+ ```python
305
+ with open_inventory("inventory.jsonl") as reader:
306
+ for record in reader:
307
+ print(record.path)
308
+ ```
309
+ """
310
+ path_inventory = Path(path_inventory)
311
+ if not path_inventory.is_file():
312
+ raise ValueError(
313
+ f"The inventory {path_inventory} does not exist. Write it with `sd-make-inventory`."
314
+ )
315
+ with open(path_inventory, "rb") as fh:
316
+ data = _read_line(path_inventory, fh, 1)
317
+ if data is None:
318
+ raise _not_an_inventory(path_inventory, "it is empty")
319
+ yield InventoryReader(path_inventory, _load_header(path_inventory, data), fh)
320
+
321
+
322
+ def _read_line(path_inventory: Path, fh: BinaryIO, iline: int) -> Any:
323
+ """Read the next line of an inventory as JSON.
324
+
325
+ Every line is decoded on its own,
326
+ so that invalid UTF-8 is reported on the line where it occurs.
327
+
328
+ Parameters
329
+ ----------
330
+ path_inventory
331
+ The inventory file, used in the messages.
332
+ fh
333
+ The inventory file, open in binary mode.
334
+ iline
335
+ The 1-based number of the line to read, used in the messages.
336
+
337
+ Returns
338
+ -------
339
+ data
340
+ The JSON data on the line, or `None` at the end of the file.
341
+ """
342
+ line = fh.readline(MAX_LINE_LENGTH)
343
+ if line == b"":
344
+ return None
345
+ if not line.endswith(b"\n"):
346
+ if len(line) == MAX_LINE_LENGTH:
347
+ reason = f"line {iline} is longer than {MAX_LINE_LENGTH} bytes"
348
+ else:
349
+ reason = f"line {iline} does not end with a newline"
350
+ raise _not_an_inventory(path_inventory, reason)
351
+ try:
352
+ text = line.decode("utf-8")
353
+ except UnicodeDecodeError as exc:
354
+ raise _not_an_inventory(path_inventory, f"line {iline} is not valid UTF-8") from exc
355
+ try:
356
+ return json.loads(text)
357
+ except ValueError as exc:
358
+ raise _not_an_inventory(path_inventory, f"line {iline} is not valid JSON") from exc
359
+
360
+
361
+ def _load_header(path_inventory: Path, data: Any) -> InventoryHeader:
362
+ """Validate the header on the first line of an inventory.
363
+
364
+ Parameters
365
+ ----------
366
+ path_inventory
367
+ The inventory file, used in the messages.
368
+ data
369
+ The JSON data on the first line.
370
+
371
+ Returns
372
+ -------
373
+ header
374
+ The validated header.
375
+ """
376
+ if not isinstance(data, dict) or data.get("format") != INVENTORY_FORMAT:
377
+ raise _not_an_inventory(
378
+ path_inventory, f"line 1 is not a JSON object with format {INVENTORY_FORMAT!r}"
379
+ )
380
+ version = data.get("version")
381
+ if type(version) is not int or version != INVENTORY_VERSION:
382
+ raise ValueError(
383
+ f"The inventory {path_inventory} has version {version!r}, "
384
+ f"while this version of StepUp Data reads version {INVENTORY_VERSION!r}. "
385
+ "Write it again with `sd-make-inventory`."
386
+ )
387
+ if data.keys() != HEADER_KEYS:
388
+ raise _not_an_inventory(
389
+ path_inventory, f"the keys on line 1 are not {', '.join(sorted(HEADER_KEYS))}"
390
+ )
391
+ fields = data["fields"]
392
+ if not (isinstance(fields, list) and all(isinstance(field, str) for field in fields)):
393
+ raise _not_an_inventory(path_inventory, "the fields on line 1 are not a list of strings")
394
+ algorithms = [field for field in fields if field not in ("mode", "path", "size")]
395
+ if len(algorithms) > 1 or not all(algorithm in HASH_ALGORITHMS for algorithm in algorithms):
396
+ raise _not_an_inventory(
397
+ path_inventory,
398
+ "the fields on line 1 are not path, size, optionally mode "
399
+ f"and at most one hash algorithm out of {', '.join(HASH_ALGORITHMS)}",
400
+ )
401
+ header = InventoryHeader(algorithms[0] if algorithms else None, "mode" in fields)
402
+ if fields != header.fields:
403
+ raise _not_an_inventory(
404
+ path_inventory,
405
+ f"the fields on line 1 are not the sorted list {', '.join(header.fields)}",
406
+ )
407
+ return header
408
+
409
+
410
+ def _load_record(path_inventory: Path, header: InventoryHeader, iline: int, data: Any) -> Record:
411
+ """Validate the record of one file in an inventory.
412
+
413
+ Parameters
414
+ ----------
415
+ path_inventory
416
+ The inventory file, used in the messages.
417
+ header
418
+ The header of the inventory, which defines the keys of a regular file record.
419
+ iline
420
+ The 1-based number of the line, used in the messages.
421
+ data
422
+ The JSON data on the line.
423
+
424
+ Returns
425
+ -------
426
+ record
427
+ The validated record.
428
+ """
429
+ where = f"line {iline}"
430
+ if isinstance(data, dict) and "link" in data:
431
+ if data.keys() != LINK_KEYS:
432
+ keys = ", ".join(sorted(LINK_KEYS))
433
+ raise _not_an_inventory(
434
+ path_inventory, f"{where} is a link without exactly the keys {keys}"
435
+ )
436
+ target = data["link"]
437
+ if not (isinstance(target, str) and len(target) > 0):
438
+ raise _not_an_inventory(
439
+ path_inventory, f"the link target on {where} is not a non-empty string"
440
+ )
441
+ return LinkRecord(_load_record_path(path_inventory, where, data["path"]), target)
442
+ if not isinstance(data, dict) or data.keys() != set(header.fields):
443
+ raise _not_an_inventory(
444
+ path_inventory,
445
+ f"{where} is not a JSON object with the keys {', '.join(header.fields)}",
446
+ )
447
+ path = _load_record_path(path_inventory, where, data["path"])
448
+ size = data["size"]
449
+ if not isinstance(size, int) or isinstance(size, bool) or size < 0:
450
+ raise _not_an_inventory(path_inventory, f"the size on {where} is not a non-negative int")
451
+ digest = None
452
+ if header.hash_algorithm is not None:
453
+ digest = data[header.hash_algorithm]
454
+ num_digits = 2 * hashlib.new(header.hash_algorithm).digest_size
455
+ if not (isinstance(digest, str) and re.fullmatch(f"[0-9a-f]{{{num_digits}}}", digest)):
456
+ raise _not_an_inventory(
457
+ path_inventory,
458
+ f"the {header.hash_algorithm} digest on {where} "
459
+ f"does not have {num_digits} lowercase hexadecimal digits",
460
+ )
461
+ mode = data.get("mode")
462
+ if header.mode and not (isinstance(mode, str) and MODE_PATTERN.fullmatch(mode)):
463
+ raise _not_an_inventory(
464
+ path_inventory, f"the mode on {where} does not have the form rw-r--r--"
465
+ )
466
+ return FileRecord(path, digest, size, mode)
467
+
468
+
469
+ def _load_record_path(path_inventory: Path, where: str, path: Any) -> str:
470
+ """Validate the path of a record, see `_check_record_path`."""
471
+ reason = _check_record_path(path)
472
+ if reason is not None:
473
+ raise _not_an_inventory(path_inventory, f"the path on {where} {reason}")
474
+ return path
475
+
476
+
477
+ def _check_record_path(path: Any) -> str | None:
478
+ """Check that a path can be written in an inventory.
479
+
480
+ A valid path is a non-empty string that is relative, normalized,
481
+ uses `/` as separator and does not name a directory.
482
+ It may start with `../`.
483
+
484
+ Parameters
485
+ ----------
486
+ path
487
+ The path in the record of a file.
488
+
489
+ Returns
490
+ -------
491
+ reason
492
+ `None` for a valid path, otherwise why it is invalid,
493
+ phrased to complete a sentence that starts with the path.
494
+ """
495
+ if not (isinstance(path, str) and len(path) > 0):
496
+ return "is not a non-empty string"
497
+ if "\\" in path:
498
+ return f"contains a backslash: {path}"
499
+ if path.startswith("/") or PureWindowsPath(path).is_absolute():
500
+ return f"is absolute: {path}"
501
+ if Path(path).normpath() != path or Path(path).name in (".", ".."):
502
+ return f"is not the normalized path of a file: {path}"
503
+ return None
504
+
505
+
506
+ def _not_an_inventory(path_inventory: Path, reason: str) -> ValueError:
507
+ """Create the error for a file that is not an inventory in the current format.
508
+
509
+ The message does not suggest writing the inventory to the same path,
510
+ because the file may well be a data file that was given where the inventory belongs.
511
+ """
512
+ return ValueError(
513
+ f"The file {path_inventory} is not an inventory written by `sd-make-inventory`, "
514
+ f"because {reason}."
515
+ )