sim-cli-core 0.2.4__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.
sim/config.py ADDED
@@ -0,0 +1,380 @@
1
+ """Two-tier config: global ~/.sim/config.toml + project .sim/config.toml.
2
+
3
+ Resolution order for any lookup:
4
+ env var > project .sim/config.toml > global ~/.sim/config.toml > default
5
+
6
+ Usage:
7
+ from sim import config
8
+ port = config.resolve_server_port()
9
+ path = config.resolve_solver_path("fluent")
10
+ history = config.history_path()
11
+
12
+ With no config files present, behavior is identical to pre-#5 (env var
13
+ and auto-detection only). Missing or malformed TOML falls back silently.
14
+
15
+ See docs/architecture/multi-session-and-config.md for the schema rules.
16
+ """
17
+ from __future__ import annotations
18
+
19
+ import os
20
+ import sys
21
+ from pathlib import Path
22
+ from typing import Any # noqa: F401 — used in newer additions below
23
+
24
+ if sys.version_info >= (3, 11):
25
+ import tomllib
26
+ else: # pragma: no cover — exercised only on 3.10
27
+ import tomli as tomllib
28
+
29
+
30
+ DEFAULT_SERVER_PORT = 7600
31
+ DEFAULT_SERVER_HOST = "127.0.0.1"
32
+
33
+
34
+ # ── Paths ────────────────────────────────────────────────────────────────────
35
+
36
+
37
+ def sim_home() -> Path:
38
+ """Global `~/.sim/` dir. Override with SIM_HOME env var (test isolation)."""
39
+ raw = os.environ.get("SIM_HOME")
40
+ if raw:
41
+ return Path(raw)
42
+ return Path.home() / ".sim"
43
+
44
+
45
+ def project_sim_dir() -> Path:
46
+ """Project-level `.sim/` dir. Override with SIM_DIR env var (back-compat)."""
47
+ raw = os.environ.get("SIM_DIR")
48
+ if raw:
49
+ return Path(raw)
50
+ return Path.cwd() / ".sim"
51
+
52
+
53
+ def global_config_path() -> Path:
54
+ return sim_home() / "config.toml"
55
+
56
+
57
+ def project_config_path() -> Path:
58
+ return project_sim_dir() / "config.toml"
59
+
60
+
61
+ def history_path() -> Path:
62
+ return sim_home() / "history.jsonl"
63
+
64
+
65
+ def server_log_path() -> Path:
66
+ """Server log file lives under the project `.sim/` so each project gets its own."""
67
+ return project_sim_dir() / "sim-serve.log"
68
+
69
+
70
+ # ── Loading ──────────────────────────────────────────────────────────────────
71
+
72
+
73
+ def _read_toml(path: Path) -> dict[str, Any]:
74
+ if not path.is_file():
75
+ return {}
76
+ try:
77
+ return tomllib.loads(path.read_text(encoding="utf-8"))
78
+ except (tomllib.TOMLDecodeError, OSError):
79
+ return {}
80
+
81
+
82
+ def _deep_merge(base: dict, overlay: dict) -> dict:
83
+ """Return a new dict: overlay wins on scalar keys, sub-dicts merge recursively."""
84
+ out = dict(base)
85
+ for k, v in overlay.items():
86
+ if isinstance(v, dict) and isinstance(out.get(k), dict):
87
+ out[k] = _deep_merge(out[k], v)
88
+ else:
89
+ out[k] = v
90
+ return out
91
+
92
+
93
+ def load_config() -> dict[str, Any]:
94
+ """Merge global + project configs (project wins). Returns `{}` when both absent."""
95
+ g = _read_toml(global_config_path())
96
+ p = _read_toml(project_config_path())
97
+ return _deep_merge(g, p)
98
+
99
+
100
+ # The merged config is read many times per CLI invocation; cache it for
101
+ # the duration of the process. Tests that mutate config files between
102
+ # calls should invoke `clear_cache()`.
103
+
104
+ _cached: dict[str, Any] | None = None
105
+
106
+
107
+ def _cached_config() -> dict[str, Any]:
108
+ global _cached
109
+ if _cached is None:
110
+ _cached = load_config()
111
+ return _cached
112
+
113
+
114
+ def clear_cache() -> None:
115
+ """Invalidate the cached merged config. Tests only."""
116
+ global _cached
117
+ _cached = None
118
+
119
+
120
+ # ── Resolvers ────────────────────────────────────────────────────────────────
121
+
122
+
123
+ def resolve_server_port() -> int:
124
+ """env SIM_PORT > config [server].port > default 7600."""
125
+ raw = os.environ.get("SIM_PORT")
126
+ if raw:
127
+ try:
128
+ return int(raw)
129
+ except ValueError:
130
+ pass
131
+ cfg = _cached_config()
132
+ port = cfg.get("server", {}).get("port")
133
+ if isinstance(port, int):
134
+ return port
135
+ return DEFAULT_SERVER_PORT
136
+
137
+
138
+ def resolve_server_host() -> str:
139
+ """env SIM_HOST > config [server].host > default 127.0.0.1."""
140
+ raw = os.environ.get("SIM_HOST")
141
+ if raw:
142
+ return raw
143
+ cfg = _cached_config()
144
+ host = cfg.get("server", {}).get("host")
145
+ if isinstance(host, str) and host:
146
+ return host
147
+ return DEFAULT_SERVER_HOST
148
+
149
+
150
+ def resolve_solver_path(solver: str) -> str | None:
151
+ """Look up a solver's install path override.
152
+
153
+ Lookup order: env var (driver-specific) > config [solvers.<name>].path > None.
154
+
155
+ The env var name is driver-specific (AWP_ROOT252, FLUENT_ROOT, ...).
156
+ We only consult the config tier here — env vars are read inside each
157
+ driver's `detect_installed()` as before, so installations without any
158
+ config file work unchanged.
159
+ """
160
+ cfg = _cached_config()
161
+ return cfg.get("solvers", {}).get(solver, {}).get("path")
162
+
163
+
164
+ def resolve_solver_profile(solver: str) -> str | None:
165
+ """Project pin for a solver profile (e.g. pyfluent_0_37_legacy).
166
+
167
+ Advisory only under multi-session (see design note §4): if the
168
+ `sim connect` call names a different solver, this pin is ignored with
169
+ a warning. Same-solver mismatches are caller-decided.
170
+ """
171
+ cfg = _cached_config()
172
+ return cfg.get("solvers", {}).get(solver, {}).get("profile")
173
+
174
+
175
+ def list_solver_pins() -> dict[str, dict]:
176
+ """All `[solvers.<name>]` tables from the merged config."""
177
+ cfg = _cached_config()
178
+ solvers = cfg.get("solvers", {})
179
+ return {k: v for k, v in solvers.items() if isinstance(v, dict)}
180
+
181
+
182
+ # ── Init helper ──────────────────────────────────────────────────────────────
183
+
184
+
185
+ GLOBAL_STUB = """\
186
+ # ~/.sim/config.toml — global sim-cli settings
187
+ #
188
+ # Uncomment and edit values you want to override. With this file absent
189
+ # or empty, sim-cli behaves exactly as it did before (env vars +
190
+ # auto-detection only).
191
+
192
+ # [server]
193
+ # port = 7600
194
+ # host = "127.0.0.1"
195
+
196
+ # [solvers.fluent]
197
+ # path = "C:\\\\Program Files\\\\ANSYS Inc\\\\v252"
198
+
199
+ # [solvers.mapdl]
200
+ # path = "C:\\\\Program Files\\\\ANSYS Inc\\\\v252"
201
+ """
202
+
203
+ PROJECT_STUB = """\
204
+ # .sim/config.toml — project-level sim-cli settings
205
+ #
206
+ # Overrides ~/.sim/config.toml; env vars override this.
207
+
208
+ # [server]
209
+ # port = 7600
210
+
211
+ # [solvers.fluent]
212
+ # profile = "pyfluent_0_38_modern"
213
+ """
214
+
215
+
216
+ def init_config_file(scope: str) -> Path:
217
+ """Create a stub config file at the given scope if it does not exist.
218
+
219
+ `scope` is 'global' or 'project'. Returns the path of the written (or
220
+ already-existing) file. Directories are created as needed.
221
+ """
222
+ if scope == "global":
223
+ path = global_config_path()
224
+ content = GLOBAL_STUB
225
+ elif scope == "project":
226
+ path = project_config_path()
227
+ content = PROJECT_STUB
228
+ else:
229
+ raise ValueError(f"scope must be 'global' or 'project', got {scope!r}")
230
+
231
+ path.parent.mkdir(parents=True, exist_ok=True)
232
+ if not path.exists():
233
+ path.write_text(content, encoding="utf-8")
234
+ return path
235
+
236
+
237
+ # ── sim.toml — project manifest (plugins, defaults) ─────────────────────────
238
+ #
239
+ # Distinct from the global/project `config.toml` files above: `sim.toml`
240
+ # lives at the project root and declares plugins to install + project-wide
241
+ # defaults. It's the file `sim init` creates and `sim setup` reads. Two
242
+ # files because the `[server] / [solvers.<x>]` config tier predates the
243
+ # plugin layer and we don't want to break existing workflows by merging.
244
+
245
+ SIM_TOML_NAME = "sim.toml"
246
+
247
+
248
+ def project_sim_toml_path() -> Path:
249
+ """Walk up from cwd looking for sim.toml; return the canonical location.
250
+
251
+ Returns the cwd path when no sim.toml is found, so `sim init` writes
252
+ there. Walk-up is for the `sim setup` and `sim config show` cases.
253
+ """
254
+ cur = Path.cwd().resolve()
255
+ for parent in (cur, *cur.parents):
256
+ candidate = parent / SIM_TOML_NAME
257
+ if candidate.is_file():
258
+ return candidate
259
+ return cur / SIM_TOML_NAME
260
+
261
+
262
+ SIM_TOML_STUB = """\
263
+ # sim.toml — project manifest for sim-cli
264
+ #
265
+ # Declare the plugins your project depends on and any project-wide defaults.
266
+ # `sim setup` reads this file; `sim config show --json` prints the merged
267
+ # resolved config.
268
+
269
+ [sim]
270
+ # default_solver = "gmsh"
271
+ # workspace = "./workspace"
272
+
273
+ # Each entry under [[sim.plugins]] declares one plugin to install.
274
+ # Sources accepted: name (resolved via the public index), git+https://...,
275
+ # wheel = "./path/to/file.whl", or version = "==X.Y.Z" / ">=X".
276
+ #
277
+ # [[sim.plugins]]
278
+ # name = "coolprop"
279
+ # version = ">=0.1.0"
280
+ """
281
+
282
+
283
+ def init_sim_toml(*, force: bool = False) -> Path:
284
+ """Create a starter sim.toml in the cwd. Idempotent unless ``force=True``."""
285
+ path = Path.cwd() / SIM_TOML_NAME
286
+ if path.exists() and not force:
287
+ return path
288
+ path.write_text(SIM_TOML_STUB, encoding="utf-8")
289
+ return path
290
+
291
+
292
+ def load_sim_toml() -> dict[str, Any]:
293
+ """Load the project's sim.toml, walking up from cwd. Returns {} if none."""
294
+ path = project_sim_toml_path()
295
+ if not path.is_file():
296
+ return {}
297
+ try:
298
+ return tomllib.loads(path.read_text(encoding="utf-8"))
299
+ except (tomllib.TOMLDecodeError, OSError):
300
+ return {}
301
+
302
+
303
+ def validate_sim_toml(path: Path) -> list[str]:
304
+ """Return a list of human-readable validation errors. Empty == valid.
305
+
306
+ Schema (informal):
307
+ [sim]
308
+ default_solver = <string>?
309
+ workspace = <string>?
310
+ server_port = <int>?
311
+
312
+ [[sim.plugins]]
313
+ name = <string> # required
314
+ version = <string>?
315
+ git = <string>?
316
+ wheel = <string>? # local path
317
+ """
318
+ errors: list[str] = []
319
+ if not path.is_file():
320
+ errors.append(f"file not found: {path}")
321
+ return errors
322
+ try:
323
+ data = tomllib.loads(path.read_text(encoding="utf-8"))
324
+ except tomllib.TOMLDecodeError as e:
325
+ errors.append(f"invalid TOML: {e}")
326
+ return errors
327
+
328
+ sim = data.get("sim")
329
+ if sim is None:
330
+ errors.append("missing [sim] table")
331
+ return errors
332
+ if not isinstance(sim, dict):
333
+ errors.append("[sim] must be a table")
334
+ return errors
335
+
336
+ if "default_solver" in sim and not isinstance(sim["default_solver"], str):
337
+ errors.append("[sim].default_solver must be a string")
338
+ if "workspace" in sim and not isinstance(sim["workspace"], str):
339
+ errors.append("[sim].workspace must be a string")
340
+ if "server_port" in sim and not isinstance(sim["server_port"], int):
341
+ errors.append("[sim].server_port must be an integer")
342
+
343
+ plugins = sim.get("plugins") or []
344
+ if not isinstance(plugins, list):
345
+ errors.append("[[sim.plugins]] must be an array of tables")
346
+ else:
347
+ for i, p in enumerate(plugins):
348
+ if not isinstance(p, dict):
349
+ errors.append(f"[[sim.plugins]] entry #{i} must be a table")
350
+ continue
351
+ if "name" not in p or not isinstance(p["name"], str):
352
+ errors.append(f"[[sim.plugins]] entry #{i} missing required 'name'")
353
+ continue
354
+ for k in ("version", "git", "wheel"):
355
+ if k in p and not isinstance(p[k], str):
356
+ errors.append(f"[[sim.plugins]] {p['name']!r} field {k!r} must be a string")
357
+
358
+ return errors
359
+
360
+
361
+ def derive_install_source(plugin_entry: dict[str, Any]) -> str:
362
+ """Translate one [[sim.plugins]] entry to an install-source string.
363
+
364
+ Resolution priority: explicit ``wheel`` path > explicit ``git`` URL
365
+ > ``name@version`` if version set > bare ``name``.
366
+ """
367
+ if "wheel" in plugin_entry:
368
+ return plugin_entry["wheel"]
369
+ if "git" in plugin_entry:
370
+ return f"git+{plugin_entry['git']}"
371
+ name = plugin_entry["name"]
372
+ version = plugin_entry.get("version")
373
+ if version:
374
+ # Strip leading == / >= so it composes with our @ form.
375
+ v = version.lstrip(">=<! ")
376
+ if version.startswith("=="):
377
+ return f"{name}@{v}"
378
+ # Range constraints: fall back to bare name and let pip resolve.
379
+ return name
380
+ return name