1"""The forge token surface: two names, host-qualified variants.
3``FORGE_TOKEN`` and ``FORGE_ADMIN_TOKEN`` are the only token names
4the workshop speaks. The shared rung may store host-qualified
5variants (``FORGE_TOKEN__<HOST>``), resolved through the contract's
6forge URL, so one machine serves several forges and two instances
7of one kind never collide. Everything per-forge (ambient job
8tokens, secret APIs, dialects, their own fallback variables) lives
9in the backends.
10"""
12from __future__ import annotations
14import os
15import re
16from urllib.parse import urlparse
18#: The host a kind means when the contract carries no URL. Gitea has
19#: no public default: its contract always names the server.
20_DEFAULT_HOSTS = {"github": "github.com", "gitlab": "gitlab.com"}
23def host_qualifier(kind: str, url: str) -> str:
24 """The key suffix the contract's forge resolves through.
26 The host (and port, when one is spelled) uppercased, every other
27 character folded to ``_``: ``https://forge.example.com:3000`` is
28 ``FORGE_EXAMPLE_COM_3000``. Empty when neither the URL nor the
29 kind names a host, and the bare names are the whole ladder.
30 """
31 host = urlparse(url).netloc if url else ""
32 if not host:
33 host = _DEFAULT_HOSTS.get(kind, "")
34 return re.sub(r"[^A-Z0-9]", "_", host.upper())
37def _lookup(name: str, qualifier: str) -> tuple[str, str]:
38 """The first non-empty rung of one name's ladder, and its variable."""
39 if qualifier:
40 qualified = f"{name}__{qualifier}"
41 value = os.environ.get(qualified, "")
42 if value:
43 return value, qualified
44 value = os.environ.get(name, "")
45 if value:
46 return value, name
47 return "", ""
50def forge_token(kind: str, url: str) -> tuple[str, str]:
51 """The everyday token and the variable that supplied it.
53 Host-qualified first, then bare ``FORGE_TOKEN``; both empty means
54 the backend's own documented resolution decides (GitHub asks
55 ``gh auth token``; a backend may read its own dialect's
56 variables).
57 """
58 return _lookup("FORGE_TOKEN", host_qualifier(kind, url))
61def admin_token(kind: str, url: str) -> tuple[str, str]:
62 """The admin ladder: ``FORGE_ADMIN_TOKEN`` first, then the everyday token.
64 The fallback keeps a solo developer whose one token already
65 administers working with nothing extra. The variable name rides
66 along so a refusal can teach the missing grant; it is empty when
67 nothing resolved.
68 """
69 token, var = _lookup("FORGE_ADMIN_TOKEN", host_qualifier(kind, url))
70 if token:
71 return token, var
72 return forge_token(kind, url)