-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsource_cache.py
More file actions
40 lines (32 loc) · 1.01 KB
/
Copy pathsource_cache.py
File metadata and controls
40 lines (32 loc) · 1.01 KB
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
import hashlib
import json
from pathlib import Path
def file_sha256(path: Path) -> str:
digest = hashlib.sha256()
with open(path, "rb") as file:
for chunk in iter(lambda: file.read(1024 * 1024), b""):
digest.update(chunk)
return digest.hexdigest()
def file_signature(path: str) -> dict:
source = Path(path)
stat = source.stat()
return {
"path": str(source.resolve()),
"size": stat.st_size,
"mtime_ns": stat.st_mtime_ns,
"sha256": file_sha256(source),
}
def read_json(path: Path):
path = Path(path)
if not path.exists():
return None
try:
with open(path, "r", encoding="utf-8") as file:
return json.load(file)
except (OSError, json.JSONDecodeError):
return None
def write_json(path: Path, payload: dict) -> None:
path = Path(path)
path.parent.mkdir(parents=True, exist_ok=True)
with open(path, "w", encoding="utf-8") as file:
json.dump(payload, file, ensure_ascii=False, indent=2)