blob: d8571ba4dce12a570c8f326c7e581a70da4835c9 (
plain)
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
|
"""Small filesystem helpers shared by service modules."""
import filecmp
import hashlib
import json
from pathlib import Path
def file_sha256(path: Path) -> str:
digest = hashlib.sha256()
with path.open("rb") as stream:
for chunk in iter(lambda: stream.read(1024 * 1024), b""):
digest.update(chunk)
return digest.hexdigest()
def files_match(file_a: Path, file_b: Path) -> bool:
try:
return file_a.is_file() and file_b.is_file() and filecmp.cmp(file_a, file_b, shallow=False)
except OSError:
return False
def read_json(path: Path) -> dict:
try:
with path.open("r", encoding="utf-8") as stream:
payload = json.load(stream)
return payload if isinstance(payload, dict) else {}
except (OSError, ValueError, TypeError):
return {}
def write_json(path: Path, payload: dict) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
with path.open("w", encoding="utf-8") as stream:
json.dump(payload, stream, indent=2)
|