cfgcommander 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,19 @@
1
+ """cfgcommander: a Norton Commander style TUI generated from a config file."""
2
+
3
+ from .fields import Field, Kind, ValidationError
4
+ from .formats import FormatError, detect, get_backend
5
+ from .model import ConfigModel
6
+ from .schema import Schema
7
+
8
+ __version__ = "0.1.0"
9
+
10
+ __all__ = [
11
+ "ConfigModel",
12
+ "Field",
13
+ "FormatError",
14
+ "Kind",
15
+ "Schema",
16
+ "ValidationError",
17
+ "detect",
18
+ "get_backend",
19
+ ]
@@ -0,0 +1,5 @@
1
+ import sys
2
+
3
+ from .cli import main
4
+
5
+ sys.exit(main())
cfgcommander/cli.py ADDED
@@ -0,0 +1,55 @@
1
+ """Command line entry point."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import os
7
+ import sys
8
+
9
+ from . import __version__
10
+ from .formats import BACKENDS, FormatError
11
+ from .model import ConfigModel
12
+
13
+
14
+ def build_parser() -> argparse.ArgumentParser:
15
+ parser = argparse.ArgumentParser(
16
+ prog="cfgcommander",
17
+ description="Edit a TOML, JSON, YAML or INI config file in a retro DOS commander style TUI.",
18
+ )
19
+ parser.add_argument("file", help="config file to edit")
20
+ parser.add_argument(
21
+ "--schema",
22
+ metavar="FILE",
23
+ help="JSON Schema used for enums (drop-downs / radio buttons) and numeric ranges",
24
+ )
25
+ parser.add_argument(
26
+ "--format",
27
+ choices=sorted(BACKENDS),
28
+ help="force the file format instead of detecting it",
29
+ )
30
+ parser.add_argument("--version", action="version", version=f"%(prog)s {__version__}")
31
+ return parser
32
+
33
+
34
+ def main(argv: list[str] | None = None) -> int:
35
+ args = build_parser().parse_args(argv)
36
+ try:
37
+ model = ConfigModel.load(args.file, schema=args.schema, fmt=args.format)
38
+ except (OSError, ValueError) as exc: # FormatError and bad schema JSON are ValueErrors
39
+ print(f"cfgcommander: {exc}", file=sys.stderr)
40
+ return 2
41
+
42
+ # With the kitty keyboard protocol some terminals stop composing Option/AltGr
43
+ # characters ([ ] { } | @ # on non-US layouts), so they never reach the inputs.
44
+ # The classic encoding carries everything this UI binds. Must be set before
45
+ # Textual is imported; TEXTUAL_DISABLE_KITTY_KEY=0 turns the protocol back on.
46
+ os.environ.setdefault("TEXTUAL_DISABLE_KITTY_KEY", "1")
47
+
48
+ from .ui.app import CommanderApp # imported late so the model works without a terminal
49
+
50
+ CommanderApp(model).run()
51
+ return 0
52
+
53
+
54
+ if __name__ == "__main__":
55
+ sys.exit(main())
cfgcommander/fields.py ADDED
@@ -0,0 +1,215 @@
1
+ """Value kinds and per-field parsing/validation. No UI and no file format code here."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import datetime as _dt
6
+ import math
7
+ from collections.abc import Mapping, Sequence
8
+ from dataclasses import dataclass
9
+ from enum import Enum
10
+ from typing import Any
11
+
12
+
13
+ class ValidationError(ValueError):
14
+ """A value does not fit its field (wrong type, out of range, not in the enum)."""
15
+
16
+
17
+ class Kind(str, Enum):
18
+ TABLE = "table"
19
+ TABLE_ARRAY = "table_array" # array whose items are all tables ([[x]] in TOML)
20
+ ARRAY = "array"
21
+ BOOL = "bool"
22
+ INT = "int"
23
+ FLOAT = "float"
24
+ STRING = "string"
25
+ NULL = "null"
26
+
27
+ @property
28
+ def is_container(self) -> bool:
29
+ return self in (Kind.TABLE, Kind.TABLE_ARRAY, Kind.ARRAY)
30
+
31
+
32
+ _TRUE = {"true", "yes", "on", "1"}
33
+ _FALSE = {"false", "no", "off", "0"}
34
+
35
+
36
+ def unwrap_scalar(value: Any) -> Any:
37
+ """Strip format-library wrappers (e.g. tomlkit's Bool item) from a scalar."""
38
+ if isinstance(value, (Mapping, list, tuple)):
39
+ return value
40
+ unwrap = getattr(value, "unwrap", None)
41
+ return unwrap() if callable(unwrap) else value
42
+
43
+
44
+ def is_bool(value: Any) -> bool:
45
+ return isinstance(value, bool) or type(value).__name__ == "ScalarBoolean"
46
+
47
+
48
+ def is_sequence(value: Any) -> bool:
49
+ return isinstance(value, Sequence) and not isinstance(value, (str, bytes, bytearray))
50
+
51
+
52
+ def temporal_type(value: Any) -> type | None:
53
+ """The stdlib date/time base class of a value, if it is one."""
54
+ for cls in (_dt.datetime, _dt.date, _dt.time): # datetime first: it subclasses date
55
+ if isinstance(value, cls):
56
+ return cls
57
+ return None
58
+
59
+
60
+ def kind_of(value: Any) -> Kind:
61
+ if isinstance(value, Mapping):
62
+ return Kind.TABLE
63
+ if is_sequence(value):
64
+ items = [value[i] for i in range(len(value))]
65
+ if items and all(isinstance(item, Mapping) for item in items):
66
+ return Kind.TABLE_ARRAY
67
+ return Kind.ARRAY
68
+ value = unwrap_scalar(value)
69
+ if value is None:
70
+ return Kind.NULL
71
+ if is_bool(value):
72
+ return Kind.BOOL
73
+ if isinstance(value, int):
74
+ return Kind.INT
75
+ if isinstance(value, float):
76
+ return Kind.FLOAT
77
+ return Kind.STRING
78
+
79
+
80
+ def plain(value: Any) -> Any:
81
+ """Convert a native scalar into a plain Python value the UI can show."""
82
+ value = unwrap_scalar(value)
83
+ if value is None:
84
+ return None
85
+ if is_bool(value):
86
+ return bool(value)
87
+ if isinstance(value, int):
88
+ return int(value)
89
+ if isinstance(value, float):
90
+ return float(value)
91
+ if temporal_type(value) is not None:
92
+ return value.isoformat()
93
+ return str(value)
94
+
95
+
96
+ def same_value(a: Any, b: Any) -> bool:
97
+ """Equality that does not confuse 1, 1.0 and True."""
98
+ a, b = unwrap_scalar(a), unwrap_scalar(b)
99
+ if is_bool(a) != is_bool(b):
100
+ return False
101
+ if isinstance(a, float) != isinstance(b, float):
102
+ return False
103
+ if isinstance(a, float) and math.isnan(a) and math.isnan(b):
104
+ return True
105
+ return bool(a == b)
106
+
107
+
108
+ @dataclass(frozen=True)
109
+ class Field:
110
+ """Everything the UI needs to edit one scalar: its kind plus schema constraints."""
111
+
112
+ kind: Kind
113
+ nullable: bool = False
114
+ allow_float: bool = False # INT field whose schema says "number"
115
+ enum: tuple | None = None
116
+ minimum: float | None = None
117
+ maximum: float | None = None
118
+ exclusive_minimum: float | None = None
119
+ exclusive_maximum: float | None = None
120
+ title: str | None = None
121
+ description: str | None = None
122
+ default: Any = None
123
+ temporal: type | None = None
124
+
125
+ @property
126
+ def is_number(self) -> bool:
127
+ return self.kind in (Kind.INT, Kind.FLOAT)
128
+
129
+ def parse(self, raw: Any) -> Any:
130
+ """Turn UI input (usually text) into a typed, validated Python value."""
131
+ value = self._convert(raw)
132
+ self.validate(value)
133
+ return value
134
+
135
+ def _convert(self, raw: Any) -> Any:
136
+ if raw is None or (self.nullable and isinstance(raw, str) and raw.strip() == ""):
137
+ if not self.nullable:
138
+ raise ValidationError("a value is required")
139
+ return None
140
+ if self.kind is Kind.BOOL:
141
+ if is_bool(raw):
142
+ return bool(raw)
143
+ text = str(raw).strip().lower()
144
+ if text in _TRUE:
145
+ return True
146
+ if text in _FALSE:
147
+ return False
148
+ raise ValidationError("expected true or false")
149
+ if self.kind is Kind.INT:
150
+ if is_bool(raw):
151
+ raise ValidationError("expected an integer")
152
+ if isinstance(raw, int):
153
+ return int(raw)
154
+ if isinstance(raw, float):
155
+ if raw.is_integer():
156
+ return int(raw)
157
+ if self.allow_float:
158
+ return raw
159
+ raise ValidationError("expected an integer")
160
+ text = str(raw).strip()
161
+ try:
162
+ return int(text)
163
+ except ValueError:
164
+ pass
165
+ if self.allow_float:
166
+ try:
167
+ return float(text)
168
+ except ValueError:
169
+ pass
170
+ raise ValidationError("expected an integer" if not self.allow_float else "expected a number")
171
+ if self.kind is Kind.FLOAT:
172
+ if is_bool(raw):
173
+ raise ValidationError("expected a number")
174
+ try:
175
+ return float(raw.strip() if isinstance(raw, str) else raw)
176
+ except (TypeError, ValueError):
177
+ raise ValidationError("expected a number") from None
178
+ if self.temporal is not None:
179
+ if isinstance(raw, self.temporal):
180
+ return raw
181
+ try:
182
+ return self.temporal.fromisoformat(str(raw).strip())
183
+ except ValueError:
184
+ raise ValidationError(f"expected an ISO {self.temporal.__name__}") from None
185
+ return str(raw)
186
+
187
+ def validate(self, value: Any) -> None:
188
+ if value is None:
189
+ return
190
+ if self.enum is not None and not any(same_value(value, option) for option in self.enum):
191
+ raise ValidationError("must be one of: " + ", ".join(map(str, self.enum)))
192
+ if isinstance(value, (int, float)) and not is_bool(value):
193
+ if self.minimum is not None and value < self.minimum:
194
+ raise ValidationError(f"must be >= {self.minimum:g}")
195
+ if self.maximum is not None and value > self.maximum:
196
+ raise ValidationError(f"must be <= {self.maximum:g}")
197
+ if self.exclusive_minimum is not None and value <= self.exclusive_minimum:
198
+ raise ValidationError(f"must be > {self.exclusive_minimum:g}")
199
+ if self.exclusive_maximum is not None and value >= self.exclusive_maximum:
200
+ raise ValidationError(f"must be < {self.exclusive_maximum:g}")
201
+
202
+ def zero(self) -> Any:
203
+ """A sensible initial value for a brand new item of this field."""
204
+ if self.default is not None:
205
+ return self.default
206
+ if self.enum:
207
+ return self.enum[0]
208
+ low = self.minimum if self.minimum is not None else self.exclusive_minimum
209
+ if self.kind is Kind.BOOL:
210
+ return False
211
+ if self.kind is Kind.INT:
212
+ return int(low) if low is not None and low > 0 else 0
213
+ if self.kind is Kind.FLOAT:
214
+ return float(low) if low is not None and low > 0 else 0.0
215
+ return ""
@@ -0,0 +1,61 @@
1
+ """Format registry and detection (by extension first, then by content)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from pathlib import Path
6
+ from typing import Any
7
+
8
+ from .base import Backend, FormatError
9
+ from .inifmt import IniBackend
10
+ from .jsonfmt import JsonBackend
11
+ from .tomlfmt import TomlBackend
12
+ from .yamlfmt import YamlBackend
13
+
14
+ # Sniffing order matters: strictest grammar first, YAML (which accepts almost
15
+ # anything, including JSON) last.
16
+ BACKENDS: dict[str, Backend] = {
17
+ backend.name: backend
18
+ for backend in (JsonBackend(), TomlBackend(), IniBackend(), YamlBackend())
19
+ }
20
+
21
+ _EXTENSIONS = {ext: backend for backend in BACKENDS.values() for ext in backend.extensions}
22
+
23
+
24
+ def get_backend(name: str) -> Backend:
25
+ try:
26
+ return BACKENDS[name.lower()]
27
+ except KeyError:
28
+ raise FormatError(f"unknown format {name!r} (choose from {', '.join(BACKENDS)})") from None
29
+
30
+
31
+ def backend_for_extension(path: str | Path) -> Backend | None:
32
+ return _EXTENSIONS.get(Path(path).suffix.lower())
33
+
34
+
35
+ def detect(path: str | Path | None, text: str) -> tuple[Backend, Any]:
36
+ """Pick a backend and parse ``text`` with it.
37
+
38
+ The file extension is tried first. If it is unknown, or the content does not
39
+ parse as that format, every format is tried against the content.
40
+ """
41
+ errors: list[str] = []
42
+ preferred = backend_for_extension(path) if path is not None else None
43
+ if preferred is not None:
44
+ try:
45
+ return preferred, preferred.loads(text)
46
+ except FormatError as exc:
47
+ errors.append(str(exc))
48
+ for backend in BACKENDS.values():
49
+ if backend is preferred:
50
+ continue
51
+ try:
52
+ root = backend.loads(text)
53
+ except FormatError as exc:
54
+ errors.append(str(exc))
55
+ continue
56
+ if backend.sniffable(root):
57
+ return backend, root
58
+ raise FormatError("could not parse the file as TOML, JSON, YAML or INI:\n " + "\n ".join(errors))
59
+
60
+
61
+ __all__ = ["BACKENDS", "Backend", "FormatError", "backend_for_extension", "detect", "get_backend"]
@@ -0,0 +1,45 @@
1
+ """Backend interface: each file format parses into a mutable tree and writes it back."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from abc import ABC, abstractmethod
6
+ from typing import Any
7
+
8
+
9
+ class FormatError(ValueError):
10
+ """The text could not be parsed (or written) in a given format."""
11
+
12
+
13
+ class Backend(ABC):
14
+ name: str = ""
15
+ extensions: tuple[str, ...] = ()
16
+
17
+ @abstractmethod
18
+ def loads(self, text: str) -> Any:
19
+ """Parse text into a tree of mutable mappings/sequences. Raises FormatError."""
20
+
21
+ @abstractmethod
22
+ def dumps(self, root: Any) -> str:
23
+ """Serialise the tree, keeping comments and key order where the format has them."""
24
+
25
+ def sniffable(self, root: Any) -> bool:
26
+ """Whether a successful parse is convincing enough when guessing by content."""
27
+ return True
28
+
29
+ def coerce(self, old: Any, new: Any) -> Any:
30
+ """Give a new scalar the presentation style of the one it replaces."""
31
+ return new
32
+
33
+ def wrap(self, value: Any) -> Any:
34
+ """Convert a plain Python value into something insertable into the tree."""
35
+ return value
36
+
37
+ def append(self, seq: Any, value: Any) -> None:
38
+ seq.append(self.wrap(value))
39
+
40
+ def delete(self, seq: Any, index: int) -> None:
41
+ del seq[index]
42
+
43
+ def swap(self, seq: Any, i: int, j: int) -> None:
44
+ """Exchange two items of a sequence."""
45
+ seq[i], seq[j] = seq[j], seq[i]
@@ -0,0 +1,190 @@
1
+ """INI via configparser.
2
+
3
+ configparser throws comments and blank lines away when it writes, so it is used
4
+ for what it is good at (parsing, and defining what a valid file means) while saving
5
+ patches only the changed ``key = value`` lines of the original text. The patched
6
+ text is re-parsed with configparser to prove it says what the model says; if that
7
+ ever fails, the file is rewritten with ``ConfigParser.write`` (correct, but plain).
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import configparser
13
+ import copy
14
+ import io
15
+ import re
16
+ from typing import Any
17
+
18
+ from .base import Backend, FormatError
19
+
20
+ _NO_DEFAULT = "\x00cfgcommander-no-default\x00" # so [DEFAULT] behaves like any section
21
+ _BOOL_WORDS = {"true": "false", "yes": "no", "on": "off"}
22
+ _BOOL_FALSE = {v: k for k, v in _BOOL_WORDS.items()}
23
+ _INT_RE = re.compile(r"[+-]?(0|[1-9]\d*)\Z")
24
+ _FLOAT_RE = re.compile(r"[+-]?\d+\.\d+([eE][+-]?\d+)?\Z")
25
+ _SECTION_RE = re.compile(r"\[(?P<header>.+)\]")
26
+ _OPTION_RE = re.compile(r"(?P<indent>\s*)(?P<key>.*?)(?P<delim>\s*[=:]\s*)(?P<value>.*)\Z", re.S)
27
+
28
+
29
+ def _parser() -> configparser.ConfigParser:
30
+ parser = configparser.ConfigParser(
31
+ interpolation=None,
32
+ allow_no_value=True,
33
+ default_section=_NO_DEFAULT,
34
+ )
35
+ parser.optionxform = str # keep the case of keys
36
+ return parser
37
+
38
+
39
+ def _typed(raw: str | None) -> Any:
40
+ if raw is None:
41
+ return None
42
+ lowered = raw.lower()
43
+ if lowered in _BOOL_WORDS:
44
+ return True
45
+ if lowered in _BOOL_FALSE:
46
+ return False
47
+ if _INT_RE.match(raw):
48
+ return int(raw)
49
+ if _FLOAT_RE.match(raw):
50
+ return float(raw)
51
+ return raw
52
+
53
+
54
+ def _match_case(word: str, like: str) -> str:
55
+ if like.isupper():
56
+ return word.upper()
57
+ if like[:1].isupper():
58
+ return word.capitalize()
59
+ return word
60
+
61
+
62
+ def _raw(value: Any, original_raw: str | None) -> str | None:
63
+ """Format a typed value as INI text, imitating how the original was written."""
64
+ if value is None:
65
+ return None
66
+ if isinstance(value, bool):
67
+ like = (original_raw or "true").lower()
68
+ if like in _BOOL_WORDS:
69
+ true_word, false_word = like, _BOOL_WORDS[like]
70
+ elif like in _BOOL_FALSE:
71
+ true_word, false_word = _BOOL_FALSE[like], like
72
+ else:
73
+ true_word, false_word = "true", "false"
74
+ return _match_case(true_word if value else false_word, original_raw or "true")
75
+ if isinstance(value, float):
76
+ return repr(value)
77
+ return str(value)
78
+
79
+
80
+ class IniDocument(dict):
81
+ """section -> {key -> typed value}, plus the source text for comment-safe saving."""
82
+
83
+ def __init__(self, text: str, parser: configparser.ConfigParser):
84
+ super().__init__()
85
+ self.text = text
86
+ self.raw: dict[str, dict[str, str | None]] = {}
87
+ for section in parser.sections():
88
+ self.raw[section] = dict(parser.items(section, raw=True))
89
+ self[section] = {key: _typed(value) for key, value in self.raw[section].items()}
90
+ self.original = copy.deepcopy(dict(self))
91
+
92
+ def raw_values(self) -> dict[str, dict[str, str | None]]:
93
+ """Current content as the raw strings configparser should read back."""
94
+ result: dict[str, dict[str, str | None]] = {}
95
+ for section, options in self.items():
96
+ result[section] = {}
97
+ for key, value in options.items():
98
+ original_raw = self.raw.get(section, {}).get(key)
99
+ unchanged = (
100
+ section in self.original
101
+ and key in self.original[section]
102
+ and type(self.original[section][key]) is type(value)
103
+ and self.original[section][key] == value
104
+ )
105
+ result[section][key] = original_raw if unchanged else _raw(value, original_raw)
106
+ return result
107
+
108
+
109
+ def _patch(text: str, original: dict, wanted: dict) -> str:
110
+ """Rewrite only the value part of lines whose value changed."""
111
+ lines = text.splitlines(keepends=True)
112
+ output: list[str] = []
113
+ section: str | None = None
114
+ skip_deeper_than: int | None = None # dropping continuation lines of a replaced value
115
+ key_indent: int | None = None # indent of the option we are inside, if any
116
+ for line in lines:
117
+ body = line.rstrip("\r\n")
118
+ ending = line[len(body):]
119
+ stripped = body.strip()
120
+ indent = len(body) - len(body.lstrip())
121
+ if skip_deeper_than is not None:
122
+ if stripped and indent > skip_deeper_than:
123
+ continue
124
+ skip_deeper_than = None
125
+ if not stripped or stripped[0] in "#;":
126
+ output.append(line)
127
+ continue
128
+ if key_indent is not None and indent > key_indent:
129
+ output.append(line) # continuation of an untouched multi-line value
130
+ continue
131
+ header = _SECTION_RE.match(stripped)
132
+ if header:
133
+ section, key_indent = header.group("header"), None
134
+ output.append(line)
135
+ continue
136
+ key_indent = indent
137
+ match = _OPTION_RE.match(body)
138
+ if match:
139
+ key, delim = match.group("key").strip(), match.group("delim")
140
+ else:
141
+ key, delim = stripped, ""
142
+ new = wanted.get(section, {}).get(key, ...) if section is not None else ...
143
+ if new is ... or new == original.get(section, {}).get(key):
144
+ output.append(line)
145
+ continue
146
+ prefix = (match.group("indent") if match else body[:indent]) + key
147
+ if new is None:
148
+ output.append(prefix + ending)
149
+ else:
150
+ continuation = "\n" + " " * (indent + 4)
151
+ output.append(prefix + (delim or " = ") + new.replace("\n", continuation) + ending)
152
+ skip_deeper_than = indent
153
+ return "".join(output)
154
+
155
+
156
+ class IniBackend(Backend):
157
+ name = "ini"
158
+ extensions = (".ini", ".cfg", ".conf")
159
+
160
+ def loads(self, text: str) -> Any:
161
+ parser = _parser()
162
+ try:
163
+ parser.read_string(text)
164
+ except configparser.Error as exc:
165
+ raise FormatError(f"INI: {str(exc).splitlines()[0]}") from exc
166
+ return IniDocument(text, parser)
167
+
168
+ def sniffable(self, root: Any) -> bool:
169
+ return len(root) > 0
170
+
171
+ def dumps(self, root: Any) -> str:
172
+ wanted = root.raw_values()
173
+ patched = _patch(root.text, root.raw, wanted)
174
+ check = _parser()
175
+ try:
176
+ check.read_string(patched)
177
+ reread = {s: dict(check.items(s, raw=True)) for s in check.sections()}
178
+ except configparser.Error:
179
+ reread = None
180
+ if reread == wanted:
181
+ return patched
182
+ # Safety net: never write a file that disagrees with the model.
183
+ plain = _parser()
184
+ for section, options in wanted.items():
185
+ plain.add_section(section)
186
+ for key, value in options.items():
187
+ plain.set(section, key, value)
188
+ buffer = io.StringIO()
189
+ plain.write(buffer)
190
+ return buffer.getvalue()