Skip to main content

Module persistence

Module persistence 

Source
Expand description

Generic app-data path resolution and atomic JSON persistence helpers.

This module owns mechanics only: given a path and a serializable value, write it atomically; given a path, read and parse a JSON value. It has no knowledge of any particular product’s settings shape or file name — the caller supplies both.

Functions§

app_data_path
Resolve file_name inside the app’s config directory (e.g. ~/.config/<app>/settings.json on Linux). Does not create the directory; callers that write should create parents first (see write_json_atomic).
atomic_write
Write data to path atomically: write to a per-write unique temp file, fsync, then rename onto the target.
env_var_or_none
Read an environment variable, returning None for a missing or whitespace-only value. The returned value is not trimmed — callers that need a trimmed value should trim it themselves, matching how this distinguishes “unset” from “set to something”.
parse_json
Parse contents as JSON, producing a message that names path on failure. Split out from read_json_or_default so parse failures can be tested without touching the filesystem.
read_json_or_default
Read and parse path as JSON. A missing file is not an error — it returns T::default(), matching the common “no settings saved yet” case.
write_json_atomic
Serialize value to pretty JSON and write it to path atomically, creating parent directories as needed.