a_maze_ing / config.py 159 commits
09-06-2026
270 lines 8.0 kB
  1"""Config file parser for a_maze_ing."""
  2
  3import os
  4
  5from dataclasses import dataclass
  6
  7
  8MANDATORY_KEYS = frozenset(
  9    {
 10        "WIDTH",
 11        "HEIGHT",
 12        "ENTRY",
 13        "EXIT",
 14        "OUTPUT_FILE",
 15        "PERFECT",
 16    }
 17)
 18OPTIONAL_KEYS = frozenset(
 19    {
 20        "SEED",
 21        "PURE_ASCII",
 22        "ALGORITHM",
 23        "GLYPH",
 24        "BRAID",
 25        "RANDOMIZE_ENDPOINTS",
 26        "CLAMP_ENDPOINTS",
 27    }
 28)
 29KNOWN_KEYS = MANDATORY_KEYS | OPTIONAL_KEYS
 30
 31
 32class ConfigError(Exception):
 33    """Raised on any config validation failure."""
 34
 35
 36@dataclass(frozen=True)
 37class Config:
 38    """Immutable parsed config.
 39
 40    Attributes:
 41        width: Maze width in cells, >= 2.
 42        height: Maze height in cells, >= 2.
 43        entry: Entry cell (x, y), in bounds.
 44        exit_: Exit cell (x, y), in bounds and != entry.
 45        output_file: Destination path for hex output.
 46        perfect: True for spanning tree; False enables braid pass.
 47        seed: RNG seed, or None for random.
 48        pure_ascii: True to render with plain ASCII and no color; False for
 49            colored truecolor block rendering (background-colored ASCII cells).
 50        algorithm: Carving algorithm, "dfs" or "prim".
 51        glyph: True to embed the '42' pattern (default); False to skip it.
 52        braid: Fraction of dead-ends to remove [0.0, 1.0]; 0.0 = no loops.
 53        randomize_endpoints: True to pick fresh random entry/exit cells on
 54            every regeneration; False (default) keeps the config endpoints.
 55        clamp_endpoints: True to silently substitute out-of-bounds entry
 56            coords with (0, 0) and exit coords with (width-1, height-1)
 57            per axis; False (default) rejects OOB coords with ConfigError.
 58    """
 59
 60    width: int
 61    height: int
 62    entry: tuple[int, int]
 63    exit_: tuple[int, int]
 64    output_file: str
 65    perfect: bool
 66    seed: int | None
 67    pure_ascii: bool
 68    algorithm: str
 69    glyph: bool
 70    braid: float
 71    randomize_endpoints: bool
 72    clamp_endpoints: bool
 73
 74
 75def parse_config(path: str) -> Config:
 76    """Parse and validate a config file.
 77
 78    Args:
 79        path: Filesystem path to the config file.
 80
 81    Returns:
 82        Validated Config.
 83
 84    Raises:
 85        ConfigError: On any read/parse/validation failure.
 86    """
 87    raw = _read_raw(path)
 88    width = _parse_int(raw["WIDTH"], "WIDTH")
 89    height = _parse_int(raw["HEIGHT"], "HEIGHT")
 90    if width < 2 or height < 2:
 91        raise ConfigError("WIDTH and HEIGHT must be >= 2")
 92    if width > 100 or height > 100:
 93        raise ConfigError("WIDTH and HEIGHT must be <= 100")
 94    ts_x, ts_y = os.get_terminal_size()
 95    if ts_x < 2 * width + 1 or ts_x < 106:
 96        raise ConfigError("Terminal width must be big enough")
 97    if ts_y < (2 * height + 1) + 8:
 98        raise ConfigError("Terminal height must be big enough")
 99
100    clamp_endpoints = False
101    if "CLAMP_ENDPOINTS" in raw:
102        clamp_endpoints = _parse_bool(
103            raw["CLAMP_ENDPOINTS"], "CLAMP_ENDPOINTS"
104        )
105
106    if clamp_endpoints:
107        entry = _parse_coord_clamped(
108            raw["ENTRY"], "ENTRY", width, height, 0, 0
109        )
110        exit_ = _parse_coord_clamped(
111            raw["EXIT"], "EXIT", width, height, width - 1, height - 1
112        )
113    else:
114        entry = _parse_coord(raw["ENTRY"], "ENTRY", width, height)
115        exit_ = _parse_coord(raw["EXIT"], "EXIT", width, height)
116    if entry == exit_:
117        raise ConfigError("ENTRY and EXIT must be distinct")
118
119    perfect = _parse_bool(raw["PERFECT"], "PERFECT")
120
121    output_file = raw["OUTPUT_FILE"]
122    if not output_file:
123        raise ConfigError("OUTPUT_FILE must be non-empty")
124
125    seed: int | None = None
126    if "SEED" in raw:
127        seed = _parse_int(raw["SEED"], "SEED")
128
129    pure_ascii = False
130    if "PURE_ASCII" in raw:
131        pure_ascii = _parse_bool(raw["PURE_ASCII"], "PURE_ASCII")
132
133    algorithm = "dfs"
134    if "ALGORITHM" in raw:
135        raw_algo = raw["ALGORITHM"].strip()
136        algorithm = raw_algo.lower()
137        if algorithm not in ("dfs", "prim"):
138            raise ConfigError(
139                f"ALGORITHM must be dfs or prim, got `{raw_algo}`"
140            )
141
142    glyph = True
143    if "GLYPH" in raw:
144        glyph = _parse_bool(raw["GLYPH"], "GLYPH")
145
146    braid = 0.0
147    if "BRAID" in raw:
148        braid = _parse_float(raw["BRAID"], "BRAID")
149        if not 0.0 <= braid <= 1.0:
150            raise ConfigError(
151                f"BRAID must be in [0.0, 1.0], got `{raw['BRAID']}`"
152            )
153
154    randomize_endpoints = False
155    if "RANDOMIZE_ENDPOINTS" in raw:
156        randomize_endpoints = _parse_bool(
157            raw["RANDOMIZE_ENDPOINTS"], "RANDOMIZE_ENDPOINTS"
158        )
159
160    return Config(
161        clamp_endpoints=clamp_endpoints,
162        width=width,
163        height=height,
164        entry=entry,
165        exit_=exit_,
166        output_file=output_file,
167        perfect=perfect,
168        seed=seed,
169        pure_ascii=pure_ascii,
170        algorithm=algorithm,
171        glyph=glyph,
172        braid=braid,
173        randomize_endpoints=randomize_endpoints,
174    )
175
176
177def _read_raw(path: str) -> dict[str, str]:
178    """Read config, return KEY->VALUE map; raise ConfigError on bad input."""
179    try:
180        with open(path) as f:
181            text = f.read()
182    except OSError as e:
183        raise ConfigError(f"cannot read config `{path}`: {e}")
184
185    raw: dict[str, str] = {}
186    for lineno, raw_line in enumerate(text.splitlines(), 1):
187        line = raw_line.split("#", 1)[0].strip()
188        if not line:
189            continue
190        if "=" not in line:
191            raise ConfigError(f"line {lineno}: malformed `{raw_line}`")
192        key, _, val = line.partition("=")
193        key, val = key.strip(), val.strip()
194        if key in raw:
195            raise ConfigError(f"line {lineno}: duplicate key `{key}`")
196        if key not in KNOWN_KEYS:
197            raise ConfigError(f"line {lineno}: unknown key `{key}`")
198        raw[key] = val
199
200    missing = MANDATORY_KEYS - raw.keys()
201    if missing:
202        names = ", ".join(sorted(missing))
203        raise ConfigError(f"missing mandatory keys: {names}")
204    return raw
205
206
207def _parse_int(val: str, name: str) -> int:
208    """Parse `val` as int; raise ConfigError on failure."""
209    try:
210        return int(val)
211    except ValueError:
212        raise ConfigError(f"{name} must be an integer, got `{val}`")
213
214
215def _parse_float(val: str, name: str) -> float:
216    """Parse `val` as float; raise ConfigError on failure."""
217    try:
218        return float(val)
219    except ValueError:
220        raise ConfigError(f"{name} must be a number, got `{val}`")
221
222
223def _parse_coord(
224    val: str,
225    name: str,
226    width: int,
227    height: int,
228) -> tuple[int, int]:
229    """Parse `val` as `x,y` within bounds; raise ConfigError on failure."""
230    parts = val.split(",")
231    if len(parts) != 2:
232        raise ConfigError(f"{name} must be `x,y`, got `{val}`")
233    x = _parse_int(parts[0].strip(), f"{name}.x")
234    y = _parse_int(parts[1].strip(), f"{name}.y")
235    if not (0 <= x < width and 0 <= y < height):
236        raise ConfigError(
237            f"{name} ({x},{y}) out of bounds for {width}x{height}"
238        )
239    return (x, y)
240
241
242def _parse_coord_clamped(
243    val: str,
244    name: str,
245    width: int,
246    height: int,
247    default_x: int,
248    default_y: int,
249) -> tuple[int, int]:
250    """Parse `val` as `x,y`; substitute defaults per axis when OOB."""
251    parts = val.split(",")
252    if len(parts) != 2:
253        raise ConfigError(f"{name} must be `x,y`, got `{val}`")
254    x = _parse_int(parts[0].strip(), f"{name}.x")
255    y = _parse_int(parts[1].strip(), f"{name}.y")
256    if not 0 <= x < width:
257        x = default_x
258    if not 0 <= y < height:
259        y = default_y
260    return (x, y)
261
262
263def _parse_bool(val: str, name: str) -> bool:
264    """Parse `val` as case-insensitive `True`/`False`; else raise."""
265    low = val.lower()
266    if low == "true":
267        return True
268    if low == "false":
269        return False
270    raise ConfigError(f"{name} must be True or False, got `{val}`")