Skip to content

jmcore.config_file

jmcore.config_file

Narrow TOML config access for the shell TUI.

The TUI only needs to read, set, and remove string values in named top-level tables. Keeping that surface here avoids shell parsing and preserves comments and unrelated configuration through TOMLKit.

Classes

ConfigFileError

Bases: Exception

Raised when a config file cannot be safely handled by the TUI.

Source code in jmcore/src/jmcore/config_file.py
23
24
class ConfigFileError(Exception):
    """Raised when a config file cannot be safely handled by the TUI."""

Functions:

get_config_value(path: Path, section: str, key: str) -> str | None

Return a config value as text, or None when the file or key is absent.

Boolean values are rendered as "true" / "false" so shell callers can compare against a stable string.

Source code in jmcore/src/jmcore/config_file.py
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
def get_config_value(path: Path, section: str, key: str) -> str | None:
    """Return a config value as text, or ``None`` when the file or key is absent.

    Boolean values are rendered as ``"true"`` / ``"false"`` so shell callers
    can compare against a stable string.
    """
    _validate_identifier("section", section)
    _validate_identifier("key", key)
    table = _get_table(_read_document(path), section)
    if table is None or key not in table:
        return None

    value = table[key]
    if isinstance(value, bool):
        return "true" if value else "false"
    if not isinstance(value, str):
        raise ConfigFileError("config value is not a string or boolean")
    return value

main(argv: Sequence[str] | None = None) -> int

Run the TUI config helper command.

Source code in jmcore/src/jmcore/config_file.py
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
def main(argv: Sequence[str] | None = None) -> int:
    """Run the TUI config helper command."""
    args = _parse_args(argv)
    try:
        if args.command == "get":
            value = get_config_value(args.config, args.section, args.key)
            if value is not None:
                sys.stdout.write(value)
        elif args.command in {"set", "set-bool"}:
            try:
                value = sys.stdin.buffer.read().decode("utf-8")
            except UnicodeDecodeError as exc:
                raise ConfigFileError("config value must be UTF-8 text") from exc
            set_config_value(
                args.config,
                args.section,
                args.key,
                value,
                as_bool=args.command == "set-bool" or args.bool,
            )
        else:
            remove_config_value(args.config, args.section, args.key)
    except ConfigFileError as exc:
        print(f"config file error: {exc}", file=sys.stderr)
        return 2
    return 0

remove_config_value(path: Path, section: str, key: str) -> None

Remove a scalar config value, doing nothing when the file or key is absent.

Source code in jmcore/src/jmcore/config_file.py
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
def remove_config_value(path: Path, section: str, key: str) -> None:
    """Remove a scalar config value, doing nothing when the file or key is absent."""
    _validate_identifier("section", section)
    _validate_identifier("key", key)
    if not path.exists():
        return

    document = _read_document(path)
    table = _get_table(document, section)
    if table is None or key not in table:
        return

    value = table[key]
    if not isinstance(value, (str, bool)):
        raise ConfigFileError("config value is not a string or boolean")
    del table[key]
    _write_document(path, document)

set_config_value(path: Path, section: str, key: str, value: str, *, as_bool: bool = False) -> None

Set a string (or boolean with as_bool) config value without rewriting the file for a no-op.

New keys are inserted before the next chapter's banner comments so that template-generated files keep every key inside its own chapter. Keys that were previously written after such a banner are moved back on update.

The value type is stable per key: an existing string value can only be updated with a string, an existing boolean only with as_bool. With as_bool the value must be exactly "true" or "false" and is written as a TOML boolean.

Source code in jmcore/src/jmcore/config_file.py
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
def set_config_value(
    path: Path, section: str, key: str, value: str, *, as_bool: bool = False
) -> None:
    """Set a string (or boolean with ``as_bool``) config value without rewriting
    the file for a no-op.

    New keys are inserted before the next chapter's banner comments so that
    template-generated files keep every key inside its own chapter. Keys that
    were previously written after such a banner are moved back on update.

    The value type is stable per key: an existing string value can only be
    updated with a string, an existing boolean only with ``as_bool``. With
    ``as_bool`` the value must be exactly ``"true"`` or ``"false"`` and is
    written as a TOML boolean.
    """
    _validate_identifier("section", section)
    _validate_identifier("key", key)
    typed_value: str | bool = value
    if as_bool:
        # Tolerate a trailing newline so both `printf` and `echo` work as
        # stdin producers.
        stripped = value.strip()
        if stripped not in ("true", "false"):
            raise ConfigFileError("boolean config value must be 'true' or 'false'")
        typed_value = stripped == "true"
    document = _read_document(path)
    next_section = _next_table_section(document, section)
    insertion_value: str | bool | Item = typed_value
    table = _get_table(document, section)
    if table is None:
        table = tomlkit.table()
        document[section] = table
    elif key in table:
        current_value = table[key]
        if isinstance(current_value, bool):
            if not as_bool:
                raise ConfigFileError("config value is a boolean, not a string")
        elif isinstance(current_value, str):
            if as_bool:
                raise ConfigFileError("config value is a string, not a boolean")
        else:
            raise ConfigFileError("config value is not a string or boolean")
        key_index = _table_key_index(table, key)
        cut = _chapter_banner_cut(table, next_section)
        if cut is not None and key_index is not None and key_index > cut:
            # The key sits after the next chapter's banner comments, which
            # makes it look like it belongs to that chapter. Move it back.
            table[key] = typed_value
            insertion_value = table.item(key)
            table.remove(key)
        elif current_value == typed_value:
            return
        else:
            table[key] = typed_value
            _write_document(path, document)
            return

    _insert_table_value(table, key, insertion_value, next_section)
    _write_document(path, document)