lpip.cli

src/lpip/cli.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
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
"""Thin Typer CLI (ADR-0006). Command bodies call services only."""

from __future__ import annotations

import sys
from pathlib import Path

import typer

from lpip import format_cli_version
from lpip.catalog import (
    Catalog,
    add_package_to_catalog_file,
    git_sources,
    load_catalog,
    load_catalog_for_config,
    load_merged_catalog,
    local_catalog_path,
    planned_git_cache_paths_for,
    purge_all_git_catalog_caches,
    resolve_authoring_catalog_path,
    resolve_catalog_location,
    resolve_source_location,
    write_catalog_init_template,
)
from lpip.config import (
    add_configured_source,
    format_config_value,
    format_effective_config,
    format_sources_table,
    load_effective_config,
    remove_configured_source,
    resolve_init_target,
    set_config_key,
    unset_config_key,
    write_init_template,
)
from lpip.errors import (
    GitNotFoundError,
    InstallUsageError,
    LpipError,
    MissingCatalogAddFieldsError,
    UnknownPackageError,
)
from lpip.gitutils import find_git_executable
from lpip.models import EffectiveConfig, PackageSource, SourceType
from lpip.pipwrap import (
    format_pip_install_command,
    render_catalog_install,
    render_requirement,
    run_pip_install,
)
from lpip.pipxutils import format_pipx_install_command, require_pipx, run_pipx_install
from lpip.reqfile import load_requirement_lines, requirement_name
from lpip.validation import url_scheme
from lpip.versions import format_versions_report, list_package_versions

app = typer.Typer(
    name="lpip",
    help="Name-oriented front end to pip for Git-backed internal packages.",
    no_args_is_help=True,
    pretty_exceptions_enable=False,
    pretty_exceptions_show_locals=False,
)
config_app = typer.Typer(
    name="config",
    help="Persistent configuration.",
    no_args_is_help=True,
)
catalog_app = typer.Typer(
    name="catalog",
    help="Author a catalog file, or manage the Git-backed catalog cache.",
    no_args_is_help=True,
)
index_app = typer.Typer(
    name="index",
    help="Inspect versions (pip-compatible spelling of lpip versions).",
    no_args_is_help=True,
)
source_app = typer.Typer(
    name="source",
    help="Register catalog locations (not package authoring).",
    no_args_is_help=True,
)
app.add_typer(config_app, name="config")
app.add_typer(catalog_app, name="catalog")
app.add_typer(index_app, name="index")
app.add_typer(source_app, name="source")


def _print_version_and_exit(value: bool) -> None:
    if value:
        typer.echo(format_cli_version())
        raise typer.Exit()


def _invoked_as_lpipx(ctx: typer.Context) -> bool:
    prog = (ctx.info_name or "").lower()
    argv0 = Path(sys.argv[0]).name.lower()
    return prog.startswith("lpipx") or argv0.startswith("lpipx")


@app.callback()
def _root(
    ctx: typer.Context,
    _version: bool = typer.Option(
        False,
        "--version",
        "-V",
        help="Print the lpip version and exit.",
        callback=_print_version_and_exit,
        is_eager=True,
    ),
) -> None:
    """lpip command group (subcommands only)."""
    ctx.ensure_object(dict)
    ctx.obj["pipx_default"] = _invoked_as_lpipx(ctx)


def _load_catalog() -> Catalog:
    cwd = Path.cwd()
    cfg = load_effective_config(cwd=cwd)
    return load_catalog_for_config(cfg, cwd=cwd)


_LIST_HEADERS = ("name", "url", "revision", "subdirectory")
_LIST_HEADERS_WITH_SOURCE = ("name", "source", "url", "revision", "subdirectory")


def format_list_table(packages: tuple[PackageSource, ...]) -> str:
    """Aligned table; cells are never truncated (AC-0007)."""
    origins = {pkg.catalog_source for pkg in packages if pkg.catalog_source}
    with_source = len(origins) > 1
    headers = _LIST_HEADERS_WITH_SOURCE if with_source else _LIST_HEADERS
    rows: list[tuple[str, ...]]
    if with_source:
        rows = [
            (
                pkg.name,
                pkg.catalog_source or "",
                pkg.url,
                pkg.revision or "",
                pkg.subdirectory or "",
            )
            for pkg in packages
        ]
    else:
        rows = [(pkg.name, pkg.url, pkg.revision or "", pkg.subdirectory or "") for pkg in packages]
    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 _git_needed_reason(cfg: EffectiveConfig, catalog: Catalog | None) -> str | None:
    if any(src.type is SourceType.GIT for src in cfg.sources):
        return "Git is required because a configured source.type is git (catalog checkout)."
    if catalog is None:
        return None
    for pkg in catalog.packages:
        if url_scheme(pkg.url).startswith("git"):
            return f"Git is required because package {pkg.name!r} uses a git URL."
    return None


@app.command()
def doctor() -> None:
    """Report prerequisites. Read-only: does not clone or refresh the cache."""
    try:
        cwd = Path.cwd()
        cfg = load_effective_config(cwd=cwd)
        catalog = None
        if cfg.source.type is SourceType.FILE:
            catalog = load_catalog(local_catalog_path(cfg, cwd=cwd), cfg.policy)
    except LpipError as exc:
        typer.echo(exc.format(), err=True)
        raise typer.Exit(code=1) from None
    git = find_git_executable()
    needed = _git_needed_reason(cfg, catalog)
    if needed and git is None:
        typer.echo(GitNotFoundError().format(), err=True)
        typer.echo(needed, err=True)
        raise typer.Exit(code=1)
    if git is not None:
        typer.echo(f"OK git: {git}")
    else:
        typer.echo("OK git: not required")
    if cfg.config_path is not None:
        typer.echo(f"OK config: {cfg.config_path}")
    else:
        typer.echo("OK config: defaults (no persistent file)")
    typer.echo(f"OK python: {cfg.runtime.python}")


@app.command()
def validate(
    strict: bool = typer.Option(
        False,
        "--strict",
        help="Fail when a package name is defined in more than one source.",
    ),
) -> None:
    """Validate effective config and catalog sources."""
    try:
        cwd = Path.cwd()
        cfg = load_effective_config(cwd=cwd)
        catalog, clashes = load_merged_catalog(cfg, cwd=cwd)
    except LpipError as exc:
        typer.echo(exc.format(), err=True)
        raise typer.Exit(code=1) from None
    typer.echo(f"OK {catalog.path} ({len(catalog.packages)} packages)")
    for clash in clashes:
        kind = "same definition" if clash.identical else "different definition"
        typer.echo(
            f"warning: package {clash.name!r} in source {clash.shadowed_source!r} "
            f"is shadowed by {clash.winner_source!r} ({kind})",
            err=True,
        )
    if strict and clashes:
        typer.echo("error: package name clashes are not allowed with --strict", err=True)
        raise typer.Exit(code=1)


def _install_requirement(
    python: str,
    requirement: str,
    *,
    dry_run: bool,
    upgrade: bool,
    pipx: bool,
) -> int:
    if pipx:
        exe = str(require_pipx())
        if dry_run:
            typer.echo(format_pipx_install_command(exe, requirement))
            return 0
        return run_pipx_install(exe, requirement)
    if dry_run:
        typer.echo(format_pip_install_command(python, requirement, upgrade=upgrade))
        return 0
    return run_pip_install(python, requirement, upgrade=upgrade)


def _run_install(
    package: str | None,
    requirements: Path | None,
    *,
    dry_run: bool,
    catalog_only: bool,
    upgrade: bool,
    verb: str,
    revision: str | None,
    pipx: bool,
) -> None:
    try:
        if package and requirements is not None:
            raise InstallUsageError(
                "Pass a package name or -r FILE, not both.",
                hint=f"Use lpip {verb} libfoo, or lpip {verb} -r lpip-requirements.txt.",
            )
        if catalog_only and requirements is None:
            raise InstallUsageError(
                f"--catalog-only applies only to lpip {verb} -r.",
                hint="Omit --catalog-only, or pass -r FILE.",
            )
        if pipx and requirements is not None:
            raise InstallUsageError(
                "--pipx cannot be used with -r.",
                hint=f"Install one catalog CLI: lpip {verb} mycli --pipx "
                f"(or lpipx {verb} mycli).",
            )
        if revision is not None and requirements is not None:
            raise InstallUsageError(
                "--revision cannot be used with -r.",
                hint=f"Install one catalog name: lpip {verb} libfoo --revision <ref>.",
            )
        if revision is not None and not revision.strip():
            raise InstallUsageError(
                "--revision requires a Git ref (branch, tag, or SHA).",
                hint=f"Example: lpip {verb} libfoo --revision abc1234",
            )
        if package is None and requirements is None:
            raise InstallUsageError(
                "Pass a catalog package name or -r FILE.",
                hint=f"Example: lpip {verb} libfoo  or  lpip {verb} -r lpip-requirements.txt.",
            )
        cwd = Path.cwd()
        cfg = load_effective_config(cwd=cwd)
        catalog = load_catalog_for_config(cfg, cwd=cwd)
        python = cfg.runtime.python
        if requirements is not None:
            last_code = 0
            for line in load_requirement_lines(requirements):
                name = requirement_name(line)
                entry = catalog.find(name)
                if entry is not None:
                    req = render_catalog_install(entry, line)
                elif catalog_only:
                    raise UnknownPackageError(name, catalog_path=catalog.path)
                else:
                    req = line
                last_code = _install_requirement(
                    python, req, dry_run=dry_run, upgrade=upgrade, pipx=False
                )
                if last_code != 0:
                    raise typer.Exit(code=last_code)
            return
        if package is None:
            raise InstallUsageError(
                "Pass a catalog package name or -r FILE.",
                hint=f"Example: lpip {verb} libfoo  or  lpip {verb} -r lpip-requirements.txt.",
            )
        name = requirement_name(package)
        entry = catalog.find(name)
        if entry is None:
            raise UnknownPackageError(name)
        last_code = _install_requirement(
            python,
            render_catalog_install(
                entry,
                package,
                revision=revision.strip() if revision is not None else None,
            ),
            dry_run=dry_run,
            upgrade=upgrade,
            pipx=pipx,
        )
    except LpipError as exc:
        typer.echo(exc.format(), err=True)
        raise typer.Exit(code=1) from None
    if last_code != 0:
        raise typer.Exit(code=last_code)


@app.command()
def install(
    ctx: typer.Context,
    package: str | None = typer.Argument(None, help="Catalog package name."),
    requirements: Path | None = typer.Option(
        None,
        "-r",
        "--requirement",
        help="Pip requirements file (conventional name: lpip-requirements.txt).",
    ),
    dry_run: bool = typer.Option(False, "--dry-run", help="Print the pip command; do not run pip."),
    catalog_only: bool = typer.Option(
        False,
        "--catalog-only",
        help="With -r, fail if a name is not in the catalog (no pip fallback).",
    ),
    upgrade: bool = typer.Option(
        False,
        "--upgrade",
        "-U",
        help="Pass pip --upgrade (same as lpip upgrade).",
    ),
    revision: str | None = typer.Option(
        None,
        "--revision",
        help="Git ref for this install only (branch, tag, or SHA). Does not write the catalog.",
    ),
    pipx: bool = typer.Option(
        False,
        "--pipx",
        help="Install with pipx (isolated app on PATH). Implied when invoked as lpipx.",
    ),
) -> None:
    """Resolve a package or a requirements file and run ``python -m pip install``."""
    use_pipx = pipx or bool((ctx.obj or {}).get("pipx_default"))
    _run_install(
        package,
        requirements,
        dry_run=dry_run,
        catalog_only=catalog_only,
        upgrade=upgrade,
        verb="install",
        revision=revision,
        pipx=use_pipx,
    )


@app.command()
def upgrade(
    ctx: typer.Context,
    package: str | None = typer.Argument(None, help="Catalog package name."),
    requirements: Path | None = typer.Option(
        None,
        "-r",
        "--requirement",
        help="Pip requirements file (conventional name: lpip-requirements.txt).",
    ),
    dry_run: bool = typer.Option(False, "--dry-run", help="Print the pip command; do not run pip."),
    catalog_only: bool = typer.Option(
        False,
        "--catalog-only",
        help="With -r, fail if a name is not in the catalog (no pip fallback).",
    ),
    revision: str | None = typer.Option(
        None,
        "--revision",
        help="Git ref for this install only (branch, tag, or SHA). Does not write the catalog.",
    ),
    pipx: bool = typer.Option(
        False,
        "--pipx",
        help="Install with pipx (isolated app on PATH). Implied when invoked as lpipx.",
    ),
) -> None:
    """Same as ``lpip install --upgrade``."""
    use_pipx = pipx or bool((ctx.obj or {}).get("pipx_default"))
    _run_install(
        package,
        requirements,
        dry_run=dry_run,
        catalog_only=catalog_only,
        upgrade=True,
        verb="upgrade",
        revision=revision,
        pipx=use_pipx,
    )


@app.command("list")
def list_packages() -> None:
    """Print catalog packages as a name/url/revision/subdirectory table."""
    try:
        catalog = _load_catalog()
    except LpipError as exc:
        typer.echo(exc.format(), err=True)
        raise typer.Exit(code=1) from None
    typer.echo(format_list_table(catalog.sorted_by_name()))


@app.command()
def show(package: str = typer.Argument(..., help="Catalog package name.")) -> None:
    """Print one catalog entry and its rendered pip requirement."""
    try:
        catalog = _load_catalog()
        entry = catalog.get(package)
        rendered = render_requirement(entry)
    except LpipError as exc:
        typer.echo(exc.format(), err=True)
        raise typer.Exit(code=1) from None
    typer.echo(f"name: {entry.name}")
    if entry.catalog_source:
        typer.echo(f"source: {entry.catalog_source}")
    typer.echo(f"url: {entry.url}")
    typer.echo(f"revision: {entry.revision or ''}")
    typer.echo(f"subdirectory: {entry.subdirectory or ''}")
    typer.echo(f"requirement: {rendered.text}")


def _run_versions(package: str, *, pre: bool, all_tags: bool) -> None:
    try:
        catalog = _load_catalog()
        entry = catalog.get(package)
        report = list_package_versions(
            entry,
            include_prereleases=pre,
            include_other=all_tags,
        )
    except LpipError as exc:
        typer.echo(exc.format(), err=True)
        raise typer.Exit(code=1) from None
    typer.echo(format_versions_report(report))


@app.command("version")
def version() -> None:
    """Print the lpip version and exit."""
    typer.echo(format_cli_version())


@app.command("versions")
def versions(
    package: str = typer.Argument(..., help="Catalog package name."),
    pre: bool = typer.Option(False, "--pre", help="Include pre-release versions."),
    all_tags: bool = typer.Option(
        False, "--all", help="Also list tags that are not PEP 440 versions."
    ),
) -> None:
    """List PEP 440 versions from Git tags (no clone)."""
    _run_versions(package, pre=pre, all_tags=all_tags)


@index_app.command("versions")
def index_versions(
    package: str = typer.Argument(..., help="Catalog package name."),
    pre: bool = typer.Option(False, "--pre", help="Include pre-release versions."),
    all_tags: bool = typer.Option(
        False, "--all", help="Also list tags that are not PEP 440 versions."
    ),
) -> None:
    """Same as lpip versions (pip-compatible spelling)."""
    _run_versions(package, pre=pre, all_tags=all_tags)


@app.command("export-requirements")
def export_requirements() -> None:
    """Print pip requirements for every catalog package."""
    try:
        catalog = _load_catalog()
    except LpipError as exc:
        typer.echo(exc.format(), err=True)
        raise typer.Exit(code=1) from None
    for pkg in catalog.sorted_by_name():
        typer.echo(render_requirement(pkg).text)


@config_app.command("init")
def config_init() -> None:
    """Write a commented v1 config.toml if the target path does not exist."""
    try:
        target = resolve_init_target(cwd=Path.cwd())
        write_init_template(target)
    except LpipError as exc:
        typer.echo(exc.format(), err=True)
        raise typer.Exit(code=1) from None
    typer.echo(str(target))


@config_app.command("show")
def config_show() -> None:
    """Print the effective configuration."""
    try:
        cfg = load_effective_config(cwd=Path.cwd())
    except LpipError as exc:
        typer.echo(exc.format(), err=True)
        raise typer.Exit(code=1) from None
    typer.echo(format_effective_config(cfg))


@config_app.command("get")
def config_get(
    key: str = typer.Argument(..., help="Dotted v1 key, for example source.path."),
) -> None:
    """Print one effective configuration value."""
    try:
        cfg = load_effective_config(cwd=Path.cwd())
        value = format_config_value(cfg, key)
    except LpipError as exc:
        typer.echo(exc.format(), err=True)
        raise typer.Exit(code=1) from None
    typer.echo(value)


@config_app.command("set")
def config_set(
    key: str = typer.Argument(..., help="Dotted v1 key, for example source.path."),
    value: str = typer.Argument(..., help="New value (TOML array syntax for lists)."),
) -> None:
    """Set a key in the persistent config file, keeping comments."""
    try:
        path = set_config_key(key, value, cwd=Path.cwd())
    except LpipError as exc:
        typer.echo(exc.format(), err=True)
        raise typer.Exit(code=1) from None
    typer.echo(str(path))


@config_app.command("unset")
def config_unset(
    key: str = typer.Argument(..., help="Dotted v1 key, for example runtime.python."),
) -> None:
    """Remove a key from the persistent config file, keeping comments."""
    try:
        path = unset_config_key(key, cwd=Path.cwd())
    except LpipError as exc:
        typer.echo(exc.format(), err=True)
        raise typer.Exit(code=1) from None
    typer.echo(str(path))


def _blank_to_none(value: str | None) -> str | None:
    if value is None:
        return None
    stripped = value.strip()
    return stripped or None


@catalog_app.command("init")
def catalog_init(
    path: str | None = typer.Option(
        None,
        "--path",
        help="Catalog file to create (default: lpip-sources.toml in the current directory).",
    ),
) -> None:
    """Write a commented empty catalog in this working tree (does not commit)."""
    try:
        target = resolve_authoring_catalog_path(path, cwd=Path.cwd())
        write_catalog_init_template(target)
    except LpipError as exc:
        typer.echo(exc.format(), err=True)
        raise typer.Exit(code=1) from None
    typer.echo(str(target))


@catalog_app.command("add")
def catalog_add(
    package: str | None = typer.Argument(
        None, help="Catalog package name (pip distribution name)."
    ),
    url: str | None = typer.Option(
        None,
        "--url",
        help="Git URL: ssh://, https://, git@host:path, git+ssh://, or git+https://.",
    ),
    revision: str | None = typer.Option(None, "--revision", help="Branch, tag, or SHA."),
    subdirectory: str | None = typer.Option(
        None,
        "--subdirectory",
        help="Path of the Python project inside the repository.",
    ),
    path: str | None = typer.Option(
        None,
        "--path",
        help="Catalog file to edit (default: lpip-sources.toml in the current directory).",
    ),
    force: bool = typer.Option(
        False, "--force", help="Replace an existing entry with the same name."
    ),
    non_interactive: bool = typer.Option(
        False,
        "--non-interactive",
        help="Do not prompt; require a name and --url.",
    ),
) -> None:
    """Add a package table to a catalog file in this working tree."""
    try:
        name = _blank_to_none(package)
        pkg_url = _blank_to_none(url)
        if non_interactive:
            if name is None or pkg_url is None:
                raise MissingCatalogAddFieldsError()
            rev = _blank_to_none(revision)
            sub = _blank_to_none(subdirectory)
        elif name is not None and pkg_url is not None:
            rev = _blank_to_none(revision)
            sub = _blank_to_none(subdirectory)
        else:
            if name is None:
                name = _blank_to_none(typer.prompt("Package name"))
            if pkg_url is None:
                pkg_url = _blank_to_none(
                    typer.prompt("Git URL (ssh://, https://, or git@host:path)")
                )
            if name is None or pkg_url is None:
                raise MissingCatalogAddFieldsError()
            if revision is None:
                revision = typer.prompt("Revision (branch, tag, or SHA)", default="")
            if subdirectory is None:
                subdirectory = typer.prompt(
                    "Subdirectory (empty if the project is at the repo root)",
                    default="",
                )
            rev = _blank_to_none(revision)
            sub = _blank_to_none(subdirectory)
        cwd = Path.cwd()
        cfg = load_effective_config(cwd=cwd)
        written = add_package_to_catalog_file(
            resolve_authoring_catalog_path(path, cwd=cwd),
            PackageSource(name=name, url=pkg_url, revision=rev, subdirectory=sub),
            policy=cfg.policy,
            force=force,
        )
    except LpipError as exc:
        typer.echo(exc.format(), err=True)
        raise typer.Exit(code=1) from None
    typer.echo(str(written))


@catalog_app.command("refresh")
def catalog_refresh() -> None:
    """Clone or fetch every Git catalog and confirm catalog files."""
    try:
        cwd = Path.cwd()
        cfg = load_effective_config(cwd=cwd)
        if git_sources(cfg):
            for src in git_sources(cfg):
                location = resolve_source_location(src, cwd=cwd, force_refresh=True)
                if location.cache is not None:
                    typer.echo(str(location.cache.root))
                typer.echo(str(location.catalog_file))
        else:
            location = resolve_catalog_location(cfg, cwd=cwd, force_refresh=True)
            typer.echo(str(location.catalog_file))
    except LpipError as exc:
        typer.echo(exc.format(), err=True)
        raise typer.Exit(code=1) from None


@catalog_app.command("path")
def catalog_path() -> None:
    """Print cache and catalog file paths without fetching."""
    try:
        cwd = Path.cwd()
        cfg = load_effective_config(cwd=cwd)
        if git_sources(cfg):
            for src in git_sources(cfg):
                cache = planned_git_cache_paths_for(src)
                typer.echo(str(cache.root))
                typer.echo(str(cache.repo / src.path))
        else:
            location = resolve_catalog_location(cfg, cwd=cwd)
            typer.echo(str(location.catalog_file))
    except LpipError as exc:
        typer.echo(exc.format(), err=True)
        raise typer.Exit(code=1) from None


@catalog_app.command("purge")
def catalog_purge() -> None:
    """Delete cached checkouts for every configured Git catalog."""
    try:
        cwd = Path.cwd()
        cfg = load_effective_config(cwd=cwd)
        for cache in purge_all_git_catalog_caches(cfg):
            typer.echo(str(cache.root))
    except LpipError as exc:
        typer.echo(exc.format(), err=True)
        raise typer.Exit(code=1) from None


@source_app.command("list")
def source_list() -> None:
    """List configured catalog sources in lookup order."""
    try:
        cfg = load_effective_config(cwd=Path.cwd())
    except LpipError as exc:
        typer.echo(exc.format(), err=True)
        raise typer.Exit(code=1) from None
    typer.echo(format_sources_table(cfg.sources))


@source_app.command("add")
def source_add(
    name: str = typer.Argument(..., help="Source name (first-wins order is file order)."),
    source_type: SourceType = typer.Option(..., "--type", help="file or git."),
    path: str = typer.Option(
        "lpip-sources.toml",
        "--path",
        help="Local catalog file, or path inside a Git catalog repo.",
    ),
    url: str | None = typer.Option(None, "--url", help="Catalog Git URL when --type git."),
    revision: str | None = typer.Option(None, "--revision", help="Catalog Git revision."),
    refresh: str | None = typer.Option(
        None, "--refresh", help="always, auto, or never (git sources)."
    ),
) -> None:
    """Register a catalog in persistent config ([[sources]])."""
    try:
        written = add_configured_source(
            name,
            source_type=source_type,
            path=path,
            url=url,
            revision=revision,
            refresh=refresh,
            cwd=Path.cwd(),
        )
    except LpipError as exc:
        typer.echo(exc.format(), err=True)
        raise typer.Exit(code=1) from None
    typer.echo(str(written))


@source_app.command("remove")
def source_remove(
    name: str = typer.Argument(..., help="Source name to drop."),
) -> None:
    """Remove a catalog source from persistent config."""
    try:
        written = remove_configured_source(name, cwd=Path.cwd())
    except LpipError as exc:
        typer.echo(exc.format(), err=True)
        raise typer.Exit(code=1) from None
    typer.echo(str(written))


def main() -> None:
    app()