Preferences are kept in TOML, like every other file a person edits by hand

preferences.yaml becomes preferences.toml: config.toml and the device-config
backups were already TOML, and tomli/tomli-w already dependencies, so PyYAML
existed for this one file and is dropped. The file keeps its shape - flat
keys, only the overrides, grouped under comment headings with each entry's
help and default - and one name, PREFERENCES_FILENAME, for both call sites.

TOML refuses a whole document over one bad line, so a refused file is read
again a line at a time: a valid line keeps its typed value, a refused one
hands its right-hand side to parse_value as text. One broken hand edit still
costs only its line, and a word left unquoted (log_level = DEBUG) still reads.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Jean-Pierre MartineauandClaude Opus 5 committed 2026-09-13 12:45:22 -04:00
1 parent ec21d03c03
commit 266aca08fb
18 files changed
+135 -77

No files matched your search

+11 -1
View File
@@ -43,7 +43,7 @@ allowed to change behaviour, not just add to it.
the way out — from the session's teardown and from an `atexit` hook, so quitting, an
unwind and a crash all leave the console as they found it. Off the handheld, off a real
VT, or with no `setfont`, none of it happens and the log says which. The row is drawn on
the PicoCalc only, while the value round-trips through `preferences.yaml` everywhere.
the PicoCalc only, while the value round-trips through `preferences.toml` everywhere.
The 6×8 font's build moved into `scripts/calculinux-console-font-6x8.sh`, on its own
because its base bitmap is the Linux kernel's `font_6x8` and therefore GPL-2.0 — marked
@@ -51,6 +51,16 @@ allowed to change behaviour, not just add to it.
of the 6×12 script rather than keeping a second copy of them. Running the 6×12 script
still builds both.
### Changed
- **Preferences are kept in `preferences.toml`.** The same file as before — only what you
have changed, grouped and commented the way the Preferences page reads — in the format
`config.toml` and the device-config backups already use, so every file you edit by hand
speaks one syntax and MeshTerm no longer needs PyYAML. A `preferences.yaml` from an
earlier build is not read: set those preferences again, or copy the lines across as
`key = value` with text in quotes. A line TOML refuses costs only that line, and a word
left unquoted (`log_level = DEBUG`) is still understood.
## [0.3.2] — 2026-09-11
### Added
+1 -1
View File
@@ -58,7 +58,7 @@ sortable list you pick from is `contactlist.py` (`ContactListScreen`/`ContactRow
Setting vs preference — the other boundary, three-way and never blurred: a **setting** is
the *radio's* (`core/device_config.py`, read live from the companion, edited on Device
config); a **preference** is *MeshTerm's own behaviour* (`core/preferences.py`, defaults in
code, overrides in `preferences.yaml`, edited on the Preferences page — `ctx.preferences`,
code, overrides in `preferences.toml`, edited on the Preferences page — `ctx.preferences`,
or `preferences.current()` where there is no context to reach through); and **config** is
machine setup — paths and device profiles (`core/config.py`, `config.toml`, a text editor
only). A behaviour value belongs in the preference registry, not as a module constant and
+2 -3
View File
@@ -364,7 +364,7 @@ $ meshterm preferences set history_days 90
$ meshterm preferences reset --yes # back to the built-in defaults
```
They are kept in `~/.meshterm/preferences.yaml`, which lists only what you have changed;
They are kept in `~/.meshterm/preferences.toml`, which lists only what you have changed;
delete a line and the default takes over again.
**Config** is where things live and which device to talk to. MeshTerm runs with none of it
@@ -510,9 +510,8 @@ respective project for the authoritative terms):
| [Rich](https://github.com/Textualize/rich) | Console rendering | MIT |
| [prompt_toolkit](https://github.com/prompt-toolkit/python-prompt-toolkit) | Full-screen interactive TUI | BSD-3-Clause |
| [markdown-it-py](https://github.com/executablebooks/markdown-it-py) | CommonMark parser behind the written About pages | MIT |
| [PyYAML](https://pyyaml.org/) | The preferences file | MIT |
| [Segno](https://github.com/heuer/segno) | Pure-Python QR codes (channel share links) | BSD-3-Clause |
| [tomli](https://github.com/hukkin/tomli) / [tomli-w](https://github.com/hukkin/tomli-w) | TOML config read/write | MIT |
| [tomli](https://github.com/hukkin/tomli) / [tomli-w](https://github.com/hukkin/tomli-w) | TOML config, preferences and device-config backups | MIT |
## License
+1 -1
View File
@@ -3,7 +3,7 @@
#
# How MeshTerm itself behaves — transmit cooldown, message retries, how much history it
# keeps, whether it connects at launch — is *not* here. Those are preferences: they live
# in ~/.meshterm/preferences.yaml, and are edited on the Preferences page (or with
# in ~/.meshterm/preferences.toml, and are edited on the Preferences page (or with
# `meshterm preferences set <key> <value>`). Every one has a built-in default, so that
# file only ever lists what you have changed.
#
+3 -3
View File
@@ -98,7 +98,7 @@ of two directories from the same shell.
| --- | --- |
| `meshterm.db` | The history: every packet overheard, every trace walked, every message. **The one file `--db` moves.** |
| `config.toml` | Machine setup — device profiles, where the database lives. Yours to write; MeshTerm only reads it. |
| `preferences.yaml` | Your overrides of MeshTerm's own behaviour. Lists only what you changed. |
| `preferences.toml` | Your overrides of MeshTerm's own behaviour. Lists only what you changed. |
| `courier.json` | The outbox — queued messages, waiting and finished. |
| `admin.json` | Remembered repeater-admin passwords. |
| `devices.json` | The remembered default companion, and every device proven to speak the protocol. |
@@ -1420,7 +1420,7 @@ opening the menu to find out what one does. Values print in the form `preference
accepts back — no unit suffix on a number, `on`/`off` for a boolean. Where `VALUE` differs
from `DEFAULT`, this install has an override.
Overrides live in `preferences.yaml` in [MeshTerm's state
Overrides live in `preferences.toml` in [MeshTerm's state
directory](#where-meshterm-keeps-its-state), which lists only what you have changed; delete
a line and the default takes over again.
@@ -1438,7 +1438,7 @@ wanted it would be rendering a settings screen. A boolean prints `on`/`off` plai
a mapping; every other `.value | tostring` goes straight back in.
`set` and `reset --yes` answer `{"changes":…,"applied":[…],"path":…}`, `path` being the
`preferences.yaml` that was written.
`preferences.toml` that was written.
#### `meshterm about`, `about-author`, `discord`, `support`
+1 -1
View File
@@ -211,7 +211,7 @@ and nothing more: the default is installed either way.
**Choosing between them is a preference, not a command.** *Display → Console font* on the
Preferences page offers `6x12 (53x26)` and `6x8 (53x40)`, and it is drawn on the PicoCalc
only — it is a row about hardware no desktop has, though the value round-trips through
`preferences.yaml` on any machine. Picking one is the preview: the console loads it
`preferences.toml` on any machine. Picking one is the preview: the console loads it
immediately and the page repaints at the new row count (the kernel raises SIGWINCH on a
font change), so you look at the choice before you keep it. *Apply* keeps it; leaving the
page and discarding puts the saved font back.
+1 -1
View File
@@ -59,7 +59,7 @@ itself, isn't affiliated with MeshTerm.
Built on **MeshCore** *https://meshcore.io/* — its firmware and companion
library — with Rich, prompt_toolkit, Typer, bleak, pyserial, pycryptodome,
markdown-it-py, PyYAML, tomli/tomli-w and Segno, each under its own terms.
markdown-it-py, tomli/tomli-w and Segno, each under its own terms.
Map data **© OpenStreetMap contributors**, served as vector tiles by
**OpenFreeMap** *https://openfreemap.org/*, used under the
+2 -2
View File
@@ -26,7 +26,7 @@ from .core.connection import DeviceCommandError, is_connection_lost
from .core.device_config import DeviceConfigError
from .core.device_store import DeviceStore
from .core.instancelock import InstanceBusy, hold_instance_lock
from .core.preferences import PreferenceError, Preferences
from .core.preferences import PREFERENCES_FILENAME, PreferenceError, Preferences
from .core.selection import DeviceSelectionError
from .persistence.logging import configure_logging, get_logger, level_from_name, log_path
from .persistence.repository import Repository
@@ -240,7 +240,7 @@ def main_callback(
console = script.console() if scripted else make_console()
# Loaded before logging is configured, because how much goes in the file is one of
# them — and handed to the context afterwards so the file is not read twice.
prefs = Preferences.load(settings.config_dir / "preferences.yaml")
prefs = Preferences.load(settings.config_dir / PREFERENCES_FILENAME)
if absolute:
# An override of the preference rather than a second switch beside it: *how
# MeshTerm behaves* is a preference by this project's own rule, and a flag that
+3 -3
View File
@@ -22,7 +22,7 @@ from .core.courier_store import CourierStore
from .core.device_store import DeviceStore
from .core.discovery import DiscoveredDevice, discover_devices
from .core.mute_store import MuteStore
from .core.preferences import Preferences
from .core.preferences import PREFERENCES_FILENAME, Preferences
from .core.preferences import install as install_preferences
from .core.remote_store import RemoteStore
from .core.selection import resolve_device
@@ -55,7 +55,7 @@ class AppContext:
talk to (config directory, database, named profiles). *How MeshTerm behaves*
is ``preferences``, not this.
preferences: MeshTerm's own preferences, backed by
``<config_dir>/preferences.yaml`` and edited on the Preferences page. Defaults
``<config_dir>/preferences.toml`` and edited on the Preferences page. Defaults
to a set loaded from that file when not injected, and is installed as the
process-wide :func:`~meshterm.core.preferences.current` set so the render
layer — which has no context to reach through — reads the same values.
@@ -168,7 +168,7 @@ class AppContext:
stores built without a context still have to read them.
"""
if self.preferences is None:
self.preferences = Preferences.load(self.settings.config_dir / "preferences.yaml")
self.preferences = Preferences.load(self.settings.config_dir / PREFERENCES_FILENAME)
install_preferences(self.preferences)
if self.advert_store is None:
self.advert_store = AdvertStore(self.settings.config_dir / "adverts.json")
+64 -27
View File
@@ -1,4 +1,4 @@
"""Declarative registry of MeshTerm's own preferences, and the YAML file they live in.
"""Declarative registry of MeshTerm's own preferences, and the TOML file they live in.
The distinction this module draws is between the three kinds of "setting" the app already
had and never named apart:
@@ -22,9 +22,11 @@ away from that default, so the file is a short list of your disagreements with t
built-in behaviour rather than a snapshot that silently pins every value forever. Delete a
key (or use *Reset to defaults*) and the code's default takes over again.
The file is ``<config_dir>/preferences.yaml``, written grouped and commented so it reads
the way the page does. Reads are tolerant: an unknown key, a malformed value, or an
unparseable file costs the override, never the session.
The file is ``<config_dir>/preferences.toml``, written flat, grouped and commented so it
reads the way the page does — TOML, like ``config.toml`` and the device-config backups,
so every file a person edits by hand speaks one syntax. Reads are tolerant: an unknown
key, a malformed value, or a line TOML refuses costs that one override, never the rest of
the file and never the session.
Two access paths, deliberately:
@@ -37,6 +39,7 @@ Two access paths, deliberately:
from __future__ import annotations
import sys
from collections.abc import Mapping
from dataclasses import dataclass
from pathlib import Path
@@ -47,6 +50,11 @@ from .courier_store import DONE_CAP
from .geo import DEFAULT_VIEW_FRACTION
from .watch_store import ALERT_CAP, DEFAULT_SILENCE_HOURS, OFF, SILENCE_CHOICES_H
if sys.version_info >= (3, 11):
import tomllib
else: # pragma: no cover - exercised only on 3.10
import tomli as tomllib
#: Display groups, in the order the page and the file present them. The order is the
#: order a session happens in — what MeshTerm puts on the air, how loud, what it watches
#: for, how it draws the world, what it keeps, and how it paints. Nothing sorts
@@ -77,7 +85,7 @@ class PrefSpec:
Attributes:
key: Canonical key — the attribute name on :class:`Preferences`, and the key in
the YAML file.
the TOML file.
label: Human-friendly name, as the page's SETTING lane shows it.
help: One-line description, as the page's DESCRIPTION lane shows it.
group: One of :data:`GROUPS`.
@@ -191,7 +199,7 @@ _LOG_LEVEL_CHOICES: dict[str, str] = {
#: Every preference MeshTerm has, in page order. Adding one here gives it a row on the
#: Preferences page, a key in the YAML file, a ``preferences get``/``set`` CLI face, and a
#: Preferences page, a key in the TOML file, a ``preferences get``/``set`` CLI face, and a
#: default — nothing else has to follow. A default that a module already states as its
#: code-level behaviour is named, never re-typed: one source, so changing it cannot leave
#: the constant and the registry disagreeing about what MeshTerm does.
@@ -500,15 +508,15 @@ def parse_value(spec: PrefSpec, raw: Any) -> Any:
if raw in choices and not isinstance(raw, bool):
return raw
if isinstance(raw, bool):
# YAML 1.1 reads a bare ``yes``/``no`` (and ``on``/``off``) as a *boolean*, so a
# hand-edited file hands us ``True`` where the choice is spelled "yes". We quote
# ours on the way out, but someone typing the obvious thing should still be
# understood: map the boolean back to whichever spelling this spec offers.
# A hand edit that answers a yes/no choice with a TOML boolean
# (``full_width = true``) hands us ``True`` where the choice is spelled "yes".
# We quote ours on the way out, but someone typing the obvious thing should
# still be understood: map the boolean back to whichever spelling this offers.
for choice in choices:
if str(choice).lower() in (_TRUE if raw else _FALSE):
return choice
# Text arriving from the CLI or a hand-edited file: match a choice by its own
# spelling, so `preferences set watch_silence_hours 6` and a YAML `6` land alike.
# spelling, so `preferences set watch_silence_hours 6` and a TOML `6` land alike.
for choice in choices:
if text.lower() == str(choice).lower():
return choice
@@ -564,6 +572,9 @@ def range_hint(spec: PrefSpec) -> str:
# --- the store ----------------------------------------------------------------
#: The file's name inside the config directory — one spelling for every place that opens it.
PREFERENCES_FILENAME = "preferences.toml"
#: The file's opening comment. It says the one thing a reader hand-editing the file needs
#: to know — that absence means "use the default", so deleting a line is how a preference
#: is undone — and points at the two neighbouring kinds of setting so nobody looks for a
@@ -576,11 +587,36 @@ _HEADER = """\
# Preferences page) hands the value back to the code. `meshterm preferences show` prints
# every preference, what it is set to, and what it defaults to.
#
# One `key = value` per line: text in quotes ("DEBUG"), numbers and true/false bare.
#
# Device profiles, the database location, and the rest of the machine setup stay in
# config.toml; the radio's own settings live on the radio, under Device config.
"""
def _salvage(text: str) -> dict[str, Any]:
"""Read a file TOML refused as a document, one ``key = value`` line at a time.
MeshTerm writes the file flat — no tables, one entry to a line — so a line is a whole
entry and can be judged on its own. A line TOML accepts keeps its typed value. One it
refuses keeps its right-hand side as text, which is exactly what :func:`parse_value`
takes from the command line, so the likeliest hand edit of all — a word left unquoted,
``log_level = DEBUG`` — is still understood. Whatever the spec then refuses is dropped
by :meth:`Preferences.update`, the same as any other bad value.
"""
data: dict[str, Any] = {}
for line in text.splitlines():
entry = line.strip()
if not entry or entry.startswith(("#", "[")) or "=" not in entry:
continue
try:
data.update(tomllib.loads(entry))
except tomllib.TOMLDecodeError:
key, _, value = entry.partition("=")
data[key.strip()] = value.split("#", 1)[0].strip()
return data
class Preferences:
"""The effective preferences: the built-in defaults, with the file's overrides on top.
@@ -610,21 +646,27 @@ class Preferences:
@classmethod
def load(cls, path: Path) -> Preferences:
"""Read ``path``, returning all-defaults for a missing, empty, or corrupt file.
"""Read ``path``, returning all-defaults for a missing, empty, or unreadable file.
TOML refuses a whole document over one bad line, and a hand edit should cost the
line it is on, not the file: a document TOML refuses is read again a line at a
time (:func:`_salvage`), keeping every entry that still makes sense.
Args:
path: The YAML file to read.
path: The TOML file to read.
Returns:
The loaded preferences, bound to ``path`` for a later :meth:`save`.
"""
import yaml
try:
data = yaml.safe_load(path.read_text(encoding="utf-8"))
except (OSError, ValueError, yaml.YAMLError):
text = path.read_text(encoding="utf-8")
except (OSError, ValueError):
return cls(path)
return cls(path, data if isinstance(data, Mapping) else None)
try:
data: dict[str, Any] = tomllib.loads(text)
except tomllib.TOMLDecodeError:
data = _salvage(text)
return cls(path, data)
@property
def path(self) -> Path | None:
@@ -712,14 +754,14 @@ class Preferences:
self._values.clear()
return count
def as_yaml(self) -> str:
def as_toml(self) -> str:
"""Render the current overrides as the file's text: header, then grouped entries.
Each group holding an override gets its own comment heading, and each entry its
help line and its default above it, so the file reads the way the page does
rather than as a bare map someone has to look up elsewhere.
"""
import yaml
import tomli_w
lines = [_HEADER]
for group, specs in by_group():
@@ -728,12 +770,7 @@ class Preferences:
continue
lines.append(f"# --- {group} ---")
for spec in present:
entry = yaml.safe_dump(
{spec.key: self._values[spec.key]},
default_flow_style=False,
sort_keys=False,
allow_unicode=True,
).rstrip("\n")
entry = tomli_w.dumps({spec.key: self._values[spec.key]}).rstrip("\n")
lines.append(f"# {spec.help}")
lines.append(f"# default: {format_value(spec, spec.default)}")
lines.append(entry)
@@ -751,7 +788,7 @@ class Preferences:
"""
if self._path is None:
raise RuntimeError("these preferences have no file to save to")
write_atomically(self._path, self.as_yaml())
write_atomically(self._path, self.as_toml())
#: The set installed for this process. Starts as a defaults-only, file-less instance so
+1 -1
View File
@@ -61,7 +61,7 @@ def level_from_name(name: str, *, fallback: int = logging.WARNING) -> int:
Args:
name: A level name, in any case.
fallback: Used when the name is unrecognised — a hand-edited ``preferences.yaml``
fallback: Used when the name is unrecognised — a hand-edited ``preferences.toml``
with a typo in it should lose some log detail, not stop the app from starting.
Returns:
+1 -1
View File
@@ -38,7 +38,7 @@ if TYPE_CHECKING: # pragma: no cover - typing only
@register
class PreferencesTool(Tool):
"""View and change MeshTerm's own preferences, saved to ``preferences.yaml``."""
"""View and change MeshTerm's own preferences, saved to ``preferences.toml``."""
name = "preferences"
title = "Preferences"
+2 -2
View File
@@ -6,7 +6,7 @@ built out of the same parts on purpose — one grouped, lane-aligned list; a row
is staged; the shared discard confirm on the way out. Two editors that stage values should
not be two different screens to learn, so the only things that differ here are what is
being edited (:mod:`meshterm.core.preferences`, not the radio) and where Apply writes
(``preferences.yaml``, not the companion).
(``preferences.toml``, not the companion).
Its rows scroll sideways, which the device editor's do not: a preference's explanation is
the widest thing on its row and the only part that runs past the edge, so ←→ slide the
@@ -159,7 +159,7 @@ def _page_groups() -> list[tuple[str, list[PrefSpec]]]:
A preference gated to another flavour (the PicoCalc's console font, on a desktop) is a
row whose question this machine cannot answer, so it is not drawn. Its value is still
in the registry and still round-trips through the file, which is what keeps a
``preferences.yaml`` written on the handheld from being quietly emptied by a desktop.
``preferences.toml`` written on the handheld from being quietly emptied by a desktop.
"""
return by_group(get_platform().name)
+1 -2
View File
@@ -44,10 +44,9 @@ dependencies = [
"rich>=13.7", # modern console rendering (progress, tables, panels)
"markdown-it-py>=3.0", # CommonMark parser behind the written About pages
"prompt_toolkit>=3.0", # full-screen interactive TUI (terminal, input, resize)
"PyYAML>=6.0", # the preferences file (meshterm.core.preferences)
"segno>=1.6", # pure-Python QR codes (channel share links)
"tomli>=2.0; python_version < '3.11'", # TOML config reader on 3.10
"tomli-w>=1.0", # TOML writer for device-config backups
"tomli-w>=1.0", # TOML writer: preferences and device-config backups
]
[project.optional-dependencies]
+1 -1
View File
@@ -102,7 +102,7 @@ def test_a_level_name_becomes_a_level(tmp_path: Path) -> None:
def test_a_nonsense_level_still_starts_the_app() -> None:
"""A typo in a hand-edited preferences file loses log detail, not the app.
Someone editing YAML by hand and writing ``WARN`` should get a slightly quieter log,
Someone editing the preferences file by hand and writing ``WARN`` should get a slightly quieter log,
not a program that refuses to launch.
"""
assert level_from_name("WARN") == logging.WARNING
+38 -25
View File
@@ -1,4 +1,4 @@
"""Tests for MeshTerm's own preferences: the registry, the YAML file, and the page.
"""Tests for MeshTerm's own preferences: the registry, the TOML file, and the page.
Three layers, in that order — what a preference *is* (spec, default, validation), where it
is kept (the file, and its tolerance for a hand edit gone wrong), and how it is changed
@@ -137,15 +137,15 @@ def test_only_a_disagreement_with_the_default_is_recorded() -> None:
def test_the_file_round_trips_and_holds_only_the_overrides(tmp_path: Path) -> None:
"""What is saved is what was changed; everything else comes back from the code."""
path = tmp_path / "preferences.yaml"
path = tmp_path / "preferences.toml"
prefs = Preferences(path)
prefs.set("trace_cooldown_s", 2.5)
prefs.set("fast_render", False)
prefs.save()
text = path.read_text(encoding="utf-8")
assert "trace_cooldown_s: 2.5" in text
assert "fast_render: false" in text
assert "trace_cooldown_s = 2.5" in text
assert "fast_render = false" in text
assert "history_days" not in text # untouched, so not written
reloaded = Preferences.load(path)
@@ -156,9 +156,9 @@ def test_the_file_round_trips_and_holds_only_the_overrides(tmp_path: Path) -> No
def test_the_file_reads_the_way_the_page_does(tmp_path: Path) -> None:
"""Grouped under comment headings, each entry above its help and its default."""
prefs = Preferences(tmp_path / "preferences.yaml")
prefs = Preferences(tmp_path / "preferences.toml")
prefs.set("history_days", 30)
text = prefs.as_yaml()
text = prefs.as_toml()
assert "# --- History ---" in text
assert "# Older ones are deleted; 0 keeps everything" in text
assert "# default: 365 days" in text
@@ -168,27 +168,27 @@ def test_the_file_reads_the_way_the_page_does(tmp_path: Path) -> None:
def test_an_untouched_file_says_so(tmp_path: Path) -> None:
"""Saving with nothing overridden writes a file that explains its own emptiness."""
prefs = Preferences(tmp_path / "preferences.yaml")
prefs = Preferences(tmp_path / "preferences.toml")
prefs.save()
assert "every preference is at its default" in (tmp_path / "preferences.yaml").read_text(
assert "every preference is at its default" in (tmp_path / "preferences.toml").read_text(
encoding="utf-8"
)
def test_a_yaml_boolean_still_reaches_a_yes_no_choice(tmp_path: Path) -> None:
"""YAML reads a bare ``yes`` as ``True``; the obvious hand edit is understood anyway."""
path = tmp_path / "preferences.yaml"
path.write_text("full_width: yes\n", encoding="utf-8")
def test_a_yes_no_choice_is_understood_however_it_is_typed(tmp_path: Path) -> None:
"""A bare ``yes`` is not TOML and ``false`` is the wrong type; the edit is understood."""
path = tmp_path / "preferences.toml"
path.write_text("full_width = yes\n", encoding="utf-8")
assert Preferences.load(path).full_width == "yes"
path.write_text("full_width: no\n", encoding="utf-8")
path.write_text("full_width = false\n", encoding="utf-8")
assert Preferences.load(path).full_width == "no"
# And what we write ourselves is quoted, so it round-trips as the string it is.
prefs = Preferences(path)
prefs.set("full_width", "yes")
prefs.save()
assert "full_width: 'yes'" in path.read_text(encoding="utf-8")
assert 'full_width = "yes"' in path.read_text(encoding="utf-8")
assert Preferences.load(path).full_width == "yes"
@@ -197,30 +197,43 @@ def test_a_yaml_boolean_still_reaches_a_yes_no_choice(tmp_path: Path) -> None:
[
"",
"not a mapping at all",
"history_days: [1, 2, 3]\n", # a container where a scalar belongs
"no_such_preference: 3\n", # a key the registry never had
"history_days: yesterday\n", # right key, unparseable value
"{{{ not yaml", # not even a document
"history_days = [1, 2, 3]\n", # a container where a scalar belongs
"no_such_preference = 3\n", # a key the registry never had
"history_days = yesterday\n", # right key, unparseable value
"{{{ not toml", # not even a document
],
)
def test_a_broken_file_costs_the_line_not_the_session(tmp_path: Path, text: str) -> None:
"""A hand edit gone wrong falls back to defaults instead of refusing to start."""
path = tmp_path / "preferences.yaml"
path = tmp_path / "preferences.toml"
path.write_text(text, encoding="utf-8")
assert Preferences.load(path).history_days == 365
def test_a_good_line_survives_a_bad_one(tmp_path: Path) -> None:
"""One unusable entry is dropped; the rest of the file still applies."""
path = tmp_path / "preferences.yaml"
path.write_text("history_days: soon\ntrace_cooldown_s: 3.0\n", encoding="utf-8")
path = tmp_path / "preferences.toml"
path.write_text("history_days = soon\ntrace_cooldown_s = 3.0\n", encoding="utf-8")
prefs = Preferences.load(path)
assert prefs.history_days == 365 and prefs.trace_cooldown_s == 3.0
def test_a_word_left_unquoted_is_read_as_the_text_it_is(tmp_path: Path) -> None:
"""The likeliest hand edit of all costs nothing; a truly broken line costs only itself."""
path = tmp_path / "preferences.toml"
path.write_text(
'log_level = DEBUG # louder\ntrace_cooldown_s = "3.0\nfast_render = false\n',
encoding="utf-8",
)
prefs = Preferences.load(path)
assert prefs.log_level == "DEBUG"
assert prefs.trace_cooldown_s == get_spec("trace_cooldown_s").default # unclosed quote
assert prefs.fast_render is False # TOML-valid, so it keeps its type
def test_a_missing_file_is_simply_the_defaults(tmp_path: Path) -> None:
"""Nothing has to exist for the app to run: absence *is* the default state."""
prefs = Preferences.load(tmp_path / "never-written.yaml")
prefs = Preferences.load(tmp_path / "never-written.toml")
assert prefs.overrides() == {} and prefs.fast_render is True
@@ -458,7 +471,7 @@ async def test_the_page_stages_a_typed_value_and_apply_returns_it(ctx: AppContex
)
assert await edit_preferences(ctx) == {"history_days": 30}
# Nothing reached disk: the page stages, the tool saves.
assert not (ctx.settings.config_dir / "preferences.yaml").exists()
assert not (ctx.settings.config_dir / "preferences.toml").exists()
async def test_the_page_unstages_a_value_set_back_to_where_it_started(ctx: AppContext) -> None:
@@ -630,7 +643,7 @@ async def test_the_tool_writes_the_staged_values_once(ctx: AppContext) -> None:
result = await tool.run(ctx, {"ops": ops})
assert result.summary == {"changes": 2}
path = ctx.settings.config_dir / "preferences.yaml"
path = ctx.settings.config_dir / "preferences.toml"
assert path.exists()
assert Preferences.load(path).history_days == 30
@@ -642,7 +655,7 @@ async def test_the_tool_reports_a_bad_value_rather_than_writing_it(ctx: AppConte
with pytest.raises(PreferenceError):
await get_tool("preferences").run(ctx, {"ops": [("set", "history_days", "soon")]})
assert not (ctx.settings.config_dir / "preferences.yaml").exists()
assert not (ctx.settings.config_dir / "preferences.toml").exists()
def test_the_context_installs_its_preferences_process_wide(ctx: AppContext) -> None:
+1 -1
View File
@@ -94,7 +94,7 @@ def test_the_preference_is_consulted_below_the_env_override(monkeypatch) -> None
def test_an_unrecognised_preference_value_changes_nothing(monkeypatch) -> None:
"""A hand-edited YAML value we cannot read is not grounds for guessing."""
"""A hand-edited preference value we cannot read is not grounds for guessing."""
from types import SimpleNamespace
_auto(monkeypatch)
+1 -1
View File
@@ -214,7 +214,7 @@ def test_the_preference_is_offered_on_the_handheld_only() -> None:
def test_the_preference_round_trips_on_every_platform(tmp_path: Path, platform: Any) -> None:
"""A file written on the handheld loads, keeps its value, and saves back on a desktop."""
set_platform(platform)
path = tmp_path / "preferences.yaml"
path = tmp_path / "preferences.toml"
written = Preferences(path)
written.set("console_font", "6x8")
written.save()