lpip.config

src/lpip/config.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
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
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
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
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
"""Load effective lpip configuration and persist set/unset with tomlkit."""

from __future__ import annotations

import os
import tomllib
from collections.abc import Mapping, Sequence
from dataclasses import dataclass
from pathlib import Path
from typing import Any

import tomlkit
from platformdirs import PlatformDirs
from tomlkit.exceptions import TOMLKitError

from lpip.errors import (
    ConfigAlreadyExistsError,
    ConfigSchemaError,
    InvalidSourceNameError,
    SourceAlreadyExistsError,
    SourceNotFoundError,
    TomlParseError,
    UnknownTomlKeyError,
)
from lpip.models import (
    EffectiveConfig,
    PolicyConfig,
    RefreshMode,
    RuntimeConfig,
    SourceConfig,
    SourceType,
)
from lpip.validation import (
    CONFIG_TOP_KEYS,
    POLICY_KEYS,
    RUNTIME_KEYS,
    SOURCE_ITEM_KEYS,
    SOURCE_KEYS,
    SOURCE_NAME_RE,
    first_unknown_key,
    optional_str,
)

APPNAME = "lpip"
APPAUTHOR = "libesys"
WORKSPACE_CONFIG = Path(".tools") / "libesys" / "lpip" / "config.toml"

# Architecture template (ADR-0013). Static write; tomlkit mutations are batch-15.
CONFIG_INIT_TEMPLATE = """\
# lpip persistent configuration (v1).
# Edit values. Unknown keys fail validation.

[source]
type = "git"  # "git" or "file"
url = "ssh://git.example/lpip-catalog.git"
revision = "main"
path = "lpip-sources.toml"
refresh = "auto"  # always | auto | never

# Local catalog instead of Git:
# type = "file"
# path = "~/company/lpip-sources.toml"
# (omit url, revision, and refresh when type is file)
#
# More than one catalog: lpip source add / list / remove ([[sources]]).
# Do not keep both [source] and [[sources]] in the same file.

[policy]
allowed_schemes = ["git+ssh", "git+https"]
require_pinned_revision = false

[runtime]
python = "python3"
"""

_ENV_CONFIG = "LPIP_CONFIG"
_ENV_TYPE = "LPIP_SOURCE_TYPE"
_ENV_PATH = "LPIP_SOURCE_PATH"
_ENV_URL = "LPIP_SOURCE_URL"
_ENV_REVISION = "LPIP_SOURCE_REVISION"


@dataclass(frozen=True)
class ConfigOverrides:
    """CLI-layer overlays (applied last)."""

    config_path: Path | None = None
    source_type: str | None = None
    source_path: str | None = None
    source_url: str | None = None
    source_revision: str | None = None


def platform_dirs() -> PlatformDirs:
    return PlatformDirs(appname=APPNAME, appauthor=APPAUTHOR)


def default_user_config_path() -> Path:
    return Path(platform_dirs().user_config_dir) / "config.toml"


def default_user_cache_dir() -> Path:
    return Path(platform_dirs().user_cache_dir)


def find_git_root(start: Path) -> Path | None:
    current = start.resolve()
    for directory in (current, *current.parents):
        marker = directory / ".git"
        if marker.is_dir() or marker.is_file():
            return directory
    return None


def workspace_config_path(git_root: Path) -> Path:
    return git_root / WORKSPACE_CONFIG


def load_effective_config(
    *,
    cwd: Path | None = None,
    environ: Mapping[str, str] | None = None,
    overrides: ConfigOverrides | None = None,
    user_config_path: Path | None = None,
) -> EffectiveConfig:
    """Merge CLI, env, workspace/user file, and defaults. Does not create files."""
    cwd = (cwd or Path.cwd()).resolve()
    env = environ if environ is not None else os.environ
    overrides = overrides or ConfigOverrides()
    user_path = user_config_path if user_config_path is not None else default_user_config_path()

    persistent = _select_persistent_file(cwd, env, overrides, user_path)
    raw = _read_config_file(persistent) if persistent is not None else {}
    merged = _apply_env_and_cli(raw, env, overrides)
    return _build_effective(merged, persistent)


def resolve_init_target(
    *,
    cwd: Path | None = None,
    environ: Mapping[str, str] | None = None,
    user_config_path: Path | None = None,
) -> Path:
    """Path ``config init`` would write (ADR-0013). Does not create files."""
    cwd = (cwd or Path.cwd()).resolve()
    env = environ if environ is not None else os.environ
    user_path = user_config_path if user_config_path is not None else default_user_config_path()
    git_root = find_git_root(cwd)
    if git_root is not None:
        return workspace_config_path(git_root)
    explicit = env.get(_ENV_CONFIG)
    if explicit:
        return Path(explicit).expanduser()
    return user_path


def write_init_template(path: Path) -> Path:
    """Write the v1 commented template. Fails if the path already exists."""
    if path.exists():
        raise ConfigAlreadyExistsError(path)
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_text(CONFIG_INIT_TEMPLATE, encoding="utf-8")
    return path


_SECTION_KEYS = {
    "source": SOURCE_KEYS,
    "policy": POLICY_KEYS,
    "runtime": RUNTIME_KEYS,
}


def _writable_config_path(
    *,
    cwd: Path | None = None,
    environ: Mapping[str, str] | None = None,
    user_config_path: Path | None = None,
) -> Path:
    path = resolve_init_target(cwd=cwd, environ=environ, user_config_path=user_config_path)
    if not path.is_file():
        raise ConfigSchemaError(
            f"Config file was not found: {path}",
            path=path,
            hint="Create the file with lpip config init before set or unset.",
        )
    return path


def _split_config_key(key: str, *, path: Path) -> tuple[str, str]:
    parts = key.split(".")
    if len(parts) != 2 or not parts[0] or not parts[1]:
        raise ConfigSchemaError(
            f"Config key {key!r} must be a dotted v1 key such as source.path.",
            path=path,
        )
    table, field = parts
    allowed = _SECTION_KEYS.get(table)
    if allowed is None:
        raise UnknownTomlKeyError(table, path=path, kind="config")
    if field not in allowed:
        raise UnknownTomlKeyError(f"{table}.{field}", path=path, kind="config")
    return table, field


def _parse_set_value(field: str, raw: str, *, path: Path) -> object:
    if field == "require_pinned_revision":
        low = raw.strip().lower()
        if low in {"true", "false"}:
            return low == "true"
        raise ConfigSchemaError(
            "policy.require_pinned_revision must be true or false.",
            path=path,
        )
    if field == "allowed_schemes":
        try:
            parsed = tomlkit.parse(f"x = {raw}")["x"]
        except TOMLKitError as exc:
            raise ConfigSchemaError(
                "policy.allowed_schemes must be a TOML array of strings.",
                path=path,
                hint='Example: \'["git+ssh", "git+https"]\'',
            ) from exc
        if not isinstance(parsed, list) or not all(isinstance(item, str) for item in parsed):
            raise ConfigSchemaError(
                "policy.allowed_schemes must be a TOML array of strings.",
                path=path,
            )
        return parsed
    if field == "type":
        if raw not in {item.value for item in SourceType}:
            raise ConfigSchemaError(
                f"source.type must be 'file' or 'git', got {raw!r}.",
                path=path,
            )
        return raw
    if field == "refresh":
        if raw not in {item.value for item in RefreshMode}:
            raise ConfigSchemaError(
                f"source.refresh must be always, auto, or never, got {raw!r}.",
                path=path,
            )
        return raw
    return raw


def _load_tomlkit(path: Path) -> tomlkit.TOMLDocument:
    try:
        return tomlkit.parse(path.read_text(encoding="utf-8"))
    except TOMLKitError as exc:
        raise TomlParseError(path, detail=str(exc)) from exc


def _dump_tomlkit(path: Path, document: tomlkit.TOMLDocument) -> None:
    path.write_text(tomlkit.dumps(document), encoding="utf-8")


def _toml_table(document: tomlkit.TOMLDocument, key: str) -> Any:
    return document[key]


def set_config_key(
    key: str,
    value: str,
    *,
    cwd: Path | None = None,
    environ: Mapping[str, str] | None = None,
    user_config_path: Path | None = None,
) -> Path:
    """Set a dotted v1 key in the init-target config file (ADR-0014)."""
    path = _writable_config_path(cwd=cwd, environ=environ, user_config_path=user_config_path)
    table, field = _split_config_key(key, path=path)
    parsed = _parse_set_value(field, value, path=path)
    document = _load_tomlkit(path)
    if table not in document:
        document[table] = tomlkit.table()
    _toml_table(document, table)[field] = parsed
    _dump_tomlkit(path, document)
    return path


def unset_config_key(
    key: str,
    *,
    cwd: Path | None = None,
    environ: Mapping[str, str] | None = None,
    user_config_path: Path | None = None,
) -> Path:
    """Remove a dotted v1 key from the init-target config file (ADR-0014)."""
    path = _writable_config_path(cwd=cwd, environ=environ, user_config_path=user_config_path)
    table, field = _split_config_key(key, path=path)
    document = _load_tomlkit(path)
    section = document.get(table)
    if isinstance(section, dict) and field in section:
        del section[field]
    _dump_tomlkit(path, document)
    return path


def format_config_value(cfg: EffectiveConfig, key: str) -> str:
    """Format one dotted v1 key from effective config (``config get``)."""
    values: dict[str, str] = {
        "source.type": cfg.source.type.value,
        "source.path": cfg.source.path,
        "source.url": cfg.source.url or "",
        "source.revision": cfg.source.revision or "",
        "source.refresh": cfg.source.refresh.value if cfg.source.refresh is not None else "",
        "policy.require_pinned_revision": "true" if cfg.policy.require_pinned_revision else "false",
        "policy.allowed_schemes": "["
        + ", ".join(f'"{item}"' for item in cfg.policy.allowed_schemes)
        + "]",
        "runtime.python": cfg.runtime.python,
    }
    if key not in values:
        raise ConfigSchemaError(
            f"Unknown config key {key!r}.",
            hint="Use a dotted v1 key such as source.path or runtime.python.",
        )
    return values[key]


def format_effective_config(cfg: EffectiveConfig) -> str:
    """Human-readable effective config (``config show``)."""
    path = str(cfg.config_path) if cfg.config_path is not None else ""
    keys = (
        "source.type",
        "source.path",
        "source.url",
        "source.revision",
        "source.refresh",
        "policy.require_pinned_revision",
        "policy.allowed_schemes",
        "runtime.python",
    )
    lines = [f"config_path: {path}"]
    if len(cfg.sources) > 1:
        lines.append(format_sources_table(cfg.sources))
        extra = [key for key in keys if not key.startswith("source.")]
    else:
        extra = list(keys)
    lines.extend(f"{key}: {format_config_value(cfg, key)}" for key in extra)
    return "\n".join(lines)


def _source_location(src: SourceConfig) -> str:
    if src.type is SourceType.GIT:
        loc = src.url or ""
        if src.revision:
            loc = f"{loc}@{src.revision}"
        return f"{loc} {src.path}".strip()
    return src.path


def format_sources_table(sources: Sequence[SourceConfig]) -> str:
    """Table for ``lpip source list`` (ADR-0021)."""
    headers = ("name", "type", "location")
    rows = [(src.name, src.type.value, _source_location(src)) for src in sources]
    widths = [len(h) for h in headers]
    for row in rows:
        widths = [max(width, len(cell)) for width, cell in zip(widths, row, strict=True)]

    def _line(cells: tuple[str, ...]) -> str:
        return "  ".join(cell.ljust(width) for cell, width in zip(cells, widths, strict=True))

    lines = [_line(headers)]
    lines.extend(_line(row) for row in rows)
    return "\n".join(lines)


def _validate_source_name(name: str) -> str:
    cleaned = name.strip()
    if not SOURCE_NAME_RE.fullmatch(cleaned):
        raise InvalidSourceNameError(name)
    return cleaned


def _source_table(
    *,
    name: str,
    source_type: SourceType,
    path: str,
    url: str | None,
    revision: str | None,
    refresh: str | None,
) -> Any:
    item = tomlkit.table()
    item["name"] = name
    item["type"] = source_type.value
    item["path"] = path
    if source_type is SourceType.GIT:
        if url:
            item["url"] = url
        if revision:
            item["revision"] = revision
        item["refresh"] = refresh or RefreshMode.AUTO.value
    return item


def _migrate_legacy_source(document: tomlkit.TOMLDocument) -> None:
    legacy = document.get("source")
    if not isinstance(legacy, dict):
        return
    item = tomlkit.table()
    item["name"] = "default"
    for key in ("type", "path", "url", "revision", "refresh"):
        if key in legacy:
            item[key] = legacy[key]
    del document["source"]
    array = tomlkit.aot()
    array.append(item)
    document["sources"] = array


def add_configured_source(
    name: str,
    *,
    source_type: SourceType,
    path: str,
    url: str | None = None,
    revision: str | None = None,
    refresh: str | None = None,
    cwd: Path | None = None,
    environ: Mapping[str, str] | None = None,
    user_config_path: Path | None = None,
) -> Path:
    """Append [[sources]] in the init-target config (ADR-0021)."""
    name = _validate_source_name(name)
    if source_type is SourceType.GIT and not (url or "").strip():
        raise ConfigSchemaError(
            "source add --type git requires --url.",
            hint="Pass --url ssh://git.example/lpip-catalog.git",
        )
    if source_type is SourceType.FILE and not path.strip():
        raise ConfigSchemaError("source add --type file requires --path.")
    dest = _writable_config_path(cwd=cwd, environ=environ, user_config_path=user_config_path)
    document = _load_tomlkit(dest)
    if "source" in document and "sources" not in document:
        _migrate_legacy_source(document)
    existing = document.get("sources")
    names: list[str] = []
    if existing is not None:
        for row in existing:
            row_name = str(row.get("name") or "")
            names.append(row_name)
    if name in names:
        raise SourceAlreadyExistsError(name, path=dest)
    if "sources" not in document:
        document["sources"] = tomlkit.aot()
    _toml_table(document, "sources").append(
        _source_table(
            name=name,
            source_type=source_type,
            path=path or "lpip-sources.toml",
            url=url,
            revision=revision,
            refresh=refresh,
        )
    )
    _dump_tomlkit(dest, document)
    return dest


def remove_configured_source(
    name: str,
    *,
    cwd: Path | None = None,
    environ: Mapping[str, str] | None = None,
    user_config_path: Path | None = None,
) -> Path:
    """Remove a [[sources]] row (ADR-0021)."""
    name = _validate_source_name(name)
    dest = _writable_config_path(cwd=cwd, environ=environ, user_config_path=user_config_path)
    document = _load_tomlkit(dest)
    if "source" in document and "sources" not in document:
        _migrate_legacy_source(document)
    existing = document.get("sources")
    if existing is None:
        raise SourceNotFoundError(name)
    kept = tomlkit.aot()
    found = False
    for row in existing:
        if str(row.get("name") or "") == name:
            found = True
            continue
        kept.append(row)
    if not found:
        raise SourceNotFoundError(name)
    if len(kept) == 0:
        del document["sources"]
    else:
        document["sources"] = kept
    _dump_tomlkit(dest, document)
    return dest


def _select_persistent_file(
    cwd: Path,
    env: Mapping[str, str],
    overrides: ConfigOverrides,
    user_path: Path,
) -> Path | None:
    explicit = overrides.config_path
    if explicit is None:
        cfg = env.get(_ENV_CONFIG)
        if cfg:
            explicit = Path(cfg)
    if explicit is not None:
        path = explicit.expanduser()
        if not path.is_file():
            raise ConfigSchemaError(
                f"Config file was not found: {path}",
                path=path,
                hint="Create the file with lpip config init, or fix LPIP_CONFIG.",
            )
        return path

    git_root = find_git_root(cwd)
    if git_root is not None:
        workspace = workspace_config_path(git_root)
        if workspace.is_file():
            return workspace

    if user_path.is_file():
        return user_path
    return None


def _read_config_file(path: Path) -> dict[str, Any]:
    try:
        with path.open("rb") as fh:
            data = tomllib.load(fh)
    except tomllib.TOMLDecodeError as exc:
        raise TomlParseError(path, detail=str(exc)) from exc

    unknown = first_unknown_key(data, CONFIG_TOP_KEYS)
    if unknown is not None:
        raise UnknownTomlKeyError(unknown, path=path, kind="config")
    result: dict[str, Any] = {}
    if "source" in data and "sources" in data:
        raise ConfigSchemaError(
            "Config has both [source] and [[sources]].",
            path=path,
            hint="Use one [source] table, or only [[sources]] (lpip source add).",
        )
    if "source" in data:
        result["source"] = _section(data["source"], SOURCE_KEYS, path, "source")
    if "sources" in data:
        raw_sources = data["sources"]
        if not isinstance(raw_sources, list):
            raise ConfigSchemaError("[[sources]] must be an array of tables.", path=path)
        result["sources"] = [
            _section(item, SOURCE_ITEM_KEYS, path, "sources") for item in raw_sources
        ]
    if "policy" in data:
        result["policy"] = _section(data["policy"], POLICY_KEYS, path, "policy")
    if "runtime" in data:
        result["runtime"] = _section(data["runtime"], RUNTIME_KEYS, path, "runtime")
    return result


def _section(body: object, allowed: frozenset[str], path: Path, name: str) -> dict[str, Any]:
    if not isinstance(body, dict):
        raise ConfigSchemaError(f"[{name}] must be a table.", path=path)
    unknown = first_unknown_key(body, allowed)
    if unknown is not None:
        raise UnknownTomlKeyError(f"{name}.{unknown}", path=path, kind="config")
    return dict(body)


def _apply_env_and_cli(
    raw: dict[str, Any],
    env: Mapping[str, str],
    overrides: ConfigOverrides,
) -> dict[str, Any]:
    source = dict(raw.get("source") or {})
    sources = [dict(item) for item in raw.get("sources") or []]
    policy = dict(raw.get("policy") or {})
    runtime = dict(raw.get("runtime") or {})

    def overlay(target: dict[str, Any], key: str, value: str | None) -> None:
        if value is not None and value != "":
            target[key] = value

    first = sources[0] if sources else source
    overlay(first, "type", env.get(_ENV_TYPE))
    overlay(first, "path", env.get(_ENV_PATH))
    overlay(first, "url", env.get(_ENV_URL))
    overlay(first, "revision", env.get(_ENV_REVISION))
    overlay(first, "type", overrides.source_type)
    overlay(first, "path", overrides.source_path)
    overlay(first, "url", overrides.source_url)
    overlay(first, "revision", overrides.source_revision)
    if sources:
        sources[0] = first
        return {"sources": sources, "policy": policy, "runtime": runtime}
    return {"source": source, "policy": policy, "runtime": runtime}


def _opt(value: object, *, path: Path | None) -> str | None:
    try:
        return optional_str(value)
    except TypeError as exc:
        raise ConfigSchemaError(str(exc), path=path) from exc


def _parse_source_config(src_raw: Mapping[str, Any], config_path: Path | None) -> SourceConfig:
    type_s = _opt(src_raw.get("type"), path=config_path) or SourceType.FILE.value
    try:
        source_type = SourceType(type_s)
    except ValueError as exc:
        raise ConfigSchemaError(
            f"source.type must be 'file' or 'git', got {type_s!r}.",
            path=config_path,
        ) from exc

    path = _opt(src_raw.get("path"), path=config_path) or "lpip-sources.toml"
    url = _opt(src_raw.get("url"), path=config_path)
    revision = _opt(src_raw.get("revision"), path=config_path)
    refresh_s = _opt(src_raw.get("refresh"), path=config_path)
    if refresh_s is None:
        refresh = RefreshMode.AUTO if source_type is SourceType.GIT else None
    else:
        try:
            refresh = RefreshMode(refresh_s)
        except ValueError as exc:
            raise ConfigSchemaError(
                f"source.refresh must be always, auto, or never, got {refresh_s!r}.",
                path=config_path,
            ) from exc

    if source_type is SourceType.GIT and not url:
        raise ConfigSchemaError(
            "source.url is required when source.type is git.",
            path=config_path,
            hint="Set source.url in config.toml or LPIP_SOURCE_URL.",
        )

    name = _opt(src_raw.get("name"), path=config_path) or "default"
    if not SOURCE_NAME_RE.fullmatch(name):
        raise InvalidSourceNameError(name)
    return SourceConfig(
        type=source_type,
        path=path,
        url=url,
        revision=revision,
        refresh=refresh,
        name=name,
    )


def _build_effective(merged: dict[str, Any], config_path: Path | None) -> EffectiveConfig:
    pol_raw = merged.get("policy") or {}
    run_raw = merged.get("runtime") or {}
    raw_sources = merged.get("sources")
    if raw_sources:
        sources = tuple(_parse_source_config(item, config_path) for item in raw_sources)
        names = [item.name for item in sources]
        if len(names) != len(set(names)):
            raise ConfigSchemaError(
                "[[sources]] names must be unique.",
                path=config_path,
            )
    else:
        sources = (_parse_source_config(merged.get("source") or {}, config_path),)

    schemes = pol_raw.get("allowed_schemes")
    if schemes is None:
        allowed = ("git+ssh", "git+https")
    elif isinstance(schemes, list) and all(isinstance(item, str) for item in schemes):
        allowed = tuple(schemes)
    else:
        raise ConfigSchemaError(
            "policy.allowed_schemes must be an array of strings.",
            path=config_path,
        )

    pin = pol_raw.get("require_pinned_revision", False)
    if not isinstance(pin, bool):
        raise ConfigSchemaError(
            "policy.require_pinned_revision must be a boolean.",
            path=config_path,
        )

    python = _opt(run_raw.get("python"), path=config_path) or "python3"

    return EffectiveConfig(
        sources=sources,
        policy=PolicyConfig(allowed_schemes=allowed, require_pinned_revision=pin),
        runtime=RuntimeConfig(python=python),
        config_path=config_path,
    )