mirror of
https://github.com/malmeloo/FindMy.py.git
synced 2026-04-18 00:53:56 +02:00
refactor(reports): improve Serializable base class
This commit is contained in:
34
findmy/util/files.py
Normal file
34
findmy/util/files.py
Normal file
@@ -0,0 +1,34 @@
|
||||
"""Utilities to simplify reading and writing data from and to files."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from collections.abc import Mapping
|
||||
from pathlib import Path
|
||||
from typing import TypeVar, cast
|
||||
|
||||
T = TypeVar("T", bound=Mapping)
|
||||
|
||||
|
||||
def save_and_return_json(data: T, dst: str | Path | None) -> T:
|
||||
"""Save and return a JSON-serializable data structure."""
|
||||
if dst is None:
|
||||
return data
|
||||
|
||||
if isinstance(dst, str):
|
||||
dst = Path(dst)
|
||||
|
||||
dst.write_text(json.dumps(data, indent=4))
|
||||
|
||||
return data
|
||||
|
||||
|
||||
def read_data_json(val: str | Path | T) -> T:
|
||||
"""Read JSON data from a file if a path is passed, or return the argument itself."""
|
||||
if isinstance(val, str):
|
||||
val = Path(val)
|
||||
|
||||
if isinstance(val, Path):
|
||||
val = cast("T", json.loads(val.read_text()))
|
||||
|
||||
return val
|
||||
Reference in New Issue
Block a user