git-finalizer 2.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.
- git_finalizer/__init__.py +8 -0
- git_finalizer/delivery/__init__.py +3 -0
- git_finalizer/delivery/cli.py +166 -0
- git_finalizer/delivery/content_scan.py +524 -0
- git_finalizer/delivery/engine.py +2364 -0
- git_finalizer/delivery/integration_publish.py +547 -0
- git_finalizer/delivery/parser.py +552 -0
- git_finalizer/delivery/patch_check.py +165 -0
- git_finalizer/delivery/policy.py +311 -0
- git_finalizer/delivery/repo_bootstrap.py +588 -0
- git_finalizer/delivery/repo_state.py +612 -0
- git_finalizer/delivery/retirement_plan.py +740 -0
- git_finalizer/delivery/runtime.py +553 -0
- git_finalizer/delivery/scanners.py +329 -0
- git_finalizer/delivery/snapshot_verify.py +425 -0
- git_finalizer/delivery/source_review.py +374 -0
- git_finalizer/delivery/trailers.py +164 -0
- git_finalizer/delivery/validation.py +1095 -0
- git_finalizer/errors.py +105 -0
- git_finalizer/git_io.py +281 -0
- git_finalizer/json_io.py +55 -0
- git_finalizer/toolchain/__init__.py +3 -0
- git_finalizer/toolchain/tool_skill_sync.py +3044 -0
- git_finalizer/toolchain/tool_temp_dir.py +1057 -0
- git_finalizer/toolchain/workflow_health.py +504 -0
- git_finalizer-2.0.0.dist-info/METADATA +383 -0
- git_finalizer-2.0.0.dist-info/RECORD +30 -0
- git_finalizer-2.0.0.dist-info/WHEEL +4 -0
- git_finalizer-2.0.0.dist-info/entry_points.txt +5 -0
- git_finalizer-2.0.0.dist-info/licenses/LICENSE +202 -0
|
@@ -0,0 +1,588 @@
|
|
|
1
|
+
# GF-INTEGRATION-ADAPTER: gitea-repository-bootstrap (single site: Gitea REST API v1 plan/ensure client)
|
|
2
|
+
"""Plan or idempotently ensure an empty Gitea repository over HTTPS (or localhost)."""
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
import argparse
|
|
7
|
+
import base64
|
|
8
|
+
from dataclasses import dataclass
|
|
9
|
+
import ipaddress
|
|
10
|
+
import json
|
|
11
|
+
import math
|
|
12
|
+
import os
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
import re
|
|
15
|
+
import subprocess
|
|
16
|
+
import sys
|
|
17
|
+
from typing import Any
|
|
18
|
+
from urllib.error import HTTPError, URLError
|
|
19
|
+
from urllib.parse import quote, urlparse
|
|
20
|
+
from urllib.request import ProxyHandler, Request, build_opener
|
|
21
|
+
|
|
22
|
+
from git_finalizer import __version__
|
|
23
|
+
from git_finalizer.errors import ErrorCode
|
|
24
|
+
from git_finalizer.git_io import validate_remote_name
|
|
25
|
+
|
|
26
|
+
SUMMARY_SCHEMA_VERSION = 1
|
|
27
|
+
VERSION = __version__
|
|
28
|
+
DEFAULT_HTTP_TIMEOUT = 15.0
|
|
29
|
+
GIT_TIMEOUT_SECONDS = 30.0
|
|
30
|
+
OWNER_RE = re.compile(r"^[A-Za-z0-9](?:[A-Za-z0-9._-]{0,62}[A-Za-z0-9])?$")
|
|
31
|
+
REPO_NAME_RE = re.compile(r"^[A-Za-z0-9](?:[A-Za-z0-9._-]{0,98}[A-Za-z0-9])?$")
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
@dataclass(frozen=True)
|
|
35
|
+
class Credential:
|
|
36
|
+
username: str
|
|
37
|
+
password: str
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
@dataclass(frozen=True)
|
|
41
|
+
class Target:
|
|
42
|
+
repo: Path
|
|
43
|
+
gitea_url: str
|
|
44
|
+
owner: str
|
|
45
|
+
repo_name: str
|
|
46
|
+
visibility: str
|
|
47
|
+
remote: str
|
|
48
|
+
ensure: bool
|
|
49
|
+
add_origin: bool
|
|
50
|
+
allow_insecure_http: bool
|
|
51
|
+
remote_scheme: str
|
|
52
|
+
timeout: float
|
|
53
|
+
summary: bool
|
|
54
|
+
profile: str | None = None
|
|
55
|
+
description: str = ""
|
|
56
|
+
repository_id: str | None = None
|
|
57
|
+
allocation_id: str | None = None
|
|
58
|
+
task_key: str | None = None
|
|
59
|
+
authority_key: str | None = None
|
|
60
|
+
worktree_path: str | None = None
|
|
61
|
+
role: str | None = None
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
class BootstrapFailure(RuntimeError):
|
|
65
|
+
def __init__(
|
|
66
|
+
self,
|
|
67
|
+
decision: str,
|
|
68
|
+
message: str,
|
|
69
|
+
*,
|
|
70
|
+
status: str = "blocked",
|
|
71
|
+
error_code: str = ErrorCode.BOOTSTRAP_BLOCKED,
|
|
72
|
+
exit_code: int = 2,
|
|
73
|
+
bootstrap_executed: bool = False,
|
|
74
|
+
owner_kind: str | None = None,
|
|
75
|
+
) -> None:
|
|
76
|
+
self.decision = decision
|
|
77
|
+
self.message = message
|
|
78
|
+
self.status = status
|
|
79
|
+
self.error_code = error_code
|
|
80
|
+
self.exit_code = exit_code
|
|
81
|
+
self.bootstrap_executed = bootstrap_executed
|
|
82
|
+
self.owner_kind = owner_kind
|
|
83
|
+
super().__init__(message)
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def _git(
|
|
87
|
+
repo: Path,
|
|
88
|
+
*arguments: str,
|
|
89
|
+
input_text: str | None = None,
|
|
90
|
+
timeout: float = GIT_TIMEOUT_SECONDS,
|
|
91
|
+
) -> subprocess.CompletedProcess[str]:
|
|
92
|
+
env = dict(os.environ)
|
|
93
|
+
env["LC_ALL"] = "C"
|
|
94
|
+
env["GIT_TERMINAL_PROMPT"] = "0"
|
|
95
|
+
env["GIT_OPTIONAL_LOCKS"] = "0"
|
|
96
|
+
try:
|
|
97
|
+
return subprocess.run(
|
|
98
|
+
["git", "-C", str(repo), *arguments],
|
|
99
|
+
input=input_text,
|
|
100
|
+
capture_output=True,
|
|
101
|
+
text=True,
|
|
102
|
+
timeout=timeout,
|
|
103
|
+
env=env,
|
|
104
|
+
close_fds=True,
|
|
105
|
+
check=False,
|
|
106
|
+
)
|
|
107
|
+
except subprocess.TimeoutExpired as exc:
|
|
108
|
+
raise BootstrapFailure(
|
|
109
|
+
"UNKNOWN",
|
|
110
|
+
f"Git credential/config command timed out ({arguments[0]})",
|
|
111
|
+
status="failed",
|
|
112
|
+
error_code=ErrorCode.BOOTSTRAP_FAILED,
|
|
113
|
+
exit_code=3,
|
|
114
|
+
) from exc
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def _is_loopback_host(host: str | None) -> bool:
|
|
118
|
+
if not host:
|
|
119
|
+
return False
|
|
120
|
+
lowered = host.lower()
|
|
121
|
+
if lowered in {"localhost", "::1"}:
|
|
122
|
+
return True
|
|
123
|
+
try:
|
|
124
|
+
addr = ipaddress.ip_address(lowered.strip("[]"))
|
|
125
|
+
return addr.is_loopback
|
|
126
|
+
except ValueError:
|
|
127
|
+
return False
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def _validate_gitea_url(raw_url: str, *, allow_insecure_http: bool) -> tuple[str, str, int | None]:
|
|
131
|
+
try:
|
|
132
|
+
parsed = urlparse(raw_url)
|
|
133
|
+
port = parsed.port
|
|
134
|
+
except ValueError as exc:
|
|
135
|
+
raise BootstrapFailure("BLOCK_INVALID_CONFIG", f"invalid gitea URL: {exc}") from exc
|
|
136
|
+
if (
|
|
137
|
+
parsed.scheme not in {"http", "https"}
|
|
138
|
+
or not parsed.netloc
|
|
139
|
+
or not parsed.hostname
|
|
140
|
+
or parsed.username is not None
|
|
141
|
+
or parsed.password is not None
|
|
142
|
+
or parsed.query
|
|
143
|
+
or parsed.fragment
|
|
144
|
+
or any(c in raw_url for c in ("\n", "\r", "\0"))
|
|
145
|
+
):
|
|
146
|
+
raise BootstrapFailure("BLOCK_INVALID_CONFIG", "gitea URL is invalid or contains embedded credentials")
|
|
147
|
+
if parsed.scheme == "http" and not _is_loopback_host(parsed.hostname) and not allow_insecure_http:
|
|
148
|
+
raise BootstrapFailure(
|
|
149
|
+
"BLOCK_INVALID_CONFIG",
|
|
150
|
+
"plaintext http:// is forbidden for non-loopback Gitea hosts unless --allow-insecure-http is passed",
|
|
151
|
+
)
|
|
152
|
+
normalized = raw_url.rstrip("/")
|
|
153
|
+
return normalized, parsed.hostname, port
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def _target(arguments: argparse.Namespace) -> Target:
|
|
157
|
+
if not math.isfinite(arguments.timeout) or arguments.timeout <= 0 or arguments.timeout > 120:
|
|
158
|
+
raise BootstrapFailure("BLOCK_INVALID_CONFIG", "timeout must be finite between 0 and 120 seconds")
|
|
159
|
+
if not OWNER_RE.fullmatch(arguments.owner):
|
|
160
|
+
raise BootstrapFailure("BLOCK_INVALID_CONFIG", "owner name is invalid")
|
|
161
|
+
if not REPO_NAME_RE.fullmatch(arguments.repo_name) or arguments.repo_name.endswith(".git"):
|
|
162
|
+
raise BootstrapFailure("BLOCK_INVALID_CONFIG", "repository name is invalid")
|
|
163
|
+
try:
|
|
164
|
+
remote = validate_remote_name(arguments.remote)
|
|
165
|
+
except Exception as exc:
|
|
166
|
+
raise BootstrapFailure("BLOCK_INVALID_CONFIG", "remote name is invalid") from exc
|
|
167
|
+
normalized_url, _, _ = _validate_gitea_url(
|
|
168
|
+
arguments.gitea_url, allow_insecure_http=getattr(arguments, "allow_insecure_http", False)
|
|
169
|
+
)
|
|
170
|
+
return Target(
|
|
171
|
+
repo=Path(arguments.repo).resolve(),
|
|
172
|
+
gitea_url=normalized_url,
|
|
173
|
+
owner=arguments.owner,
|
|
174
|
+
repo_name=arguments.repo_name,
|
|
175
|
+
visibility=arguments.visibility,
|
|
176
|
+
remote=remote,
|
|
177
|
+
ensure=bool(getattr(arguments, "repo_ensure", False)),
|
|
178
|
+
add_origin=bool(getattr(arguments, "add_origin", False)),
|
|
179
|
+
allow_insecure_http=bool(getattr(arguments, "allow_insecure_http", False)),
|
|
180
|
+
remote_scheme=str(getattr(arguments, "remote_scheme", "auto")),
|
|
181
|
+
timeout=float(arguments.timeout),
|
|
182
|
+
summary=bool(getattr(arguments, "summary", False)),
|
|
183
|
+
profile=getattr(arguments, "gitea_profile", None),
|
|
184
|
+
description=str(getattr(arguments, "description", "") or ""),
|
|
185
|
+
repository_id=getattr(arguments, "repository_id", None),
|
|
186
|
+
allocation_id=getattr(arguments, "allocation_id", None),
|
|
187
|
+
task_key=getattr(arguments, "task_key", None),
|
|
188
|
+
authority_key=getattr(arguments, "authority_key", None),
|
|
189
|
+
worktree_path=getattr(arguments, "worktree_path", None),
|
|
190
|
+
role=getattr(arguments, "role", None),
|
|
191
|
+
)
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
def resolve_credential(target: Target) -> Credential:
|
|
195
|
+
parsed = urlparse(target.gitea_url)
|
|
196
|
+
request = f"protocol={parsed.scheme}\nhost={parsed.netloc}\n\n"
|
|
197
|
+
completed = _git(target.repo, "credential", "fill", input_text=request, timeout=target.timeout)
|
|
198
|
+
if completed.returncode != 0:
|
|
199
|
+
raise BootstrapFailure("BLOCK_PERMISSION", "unable to resolve Git credential for target Gitea host")
|
|
200
|
+
fields: dict[str, str] = {}
|
|
201
|
+
for line in completed.stdout.splitlines():
|
|
202
|
+
if "=" in line:
|
|
203
|
+
key, _, val = line.partition("=")
|
|
204
|
+
fields[key] = val
|
|
205
|
+
user = fields.get("username", "")
|
|
206
|
+
pw = fields.get("password", "")
|
|
207
|
+
if not pw:
|
|
208
|
+
raise BootstrapFailure("BLOCK_PERMISSION", "Git credential helper returned an empty token/password")
|
|
209
|
+
return Credential(username=user, password=pw)
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
def _api_request(
|
|
213
|
+
target: Target,
|
|
214
|
+
credential: Credential,
|
|
215
|
+
method: str,
|
|
216
|
+
path: str,
|
|
217
|
+
body: dict[str, Any] | None = None,
|
|
218
|
+
) -> tuple[int, Any]:
|
|
219
|
+
url = f"{target.gitea_url}/api/v1{path}"
|
|
220
|
+
data = json.dumps(body).encode("utf-8") if body is not None else None
|
|
221
|
+
token_pair = base64.b64encode(f"{credential.username}:{credential.password}".encode()).decode("ascii")
|
|
222
|
+
headers = {
|
|
223
|
+
"Accept": "application/json",
|
|
224
|
+
"Authorization": f"Basic {token_pair}",
|
|
225
|
+
}
|
|
226
|
+
if data is not None:
|
|
227
|
+
headers["Content-Type"] = "application/json"
|
|
228
|
+
req = Request(url, data=data, method=method, headers=headers)
|
|
229
|
+
# Bypass HTTP proxy for loopback hosts; keep normal opener otherwise.
|
|
230
|
+
opener = build_opener(ProxyHandler({})) if _is_loopback_host(urlparse(url).hostname) else build_opener()
|
|
231
|
+
try:
|
|
232
|
+
with opener.open(req, timeout=target.timeout) as resp:
|
|
233
|
+
raw = resp.read()
|
|
234
|
+
parsed = json.loads(raw.decode("utf-8")) if raw else {}
|
|
235
|
+
return resp.status, parsed
|
|
236
|
+
except HTTPError as err:
|
|
237
|
+
raw = err.read()
|
|
238
|
+
try:
|
|
239
|
+
parsed = json.loads(raw.decode("utf-8")) if raw else {}
|
|
240
|
+
except Exception:
|
|
241
|
+
parsed = {}
|
|
242
|
+
return err.code, parsed
|
|
243
|
+
except (URLError, TimeoutError, ValueError, UnicodeDecodeError) as exc:
|
|
244
|
+
raise BootstrapFailure(
|
|
245
|
+
"UNKNOWN",
|
|
246
|
+
f"Gitea API error or invalid JSON response: {exc.__class__.__name__}",
|
|
247
|
+
status="failed",
|
|
248
|
+
error_code=ErrorCode.BOOTSTRAP_FAILED,
|
|
249
|
+
exit_code=3,
|
|
250
|
+
) from exc
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
def _redact_url(raw_url: str) -> str:
|
|
254
|
+
try:
|
|
255
|
+
parsed = urlparse(raw_url)
|
|
256
|
+
except ValueError:
|
|
257
|
+
return "<invalid-url>"
|
|
258
|
+
if parsed.username is not None or parsed.password is not None:
|
|
259
|
+
host = parsed.hostname or ""
|
|
260
|
+
port = f":{parsed.port}" if parsed.port else ""
|
|
261
|
+
return parsed._replace(netloc=f"<redacted>@{host}{port}").geturl()
|
|
262
|
+
return raw_url
|
|
263
|
+
|
|
264
|
+
|
|
265
|
+
def _expected_remote_urls(target: Target, repo_data: dict[str, Any] | None = None) -> tuple[str, ...]:
|
|
266
|
+
https_url = f"{target.gitea_url}/{target.owner}/{target.repo_name}.git"
|
|
267
|
+
parsed = urlparse(target.gitea_url)
|
|
268
|
+
host = parsed.hostname or ""
|
|
269
|
+
ssh_scp = f"git@{host}:{target.owner}/{target.repo_name}.git"
|
|
270
|
+
ssh_scheme = f"ssh://git@{host}/{target.owner}/{target.repo_name}.git"
|
|
271
|
+
candidates = [https_url, ssh_scp, ssh_scheme]
|
|
272
|
+
if repo_data:
|
|
273
|
+
for key in ("clone_url", "ssh_url"):
|
|
274
|
+
val = repo_data.get(key)
|
|
275
|
+
if isinstance(val, str) and val and val not in candidates:
|
|
276
|
+
candidates.append(val)
|
|
277
|
+
return tuple(candidates)
|
|
278
|
+
|
|
279
|
+
|
|
280
|
+
def _check_existing_remote(target: Target, repo_data: dict[str, Any] | None = None) -> tuple[str, str | None]:
|
|
281
|
+
res = _git(target.repo, "remote", "get-url", target.remote)
|
|
282
|
+
if res.returncode != 0:
|
|
283
|
+
return "missing", None
|
|
284
|
+
configured = res.stdout.strip()
|
|
285
|
+
allowed = _expected_remote_urls(target, repo_data)
|
|
286
|
+
if configured in allowed:
|
|
287
|
+
return "correct", _redact_url(configured)
|
|
288
|
+
raise BootstrapFailure(
|
|
289
|
+
"BLOCK_REMOTE_MISMATCH",
|
|
290
|
+
f"configured remote {target.remote} points to unexpected URL: {_redact_url(configured)}",
|
|
291
|
+
)
|
|
292
|
+
|
|
293
|
+
|
|
294
|
+
def _preferred_remote_url(target: Target, repo_data: dict[str, Any] | None) -> str:
|
|
295
|
+
if target.remote_scheme == "ssh":
|
|
296
|
+
if repo_data and isinstance(repo_data.get("ssh_url"), str) and repo_data["ssh_url"]:
|
|
297
|
+
return str(repo_data["ssh_url"])
|
|
298
|
+
host = urlparse(target.gitea_url).hostname or ""
|
|
299
|
+
return f"git@{host}:{target.owner}/{target.repo_name}.git"
|
|
300
|
+
return f"{target.gitea_url}/{target.owner}/{target.repo_name}.git"
|
|
301
|
+
|
|
302
|
+
|
|
303
|
+
def _resolve_owner_kind(target: Target, credential: Credential) -> str:
|
|
304
|
+
status, me = _api_request(target, credential, "GET", "/user")
|
|
305
|
+
if status in (401, 403):
|
|
306
|
+
raise BootstrapFailure("BLOCK_PERMISSION", "authentication failed against Gitea /api/v1/user")
|
|
307
|
+
if status != 200 or not isinstance(me, dict):
|
|
308
|
+
raise BootstrapFailure("UNKNOWN", f"unexpected status {status} from /user", status="failed", error_code=ErrorCode.BOOTSTRAP_FAILED, exit_code=3)
|
|
309
|
+
if me.get("login") == target.owner:
|
|
310
|
+
return "user"
|
|
311
|
+
|
|
312
|
+
page = 1
|
|
313
|
+
while page <= 50:
|
|
314
|
+
st, orgs = _api_request(target, credential, "GET", f"/user/orgs?page={page}&limit=50")
|
|
315
|
+
if st in (401, 403):
|
|
316
|
+
raise BootstrapFailure("BLOCK_PERMISSION", "permission denied querying Gitea organizations")
|
|
317
|
+
if st != 200 or not isinstance(orgs, list):
|
|
318
|
+
raise BootstrapFailure("UNKNOWN", "unexpected organization list payload", status="failed", error_code=ErrorCode.BOOTSTRAP_FAILED, exit_code=3)
|
|
319
|
+
if not orgs:
|
|
320
|
+
break
|
|
321
|
+
for org in orgs:
|
|
322
|
+
if isinstance(org, dict) and (org.get("username") == target.owner or org.get("login") == target.owner):
|
|
323
|
+
return "organization"
|
|
324
|
+
page += 1
|
|
325
|
+
|
|
326
|
+
# Confirm whether org exists at all vs missing.
|
|
327
|
+
org_st, _ = _api_request(target, credential, "GET", f"/orgs/{quote(target.owner)}")
|
|
328
|
+
if org_st in (401, 403):
|
|
329
|
+
raise BootstrapFailure("BLOCK_PERMISSION", f"permission denied for organization {target.owner}")
|
|
330
|
+
raise BootstrapFailure("BLOCK_INVALID_OWNER", f"unknown or inaccessible owner {target.owner}")
|
|
331
|
+
|
|
332
|
+
|
|
333
|
+
def execute(arguments: argparse.Namespace) -> tuple[int, dict[str, Any]]:
|
|
334
|
+
mode = "repo-ensure" if getattr(arguments, "repo_ensure", False) else "repo-plan"
|
|
335
|
+
bootstrap_executed = False
|
|
336
|
+
owner_kind: str | None = None
|
|
337
|
+
target: Target | None = None
|
|
338
|
+
repo_data: dict[str, Any] | None = None
|
|
339
|
+
remote_state = "unknown"
|
|
340
|
+
remote_url: str | None = None
|
|
341
|
+
reason = ""
|
|
342
|
+
try:
|
|
343
|
+
target = _target(arguments)
|
|
344
|
+
credential = resolve_credential(target)
|
|
345
|
+
|
|
346
|
+
st, repo_data = _api_request(
|
|
347
|
+
target,
|
|
348
|
+
credential,
|
|
349
|
+
"GET",
|
|
350
|
+
f"/repos/{quote(target.owner)}/{quote(target.repo_name)}",
|
|
351
|
+
)
|
|
352
|
+
if st in (401, 403):
|
|
353
|
+
raise BootstrapFailure("BLOCK_PERMISSION", "permission denied inspecting target repository")
|
|
354
|
+
if st == 200 and isinstance(repo_data, dict):
|
|
355
|
+
want_private = target.visibility == "private"
|
|
356
|
+
if bool(repo_data.get("private")) != want_private:
|
|
357
|
+
raise BootstrapFailure("BLOCK_REMOTE_MISMATCH", "existing repository visibility mismatch")
|
|
358
|
+
if repo_data.get("empty") is False:
|
|
359
|
+
raise BootstrapFailure("BLOCK_REMOTE_MISMATCH", "existing repository is not empty")
|
|
360
|
+
decision = "ALREADY_EXISTS_MATCH"
|
|
361
|
+
reason = "target repository already exists and is verified empty"
|
|
362
|
+
bootstrap_outcome = "already_exists_verified"
|
|
363
|
+
owner_kind = "organization" if repo_data.get("owner", {}).get("is_organization") else "user"
|
|
364
|
+
remote_state, remote_url = _check_existing_remote(target, repo_data)
|
|
365
|
+
elif st == 404:
|
|
366
|
+
owner_kind = _resolve_owner_kind(target, credential)
|
|
367
|
+
remote_state, remote_url = _check_existing_remote(target)
|
|
368
|
+
if not target.ensure:
|
|
369
|
+
decision = "CREATE_ALLOWED"
|
|
370
|
+
reason = "target repository does not exist yet and may be created"
|
|
371
|
+
bootstrap_outcome = "planned"
|
|
372
|
+
repo_data = None
|
|
373
|
+
else:
|
|
374
|
+
create_path = (
|
|
375
|
+
"/user/repos"
|
|
376
|
+
if owner_kind == "user"
|
|
377
|
+
else f"/orgs/{quote(target.owner)}/repos"
|
|
378
|
+
)
|
|
379
|
+
post_st, created = _api_request(
|
|
380
|
+
target,
|
|
381
|
+
credential,
|
|
382
|
+
"POST",
|
|
383
|
+
create_path,
|
|
384
|
+
{
|
|
385
|
+
"name": target.repo_name,
|
|
386
|
+
"private": target.visibility == "private",
|
|
387
|
+
"auto_init": False,
|
|
388
|
+
**({"description": target.description} if target.description else {}),
|
|
389
|
+
},
|
|
390
|
+
)
|
|
391
|
+
if post_st in (401, 403):
|
|
392
|
+
raise BootstrapFailure("BLOCK_PERMISSION", "permission denied creating repository", owner_kind=owner_kind)
|
|
393
|
+
if post_st not in (200, 201) or not isinstance(created, dict):
|
|
394
|
+
raise BootstrapFailure(
|
|
395
|
+
"UNKNOWN",
|
|
396
|
+
f"repository creation returned status {post_st}",
|
|
397
|
+
status="failed",
|
|
398
|
+
error_code=ErrorCode.BOOTSTRAP_FAILED,
|
|
399
|
+
exit_code=3,
|
|
400
|
+
owner_kind=owner_kind,
|
|
401
|
+
)
|
|
402
|
+
bootstrap_executed = True
|
|
403
|
+
repo_data = created
|
|
404
|
+
decision = "CREATED_EMPTY_VERIFIED"
|
|
405
|
+
reason = "created and verified empty target repository"
|
|
406
|
+
bootstrap_outcome = "created_empty_verified"
|
|
407
|
+
else:
|
|
408
|
+
raise BootstrapFailure(
|
|
409
|
+
"UNKNOWN",
|
|
410
|
+
f"unexpected repository lookup status {st}",
|
|
411
|
+
status="failed",
|
|
412
|
+
error_code=ErrorCode.BOOTSTRAP_FAILED,
|
|
413
|
+
exit_code=3,
|
|
414
|
+
)
|
|
415
|
+
|
|
416
|
+
remote_outcome = "not_run" if mode == "repo-plan" else "unchanged"
|
|
417
|
+
if target.ensure and target.add_origin and remote_state == "missing":
|
|
418
|
+
preferred = _preferred_remote_url(target, repo_data)
|
|
419
|
+
added = _git(target.repo, "remote", "add", target.remote, preferred)
|
|
420
|
+
if added.returncode != 0:
|
|
421
|
+
if bootstrap_executed:
|
|
422
|
+
raise BootstrapFailure(
|
|
423
|
+
"UNKNOWN",
|
|
424
|
+
f"remote changed before origin update; git remote add {target.remote} failed after creating repository",
|
|
425
|
+
status="failed",
|
|
426
|
+
error_code=ErrorCode.BOOTSTRAP_FAILED,
|
|
427
|
+
exit_code=3,
|
|
428
|
+
bootstrap_executed=True,
|
|
429
|
+
owner_kind=owner_kind,
|
|
430
|
+
)
|
|
431
|
+
raise BootstrapFailure("BLOCK_INVALID_CONFIG", f"git remote add {target.remote} failed")
|
|
432
|
+
verified = _git(target.repo, "remote", "get-url", target.remote)
|
|
433
|
+
if verified.returncode != 0 or verified.stdout.strip() != preferred:
|
|
434
|
+
if bootstrap_executed:
|
|
435
|
+
raise BootstrapFailure(
|
|
436
|
+
"UNKNOWN",
|
|
437
|
+
"remote changed before origin update; configured remote could not be verified",
|
|
438
|
+
status="failed",
|
|
439
|
+
error_code=ErrorCode.BOOTSTRAP_FAILED,
|
|
440
|
+
exit_code=3,
|
|
441
|
+
bootstrap_executed=True,
|
|
442
|
+
owner_kind=owner_kind,
|
|
443
|
+
)
|
|
444
|
+
raise BootstrapFailure("BLOCK_REMOTE_MISMATCH", "remote URL mismatch after configuration")
|
|
445
|
+
remote_state = "correct"
|
|
446
|
+
remote_outcome = "added_verified"
|
|
447
|
+
remote_url = _redact_url(preferred)
|
|
448
|
+
elif target.ensure and target.add_origin and remote_state == "correct":
|
|
449
|
+
remote_outcome = "already_correct"
|
|
450
|
+
|
|
451
|
+
repo_id_val = repo_data.get("id") if isinstance(repo_data, dict) else None
|
|
452
|
+
gitea_repo_id = repo_id_val if isinstance(repo_id_val, (int, str)) and not isinstance(repo_id_val, bool) else None
|
|
453
|
+
receipt = {
|
|
454
|
+
"summary_schema_version": SUMMARY_SCHEMA_VERSION,
|
|
455
|
+
"finalizer_version": VERSION,
|
|
456
|
+
"operation": "repository-bootstrap",
|
|
457
|
+
"mode": mode,
|
|
458
|
+
"status": "success",
|
|
459
|
+
"decision": decision,
|
|
460
|
+
"reason": reason,
|
|
461
|
+
"repository": str(target.repo),
|
|
462
|
+
"repository_id": target.repository_id,
|
|
463
|
+
"allocation_id": target.allocation_id,
|
|
464
|
+
"task_key": target.task_key,
|
|
465
|
+
"authority_key": target.authority_key,
|
|
466
|
+
"worktree_path": target.worktree_path,
|
|
467
|
+
"role": target.role,
|
|
468
|
+
"target": {
|
|
469
|
+
"profile": target.profile,
|
|
470
|
+
"base_url": target.gitea_url,
|
|
471
|
+
"owner": target.owner,
|
|
472
|
+
"repository": target.repo_name,
|
|
473
|
+
"visibility": target.visibility,
|
|
474
|
+
},
|
|
475
|
+
"bootstrap": {
|
|
476
|
+
"executed": bootstrap_executed,
|
|
477
|
+
"outcome": bootstrap_outcome,
|
|
478
|
+
"gitea_repository_id": gitea_repo_id,
|
|
479
|
+
"owner_kind": owner_kind,
|
|
480
|
+
},
|
|
481
|
+
"remote": {
|
|
482
|
+
"name": target.remote,
|
|
483
|
+
"state": remote_state,
|
|
484
|
+
"outcome": remote_outcome,
|
|
485
|
+
"url": remote_url,
|
|
486
|
+
"expected_url": _redact_url(_preferred_remote_url(target, repo_data)),
|
|
487
|
+
},
|
|
488
|
+
"publication": {"executed": False, "outcome": "not_run"},
|
|
489
|
+
"warnings": [],
|
|
490
|
+
"errors": [],
|
|
491
|
+
}
|
|
492
|
+
return 0, receipt
|
|
493
|
+
except BootstrapFailure as exc:
|
|
494
|
+
decision = exc.decision
|
|
495
|
+
receipt = {
|
|
496
|
+
"summary_schema_version": SUMMARY_SCHEMA_VERSION,
|
|
497
|
+
"finalizer_version": VERSION,
|
|
498
|
+
"operation": "repository-bootstrap",
|
|
499
|
+
"mode": mode,
|
|
500
|
+
"status": exc.status,
|
|
501
|
+
"decision": decision,
|
|
502
|
+
"reason": exc.message,
|
|
503
|
+
"error_code": exc.error_code,
|
|
504
|
+
"repository": str(target.repo) if target else str(arguments.repo),
|
|
505
|
+
"repository_id": target.repository_id if target else getattr(arguments, "repository_id", None),
|
|
506
|
+
"allocation_id": target.allocation_id if target else getattr(arguments, "allocation_id", None),
|
|
507
|
+
"task_key": target.task_key if target else getattr(arguments, "task_key", None),
|
|
508
|
+
"authority_key": target.authority_key if target else getattr(arguments, "authority_key", None),
|
|
509
|
+
"worktree_path": target.worktree_path if target else getattr(arguments, "worktree_path", None),
|
|
510
|
+
"role": target.role if target else getattr(arguments, "role", None),
|
|
511
|
+
"target": {
|
|
512
|
+
"profile": target.profile if target else getattr(arguments, "gitea_profile", None),
|
|
513
|
+
"base_url": target.gitea_url if target else None,
|
|
514
|
+
"owner": target.owner if target else getattr(arguments, "owner", None),
|
|
515
|
+
"repository": target.repo_name if target else getattr(arguments, "repo_name", None),
|
|
516
|
+
"visibility": target.visibility if target else getattr(arguments, "visibility", None),
|
|
517
|
+
},
|
|
518
|
+
"bootstrap": {
|
|
519
|
+
"executed": exc.bootstrap_executed or bootstrap_executed,
|
|
520
|
+
"outcome": "created_before_failure" if exc.bootstrap_executed else "not_executed",
|
|
521
|
+
"gitea_repository_id": None,
|
|
522
|
+
"owner_kind": exc.owner_kind or owner_kind,
|
|
523
|
+
},
|
|
524
|
+
"remote": {
|
|
525
|
+
"name": getattr(arguments, "remote", "origin"),
|
|
526
|
+
"state": "unknown",
|
|
527
|
+
"outcome": "unchanged",
|
|
528
|
+
"url": None,
|
|
529
|
+
"expected_url": None,
|
|
530
|
+
},
|
|
531
|
+
"publication": {"executed": False, "outcome": "not_run"},
|
|
532
|
+
"warnings": [],
|
|
533
|
+
"errors": [{"code": decision, "message": exc.message}],
|
|
534
|
+
}
|
|
535
|
+
return (2 if decision.startswith("BLOCK_") else 3), receipt
|
|
536
|
+
|
|
537
|
+
|
|
538
|
+
def render_human(receipt: dict[str, Any]) -> str:
|
|
539
|
+
return (
|
|
540
|
+
f"Git Finalizer {receipt['mode']}: status={receipt['status']} "
|
|
541
|
+
f"decision={receipt['decision']} bootstrap={receipt['bootstrap']['outcome']}"
|
|
542
|
+
)
|
|
543
|
+
|
|
544
|
+
|
|
545
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
546
|
+
parser = argparse.ArgumentParser(prog="git-finalize")
|
|
547
|
+
group = parser.add_mutually_exclusive_group(required=True)
|
|
548
|
+
group.add_argument("--repo-plan", action="store_true")
|
|
549
|
+
group.add_argument("--repo-ensure", action="store_true")
|
|
550
|
+
parser.add_argument("--repo", required=True)
|
|
551
|
+
parser.add_argument("--gitea-url", required=True)
|
|
552
|
+
parser.add_argument("--gitea-profile")
|
|
553
|
+
parser.add_argument("--owner", required=True)
|
|
554
|
+
parser.add_argument("--repo-name", required=True)
|
|
555
|
+
parser.add_argument("--visibility", choices=["private", "public"], required=True)
|
|
556
|
+
parser.add_argument("--description", default="")
|
|
557
|
+
parser.add_argument("--remote", default="origin")
|
|
558
|
+
parser.add_argument("--add-origin", action="store_true")
|
|
559
|
+
parser.add_argument("--allow-insecure-http", action="store_true")
|
|
560
|
+
parser.add_argument("--remote-scheme", choices=["auto", "https", "ssh"], default="auto")
|
|
561
|
+
parser.add_argument("--timeout", type=float, default=DEFAULT_HTTP_TIMEOUT)
|
|
562
|
+
parser.add_argument("--summary", action="store_true")
|
|
563
|
+
parser.add_argument("--repository-id")
|
|
564
|
+
parser.add_argument("--allocation-id")
|
|
565
|
+
parser.add_argument("--task-key")
|
|
566
|
+
parser.add_argument("--authority-key")
|
|
567
|
+
parser.add_argument("--worktree-path")
|
|
568
|
+
parser.add_argument("--role")
|
|
569
|
+
return parser
|
|
570
|
+
|
|
571
|
+
|
|
572
|
+
def main(argv: list[str] | None = None) -> int:
|
|
573
|
+
parser = build_parser()
|
|
574
|
+
try:
|
|
575
|
+
arguments = parser.parse_args(argv)
|
|
576
|
+
except SystemExit as exc:
|
|
577
|
+
return int(exc.code) if isinstance(exc.code, int) else 2
|
|
578
|
+
code, receipt = execute(arguments)
|
|
579
|
+
if arguments.summary:
|
|
580
|
+
print(json.dumps(receipt, ensure_ascii=False, sort_keys=True))
|
|
581
|
+
else:
|
|
582
|
+
stream = sys.stdout if code == 0 else sys.stderr
|
|
583
|
+
print(render_human(receipt), file=stream)
|
|
584
|
+
return code
|
|
585
|
+
|
|
586
|
+
|
|
587
|
+
if __name__ == "__main__":
|
|
588
|
+
raise SystemExit(main())
|