1"""Resolve this workspace's repository on its forge.
3The workspace contract's ``[forge]`` table names the kind and owner;
4the repository name comes from the ``origin`` remote. Tokens resolve
5through livery.workshop._tokens: ``FORGE_TOKEN`` (host-qualified
6first), and each backend's own documented fallback when neither is
7set. Nothing here is inferred from ambient state beyond those
8documented lookups.
9"""
11from __future__ import annotations
13import re
14from pathlib import Path
16from livery import git
17from livery.footman import fail
18from livery.forge import (
19 Forge,
20 ForgeError,
21 GiteaForge,
22 GithubForge,
23 GitlabForge,
24 PullRequest,
25 Repository,
26)
27from livery.workshop import _stack
28from livery.workshop._contract import load_contract
29from livery.workshop._tokens import admin_token, forge_token, host_qualifier
31# http and https (ports and embedded credentials included), and the
32# git@host:owner/name form: the dev rig speaks plain http on a port.
33_REMOTE_RE = re.compile(
34 r"(?:https?://[^/]+/|git@[^:]+:)(?P<owner>[^/]+)/(?P<name>[^/]+?)(?:\.git)?$"
35)
37#: A URL's user and password, the part a credential rides in before the host.
38_USERINFO_RE = re.compile(r"^(?P<scheme>[a-z][a-z0-9+.-]*://)[^/@]*@", re.IGNORECASE)
41def shown_url(url: str) -> str:
42 """*url* as a message may show it: any user and password replaced by ``***``.
44 A remote's URL can carry a token (``http://oauth2:<token>@host/...``),
45 and a refusal that names the URL is printed, logged and recorded. An
46 ``ssh`` spelling (``git@host:owner/name``) names a user and no secret,
47 and is shown as it is.
48 """
49 return _USERINFO_RE.sub(r"\g<scheme>***@", url)
52def forge_repository(root: Path) -> str:
53 """This workspace's repository name on its forge: the name ``origin`` points at.
55 The remote's URL in either spelling, ``https://host/owner/name`` or
56 ``git@host:owner/name``, with or without ``.git``.
58 Raises:
59 Failed: when *root* has no ``origin`` remote, or its URL names
60 no owner and name.
61 """
62 try:
63 url = git.remote_url(root)
64 except git.GitError as error:
65 fail(f"no origin remote:\n{error}")
66 match = _REMOTE_RE.search(url)
67 if match is None:
68 fail(f"cannot read owner/name from origin url {shown_url(url)!r}")
69 return match.group("name")
72def _connect(kind: str, url: str, token: str | None) -> Forge:
73 """One backend, connected; ``None`` lets its own resolution decide.
75 The one place a workshop verb connects, so a refusal reads the
76 same from every verb: when the lane resolved nothing and the
77 backend found nothing either, the backend's own words (its
78 variable, its CLI) are followed by the workshop's names, so the
79 reader learns both ladders at once.
81 Raises:
82 ForgeError: when the backend cannot connect; a caller that
83 falls open catches it, and a verb lets it stand as the
84 refusal.
85 """
86 try:
87 if kind == "github":
88 return GithubForge.connect(url=url, token=token)
89 if kind == "gitea":
90 return GiteaForge.connect(url=url, token=token)
91 if kind == "gitlab":91 ↛ 99line 91 didn't jump to line 99 because the condition on line 91 was always true
92 return GitlabForge.connect(url=url, token=token)
93 except ForgeError as error:
94 if token is not None or "credential" not in str(error):
95 raise
96 qualifier = host_qualifier(kind, url)
97 names = "FORGE_TOKEN" + (f" or FORGE_TOKEN__{qualifier}" if qualifier else "")
98 raise ForgeError(f"{error}; the workshop reads {names} first") from error
99 fail(f"unknown forge kind {kind!r}: use github, gitea, or gitlab")
102def this_forge(root: Path) -> Forge:
103 """The workspace's forge, per the contract's ``[forge]`` table.
105 The token is ``FORGE_TOKEN`` (host-qualified first); with neither
106 set, the backend's own documented fallback decides.
108 Returns:
109 The connected [livery.forge.Forge][].
110 """
111 contract = load_contract(root / "workshop.toml")
112 forge_table = contract.get("forge") or {}
113 kind = str(forge_table.get("kind", ""))
114 url = str(forge_table.get("url", ""))
115 if not kind:115 ↛ 116line 115 didn't jump to line 116 because the condition on line 115 was never true
116 fail("workshop.toml [forge] must carry kind and owner")
117 token, _ = forge_token(kind, url)
118 return _connect(kind, url, token or None)
121def admin_forge(root: Path) -> tuple[Forge, str]:
122 """The forge for an admin verb, and the variable that armed it.
124 Least privilege by split tokens: the everyday verbs never read
125 the admin name, and the admin verbs (configure, the post-abort
126 reconcile) resolve ``FORGE_ADMIN_TOKEN`` (host-qualified first)
127 with a fallback to the everyday token; the fallback keeps a solo
128 developer whose one token already administers working with
129 nothing extra. The second value names the admin variable used,
130 "" for the fallback, so a refusal can teach the missing grant.
131 """
132 contract = load_contract(root / "workshop.toml")
133 table = contract.get("forge") or {}
134 kind = str(table.get("kind", ""))
135 url = str(table.get("url", ""))
136 token, var = admin_token(kind, url)
137 if not var.startswith("FORGE_ADMIN_TOKEN"):
138 return this_forge(root), ""
139 return _connect(kind, url, token), var
142def admin_repository(root: Path) -> tuple[Repository, str]:
143 """The repository bound to the admin ladder's forge."""
144 contract = load_contract(root / "workshop.toml")
145 owner = str((contract.get("forge") or {}).get("owner", ""))
146 if not owner:
147 fail("workshop.toml [forge] must carry kind and owner")
148 forge, var = admin_forge(root)
149 return forge.repository(owner, forge_repository(root)), var
152def this_repository(root: Path) -> Repository:
153 """The workspace's repository, per the contract and the remote."""
154 contract = load_contract(root / "workshop.toml")
155 owner = str((contract.get("forge") or {}).get("owner", ""))
156 if not owner:
157 fail("workshop.toml [forge] must carry kind and owner")
158 return this_forge(root).repository(owner, forge_repository(root))
161def forge_kind(root: Path) -> str:
162 """The forge the workspace's contract names, ``github``, ``gitea`` or ``gitlab``.
164 Empty when the contract names none, which the fake forge speaks for,
165 and when there is no contract to read.
166 """
167 path = root / "workshop.toml"
168 if not path.is_file():
169 return ""
170 contract = load_contract(path)
171 return str((contract.get("forge") or {}).get("kind", ""))
174def pull_request_for(repo: Repository, root: Path, branch: str) -> PullRequest | None:
175 """The pull request *branch* is or was the head of, or None.
177 By head branch first, then by the branch's head commit: a forge
178 that deletes the head branch on merge may clear the merged pull
179 request's head ref, and the commit persists after the branch is
180 gone. A pull request found by the commit is the branch's own only
181 when its head branch is *branch* or empty, and never while
182 *branch* is a stacked branch still at the commit it started from:
183 that commit is the parent's head, so the pull request found is the
184 parent's. A forge that cannot be asked raises; the caller decides
185 what an unanswered question means, never this function.
186 """
187 pr = repo.pr.find_by_head(branch, state="all")
188 if pr is not None:
189 return pr
190 sha = git.any_head(root, branch)
191 if not sha:
192 return None
193 pr = repo.pr.find_by_head_sha(sha)
194 if pr is None or (pr.head_branch and pr.head_branch != branch):
195 return None
196 _parent, start = _stack.stack(root, branch)
197 return None if start == sha else pr