untaped-git 11.0.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.
@@ -0,0 +1,76 @@
1
+ """Git plugin for the unified ``untaped`` shell: Git host credentials and the repo store."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Sequence
6
+ from importlib.resources import files
7
+ from pathlib import Path
8
+ from typing import TYPE_CHECKING
9
+
10
+ from untaped.sdk import (
11
+ DoctorCheck,
12
+ DoctorResult,
13
+ PluginContext,
14
+ PluginSpec,
15
+ SkillAsset,
16
+ )
17
+ from untaped_git.settings import GitSettings
18
+
19
+ if TYPE_CHECKING:
20
+ from cyclopts import App
21
+
22
+ from untaped.contracts import Contract
23
+
24
+ __all__ = ["SPEC", "build_app"]
25
+
26
+
27
+ def build_app() -> App:
28
+ """Nullary factory returning the git cyclopts app."""
29
+ from untaped_git.cli import app # noqa: PLC0415
30
+
31
+ return app
32
+
33
+
34
+ def _contracts() -> Sequence[type[Contract]]:
35
+ from untaped_git.domain.hosts import GitHost # noqa: PLC0415
36
+
37
+ return (GitHost,)
38
+
39
+
40
+ def _git_version(ctx: PluginContext) -> DoctorResult:
41
+ from untaped_git.doctor import version_check # noqa: PLC0415 # keeps startup light
42
+
43
+ return version_check(ctx)
44
+
45
+
46
+ def _git_store(ctx: PluginContext) -> DoctorResult:
47
+ from untaped_git.doctor import store_check # noqa: PLC0415 # keeps startup light
48
+
49
+ return store_check(ctx)
50
+
51
+
52
+ SPEC = PluginSpec(
53
+ name="git",
54
+ app_factory=build_app,
55
+ help="Credentials for Git hosts, and the repo store other plugins keep repositories in.",
56
+ settings=GitSettings,
57
+ skills=(
58
+ SkillAsset(
59
+ name="untaped-git",
60
+ source=Path(str(files("untaped_git").joinpath("skills", "untaped-git"))),
61
+ description=(
62
+ "Explains untaped's Git plumbing through the `untaped git` command (which "
63
+ "plugin supplies credentials for a Git host with `git hosts`, the credential "
64
+ "helper untaped writes into its worktrees, and the repo store other plugins "
65
+ "keep repositories in). Use when a Git fetch or push in an untaped worktree "
66
+ "asks for credentials or fails to authenticate, or when the user asks where "
67
+ "untaped keeps repositories or which Git version it needs."
68
+ ),
69
+ ),
70
+ ),
71
+ doctor_checks=(
72
+ DoctorCheck(id="git.version", title="git version", run=_git_version),
73
+ DoctorCheck(id="git.store", title="git store", run=_git_store),
74
+ ),
75
+ contracts=_contracts,
76
+ )
untaped_git/api.py ADDED
@@ -0,0 +1,102 @@
1
+ """The git plugin's declared public module: the only untaped_git code other plugins import.
2
+
3
+ ``RepoStore`` is the repo store (one blobless, full-history bare repo per URL,
4
+ shared by plugins, each in its own ref namespace); ``GitHost`` is the
5
+ contract a forge plugin fills to supply credentials and a proxy for its host;
6
+ ``ls_remote`` and ``default_branch`` query a remote with those credentials;
7
+ ``check_names`` says why a branch or tag name is one the store refuses.
8
+ ``adopt`` moves a repository an older untaped version left into the store
9
+ (``setup migrate-dirs`` rows call it).
10
+ The closed :data:`__all__` keeps the boundary explicit.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import os
16
+ from collections.abc import Collection, Sequence
17
+ from pathlib import Path
18
+
19
+ from untaped_git.domain.delta import RefDelta, RefMove
20
+ from untaped_git.domain.hosts import Credential, GitHost, HostAuth, resolve_host
21
+ from untaped_git.domain.namespace import check_names
22
+ from untaped_git.domain.records import TreeEntry
23
+ from untaped_git.domain.release import Released, Removed
24
+ from untaped_git.domain.url import GitUrl, repo_url_parts, store_key, validate_git_url
25
+ from untaped_git.infrastructure import remote
26
+ from untaped_git.infrastructure.adopt import Adopted, adopt, remove_if_emptied, unfinished_removals
27
+ from untaped_git.infrastructure.repo_files import config_value, list_repos, repo_origin
28
+ from untaped_git.infrastructure.store import Prefetched, RepoStore
29
+ from untaped_git.settings import store_root
30
+
31
+ __all__ = [
32
+ "Adopted",
33
+ "Credential",
34
+ "GitHost",
35
+ "GitUrl",
36
+ "HostAuth",
37
+ "Prefetched",
38
+ "RefDelta",
39
+ "RefMove",
40
+ "Released",
41
+ "Removed",
42
+ "RepoStore",
43
+ "TreeEntry",
44
+ "adopt",
45
+ "bare_repos",
46
+ "check_names",
47
+ "default_branch",
48
+ "ls_remote",
49
+ "overlaps_store",
50
+ "remove_if_emptied",
51
+ "repo_origin",
52
+ "repo_url_parts",
53
+ "store_key",
54
+ "store_root",
55
+ "unfinished_removals",
56
+ "validate_git_url",
57
+ ]
58
+
59
+
60
+ def ls_remote(url: str, patterns: Sequence[str] = ()) -> dict[str, str]:
61
+ """``ref → commit oid`` of ``url``'s refs matching ``patterns``, with untaped's credentials.
62
+
63
+ ``HEAD`` included (with no patterns, or when one asks for it); an annotated
64
+ tag maps to its commit.
65
+ """
66
+ return remote.ls_remote(url, patterns, root=store_root(), auth=resolve_host)
67
+
68
+
69
+ def default_branch(url: str) -> str | None:
70
+ """The branch ``url``'s ``HEAD`` points at, or ``None`` (``ls-remote --symref``)."""
71
+ return remote.default_branch(url, root=store_root(), auth=resolve_host)
72
+
73
+
74
+ def overlaps_store(path: Path) -> bool:
75
+ """Whether ``path`` is the repo store's directory, lies inside it or holds it.
76
+
77
+ An older version's directory that does is never moved or deleted whole:
78
+ a custom root configured to the same place as ``git.store_dir``.
79
+ """
80
+ real, root = Path(os.path.realpath(path.expanduser())), Path(os.path.realpath(store_root()))
81
+ return real == root or real.is_relative_to(root) or root.is_relative_to(real)
82
+
83
+
84
+ def bare_repos(
85
+ root: Path, *, skip: Collection[str] = (), workspace_layout: bool | None = None
86
+ ) -> list[Path]:
87
+ """Every ``*.git`` directory under ``root``, sorted, without running git.
88
+
89
+ For an older version's cache root, before :func:`adopt`: never descends
90
+ into a repository, skips symlinks and, at the top level, hidden
91
+ directories and the names in ``skip``. ``workspace_layout`` keeps only the
92
+ repos 10.x workspace marked ``untaped.layout`` (``True``) or only the
93
+ others (``False``).
94
+ """
95
+ repos = list_repos(root, skip=skip)
96
+ if workspace_layout is None:
97
+ return repos
98
+ return [
99
+ repo
100
+ for repo in repos
101
+ if bool(config_value(repo / "config", "untaped", "layout")) is workspace_layout
102
+ ]
@@ -0,0 +1 @@
1
+ """Git plugin use cases: the host listing behind ``untaped git hosts``."""
@@ -0,0 +1,49 @@
1
+ """The host listing behind ``untaped git hosts``: who supplies credentials where."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Callable
6
+
7
+ from untaped.contracts import Ok, gather
8
+ from untaped.sdk import ConfigError
9
+ from untaped_git.domain.hosts import GitHost
10
+ from untaped_git.domain.records import GitHostRecord
11
+
12
+
13
+ def list_hosts(
14
+ *, helpers_for: Callable[[str], list[str]], missing_helper: str | None
15
+ ) -> list[GitHostRecord]:
16
+ """One row per host a ``GitHost`` provider names, sorted by host.
17
+
18
+ A host two providers name lists both (the rank decides between them);
19
+ ``credential`` says whether any of them has one for the host's root URL.
20
+ ``helpers_for`` names the user's own credential helpers git asks first for a host.
21
+ """
22
+ try:
23
+ homes = gather(GitHost.home)()
24
+ except ConfigError: # no provider is ready
25
+ return []
26
+ plugins: dict[str, list[str]] = {}
27
+ for answer in homes:
28
+ if isinstance(answer, Ok) and isinstance(answer.value, str) and answer.value:
29
+ plugins.setdefault(answer.value.lower(), []).append(answer.plugin)
30
+ rows = []
31
+ for host, names in sorted(plugins.items()):
32
+ rows.append(
33
+ GitHostRecord(
34
+ host=host,
35
+ plugins=names,
36
+ credential=_has_credential(f"https://{host}/", names),
37
+ helpers_first=helpers_for(host),
38
+ missing_helper=missing_helper,
39
+ )
40
+ )
41
+ return rows
42
+
43
+
44
+ def _has_credential(url: str, plugins: list[str]) -> bool:
45
+ try:
46
+ answers = gather(GitHost.credential, plugins=plugins)(url)
47
+ except ConfigError:
48
+ return False
49
+ return any(isinstance(answer, Ok) and answer.value is not None for answer in answers)
@@ -0,0 +1,5 @@
1
+ """The ``untaped git`` command subtree."""
2
+
3
+ from untaped_git.cli.commands import app
4
+
5
+ __all__ = ["app"]
@@ -0,0 +1,119 @@
1
+ """Git command tree: ``credential`` (git's helper protocol), ``hosts`` and ``store``."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from pathlib import Path
6
+ from typing import Annotated, Literal
7
+
8
+ from cyclopts import Parameter
9
+
10
+ from untaped.sdk import (
11
+ ColumnsOption,
12
+ FormatOption,
13
+ create_app,
14
+ echo,
15
+ emit,
16
+ read_stdin,
17
+ report_errors,
18
+ )
19
+ from untaped_git.settings import git_settings, store_root
20
+
21
+ app = create_app(
22
+ name="git",
23
+ help="Credentials for Git hosts, and the repo store other plugins keep repositories in.",
24
+ )
25
+
26
+ HOST = "git.host"
27
+ STORE = "git.store"
28
+
29
+
30
+ @app.command(name="credential")
31
+ def credential_command(
32
+ action: Annotated[
33
+ Literal["get", "store", "erase"],
34
+ Parameter(help="The credential helper action git asks for."),
35
+ ],
36
+ /,
37
+ ) -> None:
38
+ """Answer Git's credential requests from the plugins that know the host.
39
+
40
+ Git runs this as a credential helper (untaped writes it into its own
41
+ worktrees): it reads `protocol`, `host` and `path` on stdin and prints a
42
+ username and password when a plugin supplies them for that URL. `store`
43
+ and `erase` do nothing: untaped's credentials live in its own settings.
44
+ """
45
+ from untaped_git.domain.hosts import resolve_host # noqa: PLC0415
46
+
47
+ with report_errors():
48
+ if action != "get":
49
+ return
50
+ fields = _read_fields()
51
+ protocol, host = fields.get("protocol"), fields.get("host")
52
+ if protocol != "https" or not host:
53
+ return
54
+ auth = resolve_host(f"https://{host}/{fields.get('path', '')}")
55
+ if auth is None or auth.credential is None:
56
+ return
57
+ echo(f"username={auth.credential.username}")
58
+ echo(f"password={auth.credential.password.get_secret_value()}")
59
+
60
+
61
+ @app.command(name="hosts")
62
+ def hosts_command(*, fmt: FormatOption = "table", columns: ColumnsOption = None) -> None:
63
+ """List the Git hosts plugins supply credentials for.
64
+
65
+ Each row names the plugins that claim the host, whether a credential is
66
+ available, the credential helpers your own git config asks before
67
+ untaped's in its worktrees, and an untaped helper path that no longer
68
+ exists.
69
+ """
70
+ from untaped_git.application.hosts import list_hosts # noqa: PLC0415
71
+ from untaped_git.infrastructure.helpers import missing_helper, user_helpers # noqa: PLC0415
72
+
73
+ with report_errors():
74
+ root = store_root()
75
+ cwd = root if root.is_dir() else Path(root.anchor)
76
+ rows = list_hosts(
77
+ # With untaped's helper only, its worktrees reset the user's helpers away.
78
+ helpers_for=lambda host: (
79
+ [] if git_settings().untaped_helper_only else user_helpers(host, cwd=cwd)
80
+ ),
81
+ missing_helper=missing_helper(root),
82
+ )
83
+ emit(rows, fmt=fmt, columns=columns, kind=HOST)
84
+
85
+
86
+ @app.command(name="store")
87
+ def store_command(*, fmt: FormatOption = "table", columns: ColumnsOption = None) -> None:
88
+ """Report what the repo store holds and costs, read from disk alone.
89
+
90
+ Shows the repos, their size, which plugins use them and the size of the
91
+ repos only one plugin uses (what releasing them would free), repos an
92
+ interrupted release left (finished on their next use) or that only a
93
+ branch or stash keeps, pack counts, hosts that ignore the partial-clone
94
+ filter, and repos where git paused automatic maintenance.
95
+ """
96
+ from untaped_git.cli.store_view import report_lines # noqa: PLC0415
97
+ from untaped_git.infrastructure.report import store_report # noqa: PLC0415
98
+ from untaped_git.infrastructure.version import git_version, version_text # noqa: PLC0415
99
+
100
+ with report_errors():
101
+ version = git_version()
102
+ report = store_report(
103
+ store_root(),
104
+ version=None if version is None else version_text(version),
105
+ )
106
+ if fmt == "table" and columns is None:
107
+ for line in report_lines(report):
108
+ echo(line)
109
+ return
110
+ emit(report, fmt=fmt, columns=columns, kind=STORE)
111
+
112
+
113
+ def _read_fields() -> dict[str, str]:
114
+ fields: dict[str, str] = {}
115
+ for line in read_stdin():
116
+ key, sep, value = line.partition("=")
117
+ if sep:
118
+ fields[key] = value
119
+ return fields
@@ -0,0 +1,68 @@
1
+ """How ``untaped git store`` prints the store report in table format."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Callable
6
+
7
+ from untaped.sdk import plural, shown_path, size_text
8
+ from untaped_git.domain.records import RepoCount, StoreReport
9
+
10
+
11
+ def report_lines(report: StoreReport) -> list[str]:
12
+ """The report as ``untaped git store`` prints it in table format: one labelled line each.
13
+
14
+ A line shows only when it has something to say.
15
+ """
16
+ rows = [("store", _store_line(report))]
17
+ if report.used_by:
18
+ rows.append(("used by", _joined(report.used_by, lambda count: f"{count:,}")))
19
+ if report.exclusive_bytes:
20
+ rows.append(("exclusive", _joined(report.exclusive_bytes, size_text)))
21
+ if report.unowned.repos:
22
+ rows.append(
23
+ (
24
+ "unowned",
25
+ f"{_repos_text(report.unowned)} (interrupted release; finished on next use)",
26
+ )
27
+ )
28
+ if report.held_by_branches.repos:
29
+ rows.append(
30
+ (
31
+ "held by branches",
32
+ f"{_repos_text(report.held_by_branches)} "
33
+ "(only a branch or stash a release left keeps them)",
34
+ )
35
+ )
36
+ if report.repos:
37
+ rows.append(
38
+ (
39
+ "packs",
40
+ f"median {report.packs_median:g} · max {report.packs_max} · "
41
+ f"loose objects {report.loose_objects:,}",
42
+ )
43
+ )
44
+ for host, count in report.filter_ignored.items():
45
+ rows.append(("filter", f"ignored on {host}: {plural(count, 'repo')} hold every blob"))
46
+ if report.gc_log:
47
+ rows.append(("gc.log", f"{plural(len(report.gc_log), 'repo')} (auto maintenance paused)"))
48
+ width = max(len(label) for label, _ in rows)
49
+ return [f"{label:<{width}} {text}" for label, text in rows]
50
+
51
+
52
+ def _store_line(report: StoreReport) -> str:
53
+ parts = [
54
+ shown_path(report.store_dir),
55
+ f"{report.repos:,} {'repo' if report.repos == 1 else 'repos'}",
56
+ size_text(report.size_bytes),
57
+ ]
58
+ if report.git_version:
59
+ parts.append(f"git {report.git_version}")
60
+ return " ".join(parts)
61
+
62
+
63
+ def _repos_text(count: RepoCount) -> str:
64
+ return f"{plural(count.repos, 'repo')}, {size_text(count.size_bytes)}"
65
+
66
+
67
+ def _joined(values: dict[str, int], shown: Callable[[int], str]) -> str:
68
+ return " · ".join(f"{name} {shown(value)}" for name, value in values.items())
untaped_git/doctor.py ADDED
@@ -0,0 +1,65 @@
1
+ """The git plugin's doctor rows: is git new enough for the repo store, and is the store well."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import shutil
6
+
7
+ from untaped.sdk import DoctorResult, PluginContext, plural, size_text
8
+ from untaped_git.infrastructure.version import below_floor, floor_text, git_version, version_text
9
+
10
+ _ID = "git.version"
11
+
12
+
13
+ def version_check(_ctx: PluginContext) -> DoctorResult:
14
+ """``git.version``: fails below the repo store's floor, warns when git is missing."""
15
+ if shutil.which("git") is None:
16
+ return DoctorResult(
17
+ id=_ID, ok=True, warn=True, detail="`git` not found on PATH; the repo store will fail"
18
+ )
19
+ version = git_version()
20
+ if version is None:
21
+ return DoctorResult(id=_ID, ok=True, warn=True, detail="could not read `git --version`")
22
+ if below_floor(version):
23
+ return DoctorResult(
24
+ id=_ID,
25
+ ok=False,
26
+ detail=(
27
+ f"git {version_text(version)} is older than {floor_text()}, which the repo "
28
+ f"store needs; install git {floor_text()} or newer"
29
+ ),
30
+ )
31
+ return DoctorResult(
32
+ id=_ID, ok=True, detail=f"git {version_text(version)} (floor {floor_text()})"
33
+ )
34
+
35
+
36
+ def store_check(_ctx: PluginContext) -> DoctorResult:
37
+ """``git.store``: warns about paused maintenance and interrupted releases; never fails.
38
+
39
+ No fix: nothing untaped runs clears a ``gc.log`` (git retries after a
40
+ day), and an interrupted release finishes on the repo's next use.
41
+ """
42
+ from untaped_git.infrastructure.report import store_report # noqa: PLC0415
43
+ from untaped_git.settings import store_root # noqa: PLC0415
44
+
45
+ report = store_report(store_root(), version=None)
46
+ problems = []
47
+ if report.gc_log:
48
+ problems.append(
49
+ f"{plural(len(report.gc_log), 'repo')} with gc.log (auto maintenance paused)"
50
+ )
51
+ if report.unowned.repos:
52
+ problems.append(
53
+ f"{plural(report.unowned.repos, 'unowned repo')} "
54
+ "(an interrupted release; finished on next use)"
55
+ )
56
+ if problems:
57
+ return DoctorResult(id=_STORE_ID, ok=True, warn=True, detail="; ".join(problems))
58
+ return DoctorResult(
59
+ id=_STORE_ID,
60
+ ok=True,
61
+ detail=f"{plural(report.repos, 'repo')}, {size_text(report.size_bytes)}",
62
+ )
63
+
64
+
65
+ _STORE_ID = "git.store"
@@ -0,0 +1,4 @@
1
+ """Git plugin domain: URLs and store keys, ref namespaces, the ref delta, records.
2
+
3
+ Kept free of imports; callers import the submodule they need.
4
+ """
@@ -0,0 +1,54 @@
1
+ """What a fetch changed in the caller's namespace.
2
+
3
+ ``fetch()`` returns a :class:`RefDelta`, computed the same way for every call
4
+ from the namespace's refs before and after it: refs ``added`` (ref → oid),
5
+ ``moved`` (ref → old and new oid) and ``pruned`` (ref → the oid it had), named
6
+ ``heads/<branch>`` and ``tags/<tag>``. A ref git left unchanged is in no list,
7
+ so an empty delta means nothing moved.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ from collections.abc import Mapping
13
+ from dataclasses import dataclass, field
14
+ from types import MappingProxyType
15
+
16
+
17
+ @dataclass(frozen=True, slots=True)
18
+ class RefMove:
19
+ """A ref that moved: the oid it had and the one it has."""
20
+
21
+ old: str
22
+ new: str
23
+
24
+
25
+ def _empty() -> Mapping[str, str]:
26
+ return MappingProxyType({})
27
+
28
+
29
+ @dataclass(frozen=True, slots=True)
30
+ class RefDelta:
31
+ """Refs one fetch added, moved and pruned in the caller's namespace."""
32
+
33
+ added: Mapping[str, str] = field(default_factory=_empty)
34
+ moved: Mapping[str, RefMove] = field(default_factory=lambda: MappingProxyType({}))
35
+ pruned: Mapping[str, str] = field(default_factory=_empty)
36
+
37
+ def __bool__(self) -> bool:
38
+ return bool(self.added or self.moved or self.pruned)
39
+
40
+
41
+ def diff_refs(before: Mapping[str, str], after: Mapping[str, str]) -> RefDelta:
42
+ """The delta between two snapshots of one namespace (ref → oid)."""
43
+ added = {ref: oid for ref, oid in after.items() if ref not in before}
44
+ pruned = {ref: oid for ref, oid in before.items() if ref not in after}
45
+ moved = {
46
+ ref: RefMove(old, after[ref])
47
+ for ref, old in before.items()
48
+ if ref in after and after[ref] != old
49
+ }
50
+ return RefDelta(
51
+ MappingProxyType(dict(sorted(added.items()))),
52
+ MappingProxyType(dict(sorted(moved.items()))),
53
+ MappingProxyType(dict(sorted(pruned.items()))),
54
+ )
@@ -0,0 +1,126 @@
1
+ """The ``GitHost`` contract: which plugin supplies credentials for a Git host.
2
+
3
+ The git plugin owns it; a forge plugin (github, gitlab…) fills it for the
4
+ host its own settings name. :func:`resolve_host` is how untaped picks the
5
+ provider for a URL: the plugins whose ``home()`` is the URL's host are the
6
+ candidates; none means plain git (the user's own git config answers); several
7
+ are decided by their rank for ``credential`` (``git.extensions.git_host``),
8
+ whatever the URL, and an unranked tie is a configuration error (exit 4) naming
9
+ them and the rank command. Only the chosen provider is asked for credentials
10
+ and proxy. Credentials are asked only for ``https://`` URLs, so an ssh
11
+ remote never runs anyone's token command.
12
+
13
+ Core never imports this module: the repo store asks it itself, so consumers
14
+ never see a credential.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ from abc import abstractmethod
20
+ from dataclasses import dataclass
21
+ from typing import Any
22
+
23
+ from pydantic import BaseModel, ConfigDict, SecretStr
24
+
25
+ from untaped.contracts import Answers, Contract, Failed, Ok, gather
26
+ from untaped.sdk import ConfigError, experimental
27
+ from untaped_git.domain.url import url_host
28
+
29
+
30
+ class Credential(BaseModel):
31
+ """A username and password (or token) for one HTTPS remote."""
32
+
33
+ model_config = ConfigDict(frozen=True)
34
+
35
+ username: str
36
+ password: SecretStr
37
+
38
+
39
+ @experimental
40
+ class GitHost(Contract, shell=False):
41
+ """A plugin that knows a Git host: its name, and credentials and proxy for its URLs.
42
+
43
+ untaped asks ``credential`` and ``proxy`` only of the provider it chose for
44
+ the URL's host by ``home()``.
45
+ """
46
+
47
+ @abstractmethod
48
+ def home(self) -> str | None:
49
+ """The host this provider supplies credentials for, from config alone."""
50
+
51
+ @abstractmethod
52
+ def credential(self, url: str) -> Credential | None:
53
+ """Credentials for the full ``url`` (per-organisation tokens), or ``None``."""
54
+
55
+ def proxy(self, url: str) -> str | None:
56
+ """The proxy URL for ``url``, or ``None`` for the user's own git config."""
57
+ raise NotImplementedError
58
+
59
+
60
+ @dataclass(frozen=True, slots=True)
61
+ class HostAuth:
62
+ """The provider chosen for a URL, with its credential (https only) and proxy."""
63
+
64
+ plugin: str
65
+ credential: Credential | None
66
+ proxy: str | None
67
+
68
+
69
+ def resolve_host(url: str) -> HostAuth | None:
70
+ """Choose the ``GitHost`` provider for ``url``; see the module docstring."""
71
+ host = url_host(url)
72
+ if host is None:
73
+ return None
74
+ homes = _ask(GitHost.home)
75
+ if homes is None:
76
+ return None
77
+ candidates = [
78
+ answer.plugin
79
+ for answer in homes
80
+ if isinstance(answer, Ok) and isinstance(answer.value, str) and answer.value.lower() == host
81
+ ]
82
+ if not candidates:
83
+ return None
84
+ chosen = _choose(host, candidates)
85
+ https = url.startswith("https://")
86
+ credentials = _ask(GitHost.credential, url, among=[chosen]) if https else None
87
+ proxies = _ask(GitHost.proxy, url, among=[chosen])
88
+ return HostAuth(chosen, _answer(credentials, chosen), _answer(proxies, chosen))
89
+
90
+
91
+ def _ask(method: Any, *args: str, among: list[str] | None = None) -> Answers[Any] | None:
92
+ try:
93
+ return gather(method, plugins=among)(*args)
94
+ except ConfigError: # no provider is ready: plain git
95
+ return None
96
+
97
+
98
+ def _choose(host: str, candidates: list[str]) -> str:
99
+ """The one candidate, else the first of them ranked for ``credential``, whatever the URL."""
100
+ if len(candidates) == 1:
101
+ return candidates[0]
102
+ from untaped_git.settings import credential_rank # noqa: PLC0415 # the owner's own section
103
+
104
+ for plugin in credential_rank():
105
+ if plugin in candidates:
106
+ return plugin
107
+ named = ", ".join(candidates)
108
+ raise ConfigError(
109
+ f"{named} all supply credentials for {host}; rank them to choose one",
110
+ system="git",
111
+ hint=f"untaped plugin rank git.git_host credential {' '.join(candidates)}",
112
+ details={"contract": "git.git_host", "method": "credential", "providers": candidates},
113
+ )
114
+
115
+
116
+ def _answer[R](answers: Answers[R] | None, plugin: str) -> R | None:
117
+ if answers is None:
118
+ return None
119
+ for answer in answers:
120
+ if answer.plugin != plugin:
121
+ continue
122
+ if isinstance(answer, Failed):
123
+ raise answer.error
124
+ if isinstance(answer, Ok):
125
+ return answer.value
126
+ return None