devdoor 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.
- devdoor/__init__.py +6 -0
- devdoor/__main__.py +8 -0
- devdoor/cli/__init__.py +1 -0
- devdoor/cli/app.py +99 -0
- devdoor/cli/auth.py +178 -0
- devdoor/cli/domains.py +214 -0
- devdoor/cli/inspector.py +209 -0
- devdoor/cli/local.py +790 -0
- devdoor/cli/share.py +443 -0
- devdoor/cli/validators.py +40 -0
- devdoor/core/__init__.py +1 -0
- devdoor/core/config.py +482 -0
- devdoor/core/engine.py +495 -0
- devdoor/core/events.py +287 -0
- devdoor/core/protocol.py +462 -0
- devdoor/core/router.py +163 -0
- devdoor/inspector/__init__.py +14 -0
- devdoor/inspector/curl.py +68 -0
- devdoor/inspector/daemon_hook.py +147 -0
- devdoor/inspector/replay.py +122 -0
- devdoor/inspector/store.py +291 -0
- devdoor/platform/__init__.py +36 -0
- devdoor/platform/base.py +209 -0
- devdoor/platform/darwin.py +194 -0
- devdoor/platform/linux.py +185 -0
- devdoor/platform/windows.py +143 -0
- devdoor/proxy/__init__.py +7 -0
- devdoor/proxy/certs.py +311 -0
- devdoor/proxy/forwarder.py +457 -0
- devdoor/proxy/https_server.py +122 -0
- devdoor/tui/__init__.py +17 -0
- devdoor/tui/inspector_app.py +667 -0
- devdoor/tunnel/__init__.py +1 -0
- devdoor/tunnel/auth_client.py +287 -0
- devdoor/tunnel/client.py +309 -0
- devdoor/tunnel/httperr.py +168 -0
- devdoor/tunnel/mux.py +566 -0
- devdoor/tunnel/relay_api.py +245 -0
- devdoor-0.1.0.dist-info/METADATA +227 -0
- devdoor-0.1.0.dist-info/RECORD +43 -0
- devdoor-0.1.0.dist-info/WHEEL +4 -0
- devdoor-0.1.0.dist-info/entry_points.txt +3 -0
- devdoor-0.1.0.dist-info/licenses/LICENSE +21 -0
devdoor/core/config.py
ADDED
|
@@ -0,0 +1,482 @@
|
|
|
1
|
+
"""Configuration discovery, validation, runtime paths, and registry locking."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
import re
|
|
7
|
+
import sys
|
|
8
|
+
import tempfile
|
|
9
|
+
from collections.abc import Callable, Generator
|
|
10
|
+
from contextlib import contextmanager
|
|
11
|
+
from dataclasses import dataclass
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
from typing import Literal, cast
|
|
14
|
+
|
|
15
|
+
import yaml
|
|
16
|
+
from pydantic import (
|
|
17
|
+
BaseModel,
|
|
18
|
+
ConfigDict,
|
|
19
|
+
Field,
|
|
20
|
+
ValidationError,
|
|
21
|
+
ValidationInfo,
|
|
22
|
+
field_validator,
|
|
23
|
+
model_validator,
|
|
24
|
+
)
|
|
25
|
+
|
|
26
|
+
if sys.platform != "win32":
|
|
27
|
+
import fcntl
|
|
28
|
+
else:
|
|
29
|
+
import msvcrt
|
|
30
|
+
|
|
31
|
+
DEFAULT_HTTP_PORT = 10080
|
|
32
|
+
DEFAULT_HTTPS_PORT = 10443
|
|
33
|
+
DEFAULT_TLD = ".test"
|
|
34
|
+
MAX_DOMAIN_LENGTH = 253
|
|
35
|
+
CONFIG_FILENAMES = ("devdoor.yaml", ".devdoor.yaml")
|
|
36
|
+
|
|
37
|
+
LogMode = Literal["full", "minimal", "off"]
|
|
38
|
+
|
|
39
|
+
_LABEL_RE = re.compile(r"^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$")
|
|
40
|
+
_DURATION_TOKEN_RE = re.compile(r"(\d+)([smhd])")
|
|
41
|
+
_DURATION_UNITS: dict[str, int] = {"s": 1, "m": 60, "h": 3600, "d": 86400}
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def parse_log_mode(raw: str) -> LogMode:
|
|
45
|
+
"""Parse ``full``, ``minimal``, or ``off`` into a validated ``LogMode`` literal."""
|
|
46
|
+
cleaned = raw.strip().lower()
|
|
47
|
+
if cleaned == "full":
|
|
48
|
+
return "full"
|
|
49
|
+
if cleaned == "minimal":
|
|
50
|
+
return "minimal"
|
|
51
|
+
if cleaned == "off":
|
|
52
|
+
return "off"
|
|
53
|
+
raise ValueError(f"log-mode must be full, minimal, or off; got {raw!r}")
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def parse_duration_seconds(raw: str) -> int:
|
|
57
|
+
"""Parse durations like ``90``, ``30m``, ``2h``, or ``1h30m`` into positive seconds."""
|
|
58
|
+
text = raw.strip().lower()
|
|
59
|
+
if text.isdigit():
|
|
60
|
+
seconds = int(text)
|
|
61
|
+
else:
|
|
62
|
+
pos = 0
|
|
63
|
+
seconds = 0
|
|
64
|
+
for match in _DURATION_TOKEN_RE.finditer(text):
|
|
65
|
+
if match.start() != pos:
|
|
66
|
+
raise ValueError(f"Invalid duration format: {raw!r}")
|
|
67
|
+
seconds += int(match.group(1)) * _DURATION_UNITS[match.group(2)]
|
|
68
|
+
pos = match.end()
|
|
69
|
+
if pos != len(text) or seconds <= 0:
|
|
70
|
+
raise ValueError(f"Invalid duration format: {raw!r}")
|
|
71
|
+
if seconds <= 0:
|
|
72
|
+
raise ValueError("Duration must be greater than 0")
|
|
73
|
+
return seconds
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
class ConfigError(ValueError):
|
|
77
|
+
"""Raised when DevDoor configuration is missing or invalid."""
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
class ConfigNotFoundError(ConfigError):
|
|
81
|
+
"""Raised when no project config file can be discovered."""
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
@dataclass(frozen=True, slots=True)
|
|
85
|
+
class DevDoorPaths:
|
|
86
|
+
"""Resolved filesystem layout under ``~/.devdoor`` (or ``DEVDOOR_HOME``)."""
|
|
87
|
+
|
|
88
|
+
home: Path
|
|
89
|
+
|
|
90
|
+
@property
|
|
91
|
+
def config_file(self) -> Path:
|
|
92
|
+
return self.home / "config.yaml"
|
|
93
|
+
|
|
94
|
+
@property
|
|
95
|
+
def config_lock(self) -> Path:
|
|
96
|
+
return self.home / "config.lock"
|
|
97
|
+
|
|
98
|
+
@property
|
|
99
|
+
def auth_file(self) -> Path:
|
|
100
|
+
return self.home / "auth.json"
|
|
101
|
+
|
|
102
|
+
@property
|
|
103
|
+
def daemon_file(self) -> Path:
|
|
104
|
+
return self.home / "daemon.json"
|
|
105
|
+
|
|
106
|
+
@property
|
|
107
|
+
def inspector_db(self) -> Path:
|
|
108
|
+
return self.home / "inspector.db"
|
|
109
|
+
|
|
110
|
+
@property
|
|
111
|
+
def ca_dir(self) -> Path:
|
|
112
|
+
return self.home / "ca"
|
|
113
|
+
|
|
114
|
+
@property
|
|
115
|
+
def certs_dir(self) -> Path:
|
|
116
|
+
return self.home / "certs"
|
|
117
|
+
|
|
118
|
+
@property
|
|
119
|
+
def logs_dir(self) -> Path:
|
|
120
|
+
return self.home / "logs"
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
@dataclass(frozen=True, slots=True)
|
|
124
|
+
class DomainValidation:
|
|
125
|
+
"""Result of validating and normalizing a domain name."""
|
|
126
|
+
|
|
127
|
+
domain: str
|
|
128
|
+
warnings: tuple[str, ...]
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def resolve_paths(home_override: Path | None = None) -> DevDoorPaths:
|
|
132
|
+
"""Resolve DevDoor runtime directory paths, honoring ``DEVDOOR_HOME``."""
|
|
133
|
+
if home_override is not None:
|
|
134
|
+
return DevDoorPaths(home=home_override.expanduser().resolve())
|
|
135
|
+
env_home = os.environ.get("DEVDOOR_HOME", "").strip()
|
|
136
|
+
if env_home:
|
|
137
|
+
return DevDoorPaths(home=Path(env_home).expanduser().resolve())
|
|
138
|
+
return DevDoorPaths(home=(Path.home() / ".devdoor").resolve())
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def validate_domain(raw: str, *, default_tld: str = DEFAULT_TLD) -> DomainValidation:
|
|
142
|
+
"""Validate and normalize a domain name, applying ``default_tld`` to bare labels."""
|
|
143
|
+
stripped = raw.strip()
|
|
144
|
+
if not stripped or any(ch.isspace() for ch in stripped) or ":" in stripped or "*" in stripped:
|
|
145
|
+
raise ConfigError(f"Invalid domain name: {raw!r}")
|
|
146
|
+
|
|
147
|
+
candidate = stripped.rstrip(".").lower()
|
|
148
|
+
if not candidate:
|
|
149
|
+
raise ConfigError(f"Invalid domain name: {raw!r}")
|
|
150
|
+
|
|
151
|
+
if "." not in candidate:
|
|
152
|
+
tld = default_tld.strip().lower().lstrip(".")
|
|
153
|
+
if not tld:
|
|
154
|
+
raise ConfigError(f"Invalid default TLD: {default_tld!r}")
|
|
155
|
+
candidate = f"{candidate}.{tld}"
|
|
156
|
+
|
|
157
|
+
if len(candidate) > MAX_DOMAIN_LENGTH:
|
|
158
|
+
raise ConfigError(f"Domain exceeds {MAX_DOMAIN_LENGTH} characters: {candidate!r}")
|
|
159
|
+
|
|
160
|
+
labels = candidate.split(".")
|
|
161
|
+
for label in labels:
|
|
162
|
+
if not _LABEL_RE.fullmatch(label):
|
|
163
|
+
raise ConfigError(f"Invalid domain label {label!r} in {candidate!r}")
|
|
164
|
+
|
|
165
|
+
warnings: list[str] = []
|
|
166
|
+
if candidate.endswith(".local"):
|
|
167
|
+
warnings.append(
|
|
168
|
+
f"Domain {candidate!r} uses '.local', which may conflict with mDNS resolvers."
|
|
169
|
+
)
|
|
170
|
+
return DomainValidation(domain=candidate, warnings=tuple(warnings))
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def _ensure_secure_dir(directory: Path) -> None:
|
|
174
|
+
directory.mkdir(parents=True, exist_ok=True)
|
|
175
|
+
if sys.platform != "win32":
|
|
176
|
+
os.chmod(directory, 0o700)
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def _reject_bool_port(value: object) -> object:
|
|
180
|
+
if isinstance(value, bool):
|
|
181
|
+
raise ValueError("Port must be an integer between 1 and 65535, not a boolean.")
|
|
182
|
+
return value
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
class RouteConfig(BaseModel):
|
|
186
|
+
"""Path-prefix upstream route rule for a local or tunneled service."""
|
|
187
|
+
|
|
188
|
+
model_config = ConfigDict(extra="forbid")
|
|
189
|
+
|
|
190
|
+
path: str
|
|
191
|
+
port: int = Field(ge=1, le=65535)
|
|
192
|
+
strip_prefix: bool = True
|
|
193
|
+
|
|
194
|
+
@field_validator("port", mode="before")
|
|
195
|
+
@classmethod
|
|
196
|
+
def _validate_port_type(cls, value: object) -> object:
|
|
197
|
+
return _reject_bool_port(value)
|
|
198
|
+
|
|
199
|
+
@field_validator("path")
|
|
200
|
+
@classmethod
|
|
201
|
+
def _normalize_path(cls, value: str) -> str:
|
|
202
|
+
trimmed = value.strip()
|
|
203
|
+
if not trimmed or not trimmed.startswith("/"):
|
|
204
|
+
raise ValueError(f"Route path must start with '/': {value!r}")
|
|
205
|
+
if any(ch.isspace() or ch in {"?", "#"} for ch in trimmed):
|
|
206
|
+
raise ValueError(f"Route path must not contain spaces, '?' or '#': {value!r}")
|
|
207
|
+
if len(trimmed) > 1:
|
|
208
|
+
trimmed = trimmed.rstrip("/")
|
|
209
|
+
return trimmed
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
def _empty_routes() -> list[RouteConfig]:
|
|
213
|
+
return []
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
def _empty_domains() -> dict[str, RegisteredService]:
|
|
217
|
+
return {}
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
class ServiceConfig(BaseModel):
|
|
221
|
+
"""A domain entry mapping traffic to a primary port and optional path routes."""
|
|
222
|
+
|
|
223
|
+
model_config = ConfigDict(extra="forbid")
|
|
224
|
+
|
|
225
|
+
name: str | None = None
|
|
226
|
+
domain: str
|
|
227
|
+
port: int = Field(ge=1, le=65535)
|
|
228
|
+
routes: list[RouteConfig] = Field(default_factory=_empty_routes)
|
|
229
|
+
cors: bool | None = None
|
|
230
|
+
log_mode: LogMode | None = None
|
|
231
|
+
|
|
232
|
+
@field_validator("port", mode="before")
|
|
233
|
+
@classmethod
|
|
234
|
+
def _validate_port_type(cls, value: object) -> object:
|
|
235
|
+
return _reject_bool_port(value)
|
|
236
|
+
|
|
237
|
+
@field_validator("domain")
|
|
238
|
+
@classmethod
|
|
239
|
+
def _normalize_domain_field(cls, value: str, info: ValidationInfo) -> str:
|
|
240
|
+
raw_ctx: object = info.context
|
|
241
|
+
context = cast(dict[str, object], raw_ctx) if isinstance(raw_ctx, dict) else {}
|
|
242
|
+
raw_tld = context.get("default_tld", DEFAULT_TLD)
|
|
243
|
+
default_tld = raw_tld if isinstance(raw_tld, str) else DEFAULT_TLD
|
|
244
|
+
return validate_domain(value, default_tld=default_tld).domain
|
|
245
|
+
|
|
246
|
+
@model_validator(mode="after")
|
|
247
|
+
def _validate_unique_routes(self) -> ServiceConfig:
|
|
248
|
+
seen_paths: set[str] = set()
|
|
249
|
+
for route in self.routes:
|
|
250
|
+
if route.path in seen_paths:
|
|
251
|
+
raise ValueError(f"Duplicate route path {route.path!r} on domain {self.domain!r}")
|
|
252
|
+
seen_paths.add(route.path)
|
|
253
|
+
return self
|
|
254
|
+
|
|
255
|
+
|
|
256
|
+
class RegisteredService(ServiceConfig):
|
|
257
|
+
"""Service entry persisted inside global ``~/.devdoor/config.yaml``."""
|
|
258
|
+
|
|
259
|
+
project_dir: str | None = None
|
|
260
|
+
|
|
261
|
+
|
|
262
|
+
class ProjectConfig(BaseModel):
|
|
263
|
+
"""Validated ``devdoor.yaml`` / ``.devdoor.yaml`` project configuration."""
|
|
264
|
+
|
|
265
|
+
model_config = ConfigDict(extra="forbid")
|
|
266
|
+
|
|
267
|
+
services: list[ServiceConfig] = Field(min_length=1)
|
|
268
|
+
log_mode: LogMode = "full"
|
|
269
|
+
cors: bool = False
|
|
270
|
+
|
|
271
|
+
@model_validator(mode="after")
|
|
272
|
+
def _validate_unique_domains(self) -> ProjectConfig:
|
|
273
|
+
seen_domains: set[str] = set()
|
|
274
|
+
for service in self.services:
|
|
275
|
+
if service.domain in seen_domains:
|
|
276
|
+
raise ValueError(f"Duplicate service domain: {service.domain!r}")
|
|
277
|
+
seen_domains.add(service.domain)
|
|
278
|
+
return self
|
|
279
|
+
|
|
280
|
+
|
|
281
|
+
class GlobalConfig(BaseModel):
|
|
282
|
+
"""Global DevDoor runtime configuration and active domain registry."""
|
|
283
|
+
|
|
284
|
+
model_config = ConfigDict(extra="forbid")
|
|
285
|
+
|
|
286
|
+
relay_url: str | None = None
|
|
287
|
+
default_tld: str | None = None
|
|
288
|
+
log_mode: LogMode = "full"
|
|
289
|
+
cors: bool = False
|
|
290
|
+
http_port: int = Field(default=DEFAULT_HTTP_PORT, ge=1, le=65535)
|
|
291
|
+
https_port: int = Field(default=DEFAULT_HTTPS_PORT, ge=1, le=65535)
|
|
292
|
+
domains: dict[str, RegisteredService] = Field(default_factory=_empty_domains)
|
|
293
|
+
|
|
294
|
+
@field_validator("http_port", "https_port", mode="before")
|
|
295
|
+
@classmethod
|
|
296
|
+
def _validate_port_types(cls, value: object) -> object:
|
|
297
|
+
return _reject_bool_port(value)
|
|
298
|
+
|
|
299
|
+
@model_validator(mode="after")
|
|
300
|
+
def _validate_domain_keys(self) -> GlobalConfig:
|
|
301
|
+
normalized: dict[str, RegisteredService] = {}
|
|
302
|
+
for key, entry in self.domains.items():
|
|
303
|
+
key_norm = validate_domain(key).domain
|
|
304
|
+
if key_norm != entry.domain:
|
|
305
|
+
raise ValueError(
|
|
306
|
+
f"Registered domain key {key!r} does not match service domain {entry.domain!r}"
|
|
307
|
+
)
|
|
308
|
+
normalized[key_norm] = entry
|
|
309
|
+
self.domains = normalized
|
|
310
|
+
return self
|
|
311
|
+
|
|
312
|
+
|
|
313
|
+
@dataclass(frozen=True, slots=True)
|
|
314
|
+
class LoadedProjectConfig:
|
|
315
|
+
"""Loaded project config together with source path and non-fatal warnings."""
|
|
316
|
+
|
|
317
|
+
config_path: Path
|
|
318
|
+
project: ProjectConfig
|
|
319
|
+
warnings: tuple[str, ...]
|
|
320
|
+
|
|
321
|
+
|
|
322
|
+
def discover_project_config(
|
|
323
|
+
*,
|
|
324
|
+
start_dir: Path | None = None,
|
|
325
|
+
config_path: Path | None = None,
|
|
326
|
+
) -> Path:
|
|
327
|
+
"""Locate ``devdoor.yaml`` or ``.devdoor.yaml`` searching upward from ``start_dir``."""
|
|
328
|
+
if config_path is not None:
|
|
329
|
+
resolved = config_path.expanduser().resolve()
|
|
330
|
+
if not resolved.is_file():
|
|
331
|
+
raise ConfigNotFoundError(f"Config file not found: {resolved}")
|
|
332
|
+
return resolved
|
|
333
|
+
|
|
334
|
+
current = (start_dir or Path.cwd()).expanduser().resolve()
|
|
335
|
+
if current.is_file():
|
|
336
|
+
current = current.parent
|
|
337
|
+
|
|
338
|
+
for directory in (current, *current.parents):
|
|
339
|
+
for filename in CONFIG_FILENAMES:
|
|
340
|
+
candidate = directory / filename
|
|
341
|
+
if candidate.is_file():
|
|
342
|
+
return candidate
|
|
343
|
+
|
|
344
|
+
raise ConfigNotFoundError(
|
|
345
|
+
f"No devdoor.yaml or .devdoor.yaml found searching upward from {current}"
|
|
346
|
+
)
|
|
347
|
+
|
|
348
|
+
|
|
349
|
+
def _read_yaml_mapping(path: Path) -> dict[str, object]:
|
|
350
|
+
try:
|
|
351
|
+
text = path.read_text(encoding="utf-8")
|
|
352
|
+
raw = yaml.safe_load(text)
|
|
353
|
+
except (OSError, yaml.YAMLError) as exc:
|
|
354
|
+
raise ConfigError(f"Failed to read YAML config {path}: {exc}") from exc
|
|
355
|
+
|
|
356
|
+
if raw is None:
|
|
357
|
+
return {}
|
|
358
|
+
if not isinstance(raw, dict):
|
|
359
|
+
raise ConfigError(f"Config file {path} must contain a top-level YAML mapping.")
|
|
360
|
+
mapping = cast(dict[object, object], raw)
|
|
361
|
+
return {str(k): v for k, v in mapping.items()}
|
|
362
|
+
|
|
363
|
+
|
|
364
|
+
def load_project_config(
|
|
365
|
+
*,
|
|
366
|
+
start_dir: Path | None = None,
|
|
367
|
+
config_path: Path | None = None,
|
|
368
|
+
default_tld: str = DEFAULT_TLD,
|
|
369
|
+
) -> LoadedProjectConfig:
|
|
370
|
+
"""Discover, parse, and validate a ``devdoor.yaml`` / ``.devdoor.yaml`` file."""
|
|
371
|
+
path = discover_project_config(start_dir=start_dir, config_path=config_path)
|
|
372
|
+
raw = _read_yaml_mapping(path)
|
|
373
|
+
|
|
374
|
+
try:
|
|
375
|
+
project = ProjectConfig.model_validate(raw, context={"default_tld": default_tld})
|
|
376
|
+
except ValidationError as exc:
|
|
377
|
+
raise ConfigError(f"Invalid project config in {path}: {exc}") from exc
|
|
378
|
+
|
|
379
|
+
warnings: list[str] = []
|
|
380
|
+
for service in project.services:
|
|
381
|
+
warnings.extend(validate_domain(service.domain, default_tld=default_tld).warnings)
|
|
382
|
+
|
|
383
|
+
return LoadedProjectConfig(
|
|
384
|
+
config_path=path,
|
|
385
|
+
project=project,
|
|
386
|
+
warnings=tuple(dict.fromkeys(warnings)),
|
|
387
|
+
)
|
|
388
|
+
|
|
389
|
+
|
|
390
|
+
@contextmanager
|
|
391
|
+
def with_config_lock(paths: DevDoorPaths | None = None) -> Generator[Path]:
|
|
392
|
+
"""Acquire an exclusive advisory lock on ``~/.devdoor/config.lock``."""
|
|
393
|
+
resolved = paths or resolve_paths()
|
|
394
|
+
_ensure_secure_dir(resolved.home)
|
|
395
|
+
lock_path = resolved.config_lock
|
|
396
|
+
|
|
397
|
+
with lock_path.open("a+b") as lock_file:
|
|
398
|
+
if sys.platform != "win32":
|
|
399
|
+
os.chmod(lock_path, 0o600)
|
|
400
|
+
fcntl.flock(lock_file.fileno(), fcntl.LOCK_EX)
|
|
401
|
+
else:
|
|
402
|
+
lock_file.seek(0, os.SEEK_END)
|
|
403
|
+
if lock_file.tell() == 0:
|
|
404
|
+
lock_file.write(b"\0")
|
|
405
|
+
lock_file.flush()
|
|
406
|
+
lock_file.seek(0)
|
|
407
|
+
msvcrt.locking(lock_file.fileno(), msvcrt.LK_LOCK, 1)
|
|
408
|
+
|
|
409
|
+
try:
|
|
410
|
+
yield lock_path
|
|
411
|
+
finally:
|
|
412
|
+
if sys.platform != "win32":
|
|
413
|
+
fcntl.flock(lock_file.fileno(), fcntl.LOCK_UN)
|
|
414
|
+
else:
|
|
415
|
+
lock_file.seek(0)
|
|
416
|
+
msvcrt.locking(lock_file.fileno(), msvcrt.LK_UNLCK, 1)
|
|
417
|
+
|
|
418
|
+
|
|
419
|
+
def _read_global_config_unlocked(paths: DevDoorPaths) -> GlobalConfig:
|
|
420
|
+
if not paths.config_file.exists():
|
|
421
|
+
return GlobalConfig()
|
|
422
|
+
raw = _read_yaml_mapping(paths.config_file)
|
|
423
|
+
try:
|
|
424
|
+
return GlobalConfig.model_validate(raw)
|
|
425
|
+
except ValidationError as exc:
|
|
426
|
+
raise ConfigError(f"Invalid global config in {paths.config_file}: {exc}") from exc
|
|
427
|
+
|
|
428
|
+
|
|
429
|
+
def load_global_config(paths: DevDoorPaths | None = None) -> GlobalConfig:
|
|
430
|
+
"""Load global configuration from ``~/.devdoor/config.yaml``."""
|
|
431
|
+
resolved = paths or resolve_paths()
|
|
432
|
+
return _read_global_config_unlocked(resolved)
|
|
433
|
+
|
|
434
|
+
|
|
435
|
+
def atomic_write_text(target: Path, content: str, *, mode: int = 0o600) -> None:
|
|
436
|
+
"""Atomically write UTF-8 text to ``target`` with secure permissions."""
|
|
437
|
+
_ensure_secure_dir(target.parent)
|
|
438
|
+
tmp_path: Path | None = None
|
|
439
|
+
try:
|
|
440
|
+
with tempfile.NamedTemporaryFile(
|
|
441
|
+
mode="w",
|
|
442
|
+
encoding="utf-8",
|
|
443
|
+
dir=target.parent,
|
|
444
|
+
prefix=f".{target.name}-",
|
|
445
|
+
suffix=".tmp",
|
|
446
|
+
delete=False,
|
|
447
|
+
) as handle:
|
|
448
|
+
tmp_path = Path(handle.name)
|
|
449
|
+
handle.write(content)
|
|
450
|
+
if sys.platform != "win32":
|
|
451
|
+
os.chmod(tmp_path, mode)
|
|
452
|
+
os.replace(tmp_path, target)
|
|
453
|
+
tmp_path = None
|
|
454
|
+
finally:
|
|
455
|
+
if tmp_path is not None:
|
|
456
|
+
tmp_path.unlink(missing_ok=True)
|
|
457
|
+
|
|
458
|
+
|
|
459
|
+
def _write_global_config_unlocked(config: GlobalConfig, paths: DevDoorPaths) -> None:
|
|
460
|
+
payload = yaml.safe_dump(config.model_dump(mode="json", exclude_none=True), sort_keys=False)
|
|
461
|
+
atomic_write_text(paths.config_file, payload, mode=0o600)
|
|
462
|
+
|
|
463
|
+
|
|
464
|
+
def save_global_config(config: GlobalConfig, paths: DevDoorPaths | None = None) -> None:
|
|
465
|
+
"""Persist ``config`` atomically under ``with_config_lock``."""
|
|
466
|
+
resolved = paths or resolve_paths()
|
|
467
|
+
with with_config_lock(resolved):
|
|
468
|
+
_write_global_config_unlocked(config, resolved)
|
|
469
|
+
|
|
470
|
+
|
|
471
|
+
def mutate_global_config(
|
|
472
|
+
mutator: Callable[[GlobalConfig], GlobalConfig],
|
|
473
|
+
*,
|
|
474
|
+
paths: DevDoorPaths | None = None,
|
|
475
|
+
) -> GlobalConfig:
|
|
476
|
+
"""Atomically read, transform, and save ``~/.devdoor/config.yaml`` under ``config.lock``."""
|
|
477
|
+
resolved = paths or resolve_paths()
|
|
478
|
+
with with_config_lock(resolved):
|
|
479
|
+
current = _read_global_config_unlocked(resolved)
|
|
480
|
+
updated = mutator(current)
|
|
481
|
+
_write_global_config_unlocked(updated, resolved)
|
|
482
|
+
return updated
|