offgit 0.1.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.
offgit/identity.py ADDED
@@ -0,0 +1,243 @@
1
+ """Canonical project identity derived from a Git remote URL.
2
+
3
+ The canonical identity is a conservative, credential-free string such as
4
+ ``github.com/reflopai/reflop``. The project key is the hex SHA-256 of
5
+ ``"offgit:v1:" + canonical``. Nothing here ever contacts the remote.
6
+
7
+ Rules (see docs/architecture.md, "Project identity"):
8
+
9
+ * Accepted forms: ``https://host[:port]/path``, ``ssh://[user@]host[:port]/path``
10
+ and SCP-like ``[user@]host:path``. Everything else (local paths,
11
+ ``file://``, ``http://``, ``git://``, ``ext::`` ...) is rejected.
12
+ * Userinfo is stripped and never stored or logged.
13
+ * Host is lower-cased; it must be an ASCII DNS-style name (optionally mapped
14
+ through explicit ``host_aliases`` from the global config).
15
+ * A terminal ``.git`` and trailing slash are removed.
16
+ * ``github.com``: exactly ``owner/repo``; owner and repo are lower-cased
17
+ because GitHub treats them case-insensitively.
18
+ * Other hosts keep path case. Default ports (443 for https, 22 for ssh)
19
+ collapse to ``host/path``; non-default ports are namespaced by scheme as
20
+ ``https://host:8443/path`` / ``ssh://host:2222/path`` so different services
21
+ never collide.
22
+ * Query strings, fragments, percent-encoding, whitespace, control characters,
23
+ ``.``/``..`` segments and ``~`` home-relative paths are rejected rather than
24
+ guessed.
25
+ """
26
+
27
+ from __future__ import annotations
28
+
29
+ import hashlib
30
+ import re
31
+ from collections.abc import Mapping
32
+ from dataclasses import dataclass
33
+
34
+ from offgit.errors import IdentityError
35
+
36
+ IDENTITY_PREFIX = "offgit:v1:"
37
+ GITHUB_HOST = "github.com"
38
+
39
+ _HOST_LABEL = r"[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?"
40
+ _HOST_RE = re.compile(rf"^{_HOST_LABEL}(?:\.{_HOST_LABEL})*$")
41
+ _SEGMENT_RE = re.compile(r"^[A-Za-z0-9._~+-]+$")
42
+ _GH_OWNER_RE = re.compile(r"^[A-Za-z0-9](?:[A-Za-z0-9-]{0,38})$")
43
+ _GH_REPO_RE = re.compile(r"^[A-Za-z0-9._-]{1,100}$")
44
+ _USER_RE = re.compile(r"^[A-Za-z0-9._~+-]+(?::[^@/\s]*)?$")
45
+ _SCP_RE = re.compile(r"^(?:(?P<user>[^@/:\s]+)@)?(?P<host>[^@/:\s\[\]]+):(?P<path>.*)$")
46
+ _CANON_PORTED_RE = re.compile(
47
+ r"^(?P<scheme>https|ssh)://(?P<host>[^/:]+):(?P<port>[0-9]+)/(?P<path>.+)$"
48
+ )
49
+ _CANON_PLAIN_RE = re.compile(r"^(?P<host>[^/:]+)/(?P<path>.+)$")
50
+
51
+ DEFAULT_PORTS = {"https": 443, "ssh": 22}
52
+ MAX_URL_LENGTH = 2048
53
+
54
+
55
+ @dataclass(frozen=True)
56
+ class ProjectIdentity:
57
+ canonical: str
58
+ project_id: str
59
+
60
+ @classmethod
61
+ def from_canonical(cls, canonical: str) -> ProjectIdentity:
62
+ validate_canonical(canonical)
63
+ return cls(canonical=canonical, project_id=project_key(canonical))
64
+
65
+
66
+ def project_key(canonical: str) -> str:
67
+ return hashlib.sha256((IDENTITY_PREFIX + canonical).encode("utf-8")).hexdigest()
68
+
69
+
70
+ def redact_url(url: str) -> str:
71
+ """Remove userinfo (and anything credential-like) for display purposes only."""
72
+ url = url.strip()
73
+ m = re.match(r"^([A-Za-z][A-Za-z0-9+.-]*://)([^/@]*@)?(.*)$", url)
74
+ if m:
75
+ user = m.group(2)
76
+ return m.group(1) + ("***@" if user else "") + m.group(3)
77
+ m2 = _SCP_RE.match(url)
78
+ if m2 and m2.group("user"):
79
+ return "***@" + url.split("@", 1)[1]
80
+ return url
81
+
82
+
83
+ def _check_chars(url: str) -> None:
84
+ if not url:
85
+ raise IdentityError("Git remote URL is empty")
86
+ if len(url) > MAX_URL_LENGTH:
87
+ raise IdentityError("Git remote URL is too long")
88
+ for ch in url:
89
+ if ord(ch) < 0x21 or ord(ch) == 0x7F or ord(ch) > 0x7E:
90
+ raise IdentityError(
91
+ "Git remote URL contains whitespace, control or non-ASCII characters",
92
+ hint="offgit only supports plain ASCII HTTPS/SSH remote URLs",
93
+ )
94
+ if "?" in url or "#" in url:
95
+ raise IdentityError("Git remote URL must not contain a query string or fragment")
96
+ if "%" in url:
97
+ raise IdentityError(
98
+ "Git remote URL contains percent-encoding, which offgit does not normalize",
99
+ )
100
+ if "\\" in url:
101
+ raise IdentityError("Git remote URL must not contain backslashes")
102
+
103
+
104
+ def _normalize_host(host: str, aliases: Mapping[str, str]) -> str:
105
+ host_l = host.lower()
106
+ if host_l in aliases:
107
+ host_l = aliases[host_l].lower()
108
+ if host_l.endswith("."):
109
+ raise IdentityError(f"Remote host {host!r} has a trailing dot")
110
+ if not _HOST_RE.match(host_l) or len(host_l) > 253:
111
+ raise IdentityError(
112
+ f"Remote host {host!r} is not a supported DNS-style host name",
113
+ hint="IPv6 literals, IDN and unusual host names are not supported in v1",
114
+ )
115
+ return host_l
116
+
117
+
118
+ def _split_path(path: str) -> list[str]:
119
+ path = path.strip("/")
120
+ if path.endswith(".git"):
121
+ path = path[: -len(".git")]
122
+ path = path.rstrip("/")
123
+ if not path:
124
+ raise IdentityError("Git remote URL has an empty repository path")
125
+ segments = path.split("/")
126
+ for seg in segments:
127
+ if seg in ("", ".", ".."):
128
+ raise IdentityError("Git remote URL path has empty or dot segments")
129
+ if seg.startswith("~"):
130
+ raise IdentityError(
131
+ "Home-relative (~) remote paths are not supported",
132
+ hint="Use the absolute repository path on the Git server",
133
+ )
134
+ if not _SEGMENT_RE.match(seg):
135
+ raise IdentityError(f"Git remote URL path segment {seg!r} has unsupported characters")
136
+ return segments
137
+
138
+
139
+ def _build(scheme: str, host: str, port: int | None, segments: list[str]) -> str:
140
+ if host == GITHUB_HOST and (port is None or port == DEFAULT_PORTS[scheme]):
141
+ if len(segments) != 2:
142
+ raise IdentityError("GitHub remote must be exactly <owner>/<repo>")
143
+ owner, repo = segments
144
+ if not _GH_OWNER_RE.match(owner) or owner.endswith("-") or "--" in owner:
145
+ raise IdentityError(f"Invalid GitHub owner {owner!r}")
146
+ if not _GH_REPO_RE.match(repo) or repo in (".", ".."):
147
+ raise IdentityError(f"Invalid GitHub repository name {repo!r}")
148
+ return f"{GITHUB_HOST}/{owner.lower()}/{repo.lower()}"
149
+ path = "/".join(segments)
150
+ if port is None or port == DEFAULT_PORTS[scheme]:
151
+ return f"{host}/{path}"
152
+ return f"{scheme}://{host}:{port}/{path}"
153
+
154
+
155
+ def _parse_port(text: str) -> int:
156
+ if not text.isdigit() or text.startswith("0") or len(text) > 5:
157
+ raise IdentityError(f"Invalid port {text!r} in Git remote URL")
158
+ port = int(text)
159
+ if not 1 <= port <= 65535:
160
+ raise IdentityError(f"Invalid port {text!r} in Git remote URL")
161
+ return port
162
+
163
+
164
+ def canonicalize(url: str, aliases: Mapping[str, str] | None = None) -> str:
165
+ """Return the canonical identity for a Git remote URL or raise IdentityError."""
166
+ aliases = {k.lower(): v for k, v in (aliases or {}).items()}
167
+ _check_chars(url)
168
+
169
+ scheme_match = re.match(r"^([A-Za-z][A-Za-z0-9+.-]*)://(.*)$", url)
170
+ if scheme_match:
171
+ scheme = scheme_match.group(1).lower()
172
+ rest = scheme_match.group(2)
173
+ if scheme not in ("https", "ssh"):
174
+ raise IdentityError(
175
+ f"Unsupported Git remote scheme {scheme!r}",
176
+ hint="offgit supports https://, ssh:// and SCP-like user@host:path remotes",
177
+ )
178
+ authority, slash, path = rest.partition("/")
179
+ if not slash:
180
+ raise IdentityError("Git remote URL has no repository path")
181
+ if "@" in authority:
182
+ userinfo, _, authority = authority.rpartition("@")
183
+ if not userinfo or not _USER_RE.match(userinfo):
184
+ raise IdentityError("Git remote URL has malformed user information")
185
+ if authority.startswith("["):
186
+ raise IdentityError("IPv6 literal hosts are not supported")
187
+ host, colon, port_text = authority.partition(":")
188
+ port = _parse_port(port_text) if colon else None
189
+ if not host:
190
+ raise IdentityError("Git remote URL has no host")
191
+ host_n = _normalize_host(host, aliases)
192
+ return _build(scheme, host_n, port, _split_path(path))
193
+
194
+ if "::" in url:
195
+ raise IdentityError("Git remote helpers (transport::address) are not supported")
196
+ if url.startswith(("/", ".", "~")):
197
+ raise IdentityError(
198
+ "Local filesystem remotes are not supported",
199
+ hint="offgit identifies projects by a network remote such as GitHub",
200
+ )
201
+ scp = _SCP_RE.match(url)
202
+ if not scp:
203
+ raise IdentityError(
204
+ "Unrecognized Git remote URL",
205
+ hint="Expected https://host/owner/repo, ssh://host/owner/repo or user@host:owner/repo",
206
+ )
207
+ user = scp.group("user")
208
+ if user is not None and not _USER_RE.match(user):
209
+ raise IdentityError("Git remote URL has malformed user information")
210
+ host_n = _normalize_host(scp.group("host"), aliases)
211
+ path = scp.group("path")
212
+ if path.startswith("//"):
213
+ raise IdentityError("Malformed SCP-like remote path")
214
+ return _build("ssh", host_n, None, _split_path(path))
215
+
216
+
217
+ def validate_canonical(canonical: str) -> None:
218
+ """Validate a canonical identity string received from elsewhere (e.g. the server side)."""
219
+ if not isinstance(canonical, str) or not canonical or len(canonical) > MAX_URL_LENGTH:
220
+ raise IdentityError("Invalid canonical identity")
221
+ m = _CANON_PORTED_RE.match(canonical)
222
+ if m:
223
+ scheme, host, port_text, path = m.group("scheme", "host", "port", "path")
224
+ port = _parse_port(port_text)
225
+ if port == DEFAULT_PORTS[scheme]:
226
+ raise IdentityError("Canonical identity must not include a default port")
227
+ else:
228
+ m2 = _CANON_PLAIN_RE.match(canonical)
229
+ if not m2:
230
+ raise IdentityError("Invalid canonical identity")
231
+ scheme, host, port, path = "ssh", m2.group("host"), None, m2.group("path")
232
+ if path.endswith(".git"):
233
+ raise IdentityError("Canonical identity must not end in .git")
234
+ if _normalize_host(host, {}) != host:
235
+ raise IdentityError("Canonical identity host is not normalized")
236
+ rebuilt = _build(scheme, host, port, _split_path(path))
237
+ if rebuilt != canonical:
238
+ raise IdentityError("Canonical identity is not in normalized form")
239
+
240
+
241
+ def identity_from_url(url: str, aliases: Mapping[str, str] | None = None) -> ProjectIdentity:
242
+ canonical = canonicalize(url, aliases)
243
+ return ProjectIdentity(canonical=canonical, project_id=project_key(canonical))
offgit/local_state.py ADDED
@@ -0,0 +1,255 @@
1
+ """Per-worktree client metadata under ``<absolute git dir>/offgit/``.
2
+
3
+ * ``state.json`` verified bases per path, server identity/epoch (schema v1)
4
+ * ``lock`` advisory lock serializing offgit writers in this worktree
5
+ * ``pending.json`` request that was sent but whose outcome is not yet known
6
+ * ``recovery/<operation-id>/`` pull journals and exact pre-write local bytes
7
+
8
+ Nothing here is inside the working tree, so it never shows up in ``git status``.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import contextlib
14
+ import fcntl
15
+ import json
16
+ import os
17
+ import secrets
18
+ import shutil
19
+ from collections.abc import Iterator
20
+ from dataclasses import dataclass, field
21
+ from datetime import UTC, datetime
22
+ from pathlib import Path
23
+ from typing import Any
24
+
25
+ from offgit.config import atomic_write_private
26
+ from offgit.errors import OffgitError, RecoveryRequired
27
+ from offgit.hashing import is_sha256
28
+ from offgit.paths import validate_rel_path
29
+
30
+ STATE_SCHEMA = 1
31
+
32
+
33
+ def utcnow() -> str:
34
+ return datetime.now(UTC).strftime("%Y-%m-%dT%H:%M:%SZ")
35
+
36
+
37
+ @dataclass
38
+ class FileBase:
39
+ base_sha256: str
40
+ base_registered: bool = True
41
+ base_revision: int = 0
42
+
43
+ def to_dict(self) -> dict[str, Any]:
44
+ return {
45
+ "base_sha256": self.base_sha256,
46
+ "base_registered": self.base_registered,
47
+ "base_revision": self.base_revision,
48
+ }
49
+
50
+
51
+ @dataclass
52
+ class State:
53
+ project_id: str
54
+ canonical_remote: str
55
+ remote_name: str
56
+ server_id: str | None = None
57
+ server_epoch: str | None = None
58
+ last_seen_revision: int = 0
59
+ files: dict[str, FileBase] = field(default_factory=dict)
60
+
61
+ def to_dict(self) -> dict[str, Any]:
62
+ return {
63
+ "schema_version": STATE_SCHEMA,
64
+ "project_id": self.project_id,
65
+ "canonical_remote": self.canonical_remote,
66
+ "remote_name": self.remote_name,
67
+ "server_id": self.server_id,
68
+ "server_epoch": self.server_epoch,
69
+ "last_seen_revision": self.last_seen_revision,
70
+ "files": {p: fb.to_dict() for p, fb in sorted(self.files.items())},
71
+ }
72
+
73
+ @classmethod
74
+ def from_dict(cls, data: Any) -> State:
75
+ if not isinstance(data, dict) or data.get("schema_version") != STATE_SCHEMA:
76
+ raise ValueError("unsupported state schema")
77
+ files: dict[str, FileBase] = {}
78
+ raw_files = data.get("files", {})
79
+ if not isinstance(raw_files, dict):
80
+ raise ValueError("files must be an object")
81
+ for path, fb in raw_files.items():
82
+ validate_rel_path(path)
83
+ if not isinstance(fb, dict) or not is_sha256(fb.get("base_sha256")):
84
+ raise ValueError(f"invalid base for {path}")
85
+ files[path] = FileBase(
86
+ base_sha256=fb["base_sha256"],
87
+ base_registered=bool(fb.get("base_registered", True)),
88
+ base_revision=int(fb.get("base_revision", 0)),
89
+ )
90
+ if not is_sha256(data.get("project_id")) or not isinstance(
91
+ data.get("canonical_remote"), str
92
+ ):
93
+ raise ValueError("invalid project identity")
94
+ return cls(
95
+ project_id=data["project_id"],
96
+ canonical_remote=data["canonical_remote"],
97
+ remote_name=str(data.get("remote_name", "origin")),
98
+ server_id=data.get("server_id"),
99
+ server_epoch=data.get("server_epoch"),
100
+ last_seen_revision=int(data.get("last_seen_revision", 0)),
101
+ files=files,
102
+ )
103
+
104
+
105
+ class LocalStore:
106
+ def __init__(self, git_dir: str) -> None:
107
+ self.dir = Path(git_dir) / "offgit"
108
+
109
+ # -- paths ---------------------------------------------------------------
110
+ @property
111
+ def state_path(self) -> Path:
112
+ return self.dir / "state.json"
113
+
114
+ @property
115
+ def pending_path(self) -> Path:
116
+ return self.dir / "pending.json"
117
+
118
+ @property
119
+ def recovery_dir(self) -> Path:
120
+ return self.dir / "recovery"
121
+
122
+ @property
123
+ def settings_path(self) -> Path:
124
+ return self.dir / "settings.json"
125
+
126
+ def _ensure_dir(self) -> None:
127
+ self.dir.mkdir(mode=0o700, parents=True, exist_ok=True)
128
+
129
+ # -- lock ----------------------------------------------------------------
130
+ @contextlib.contextmanager
131
+ def lock(self) -> Iterator[None]:
132
+ self._ensure_dir()
133
+ fd = os.open(
134
+ self.dir / "lock", os.O_RDWR | os.O_CREAT | getattr(os, "O_NOFOLLOW", 0), 0o600
135
+ )
136
+ try:
137
+ try:
138
+ fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
139
+ except BlockingIOError as exc:
140
+ raise OffgitError(
141
+ "another offgit command is running in this worktree",
142
+ code="locked",
143
+ hint="Wait for it to finish and retry",
144
+ ) from exc
145
+ yield
146
+ finally:
147
+ os.close(fd)
148
+
149
+ # -- state ---------------------------------------------------------------
150
+ def load(self) -> State | None:
151
+ try:
152
+ raw = self.state_path.read_text(encoding="utf-8")
153
+ except FileNotFoundError:
154
+ return None
155
+ try:
156
+ return State.from_dict(json.loads(raw))
157
+ except (ValueError, TypeError) as exc:
158
+ raise RecoveryRequired(
159
+ f"local offgit state is unreadable: {self.state_path}",
160
+ code="state_corrupt",
161
+ hint="Move the file aside; offgit then treats this worktree as first use "
162
+ "(differences become conflicts, nothing is overwritten)",
163
+ ) from exc
164
+
165
+ def save(self, state: State) -> None:
166
+ self._ensure_dir()
167
+ atomic_write_private(self.state_path, json.dumps(state.to_dict(), indent=2) + "\n")
168
+
169
+ # -- per-worktree settings (remote selection) -----------------------------
170
+ def load_settings(self) -> dict[str, Any]:
171
+ try:
172
+ data = json.loads(self.settings_path.read_text(encoding="utf-8"))
173
+ except FileNotFoundError:
174
+ return {}
175
+ except ValueError:
176
+ return {}
177
+ return data if isinstance(data, dict) else {}
178
+
179
+ def save_settings(self, data: dict[str, Any]) -> None:
180
+ self._ensure_dir()
181
+ atomic_write_private(self.settings_path, json.dumps(data, indent=2) + "\n")
182
+
183
+ # -- pending mutation ------------------------------------------------------
184
+ def write_pending(self, record: dict[str, Any]) -> None:
185
+ self._ensure_dir()
186
+ atomic_write_private(self.pending_path, json.dumps(record, indent=2) + "\n")
187
+
188
+ def load_pending(self) -> dict[str, Any] | None:
189
+ try:
190
+ data = json.loads(self.pending_path.read_text(encoding="utf-8"))
191
+ except FileNotFoundError:
192
+ return None
193
+ except ValueError as exc:
194
+ raise RecoveryRequired(
195
+ f"pending-operation record is unreadable: {self.pending_path}",
196
+ code="pending_corrupt",
197
+ ) from exc
198
+ return data if isinstance(data, dict) else None
199
+
200
+ def clear_pending(self) -> None:
201
+ with contextlib.suppress(FileNotFoundError):
202
+ self.pending_path.unlink()
203
+
204
+ # -- recovery journals ----------------------------------------------------
205
+ def new_operation_dir(self) -> tuple[str, Path]:
206
+ op_id = datetime.now(UTC).strftime("%Y%m%dT%H%M%SZ") + "-" + secrets.token_hex(4)
207
+ path = self.recovery_dir / op_id
208
+ path.mkdir(mode=0o700, parents=True)
209
+ return op_id, path
210
+
211
+ def write_journal(self, op_dir: Path, journal: dict[str, Any]) -> None:
212
+ atomic_write_private(op_dir / "journal.json", json.dumps(journal, indent=2) + "\n")
213
+
214
+ def open_journals(self) -> list[tuple[Path, dict[str, Any]]]:
215
+ """Journals whose operation did not finish cleanly."""
216
+ out: list[tuple[Path, dict[str, Any]]] = []
217
+ if not self.recovery_dir.exists():
218
+ return out
219
+ for d in sorted(self.recovery_dir.iterdir()):
220
+ jp = d / "journal.json"
221
+ if not jp.is_file():
222
+ continue
223
+ try:
224
+ j = json.loads(jp.read_text(encoding="utf-8"))
225
+ except ValueError:
226
+ out.append((d, {"status": "corrupt"}))
227
+ continue
228
+ if isinstance(j, dict) and j.get("status") == "applying":
229
+ out.append((d, j))
230
+ return out
231
+
232
+ def recovery_entries(self) -> list[dict[str, Any]]:
233
+ out: list[dict[str, Any]] = []
234
+ if not self.recovery_dir.exists():
235
+ return out
236
+ for d in sorted(self.recovery_dir.iterdir()):
237
+ jp = d / "journal.json"
238
+ try:
239
+ j = json.loads(jp.read_text(encoding="utf-8"))
240
+ except (OSError, ValueError):
241
+ continue
242
+ out.append(
243
+ {
244
+ "operation_id": d.name,
245
+ "directory": str(d),
246
+ "status": j.get("status"),
247
+ "operation": j.get("operation"),
248
+ "paths": [e.get("path") for e in j.get("entries", [])],
249
+ }
250
+ )
251
+ return out
252
+
253
+ def remove_operation_dir(self, op_dir: Path) -> None:
254
+ if op_dir.parent == self.recovery_dir:
255
+ shutil.rmtree(op_dir, ignore_errors=True)
offgit/output.py ADDED
@@ -0,0 +1,160 @@
1
+ """Human (Rich) and machine (JSON) rendering of command reports.
2
+
3
+ Human output goes to stdout; diagnostics, warnings and errors to stderr. JSON
4
+ mode prints exactly one document on stdout and never emits ANSI codes.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import json
10
+ import os
11
+ import sys
12
+ from dataclasses import dataclass, field
13
+ from typing import Any
14
+
15
+ from rich.console import Console
16
+ from rich.markup import escape
17
+ from rich.table import Table
18
+
19
+ from offgit.errors import EXIT_OK, OffgitError
20
+
21
+ STYLES = {
22
+ "ok": ("✓", "green"),
23
+ "same": ("–", "grey50"),
24
+ "warn": ("!", "yellow"),
25
+ "error": ("✗", "red"),
26
+ "info": ("•", "cyan"),
27
+ }
28
+
29
+
30
+ @dataclass
31
+ class Item:
32
+ path: str
33
+ message: str
34
+ style: str = "info"
35
+ data: dict[str, Any] = field(default_factory=dict)
36
+
37
+ def to_dict(self) -> dict[str, Any]:
38
+ return {"path": self.path, "result": self.message, "level": self.style, **self.data}
39
+
40
+
41
+ @dataclass
42
+ class Report:
43
+ command: str
44
+ repository: str | None = None
45
+ server: str | None = None
46
+ items: list[Item] = field(default_factory=list)
47
+ summary: str | None = None
48
+ summary_style: str = "ok"
49
+ warnings: list[str] = field(default_factory=list)
50
+ notes: list[str] = field(default_factory=list)
51
+ data: dict[str, Any] = field(default_factory=dict)
52
+ exit_code: int = EXIT_OK
53
+ error: OffgitError | None = None
54
+ text: str | None = None # raw text body (diff) printed verbatim
55
+ table: dict[str, Any] | None = None # {"columns": [...], "rows": [[...]]}
56
+
57
+ def add(self, path: str, message: str, style: str = "info", **data: Any) -> None:
58
+ self.items.append(Item(path, message, style, data))
59
+
60
+ def to_dict(self) -> dict[str, Any]:
61
+ doc: dict[str, Any] = {
62
+ "ok": self.exit_code == EXIT_OK,
63
+ "command": self.command,
64
+ "exit_code": self.exit_code,
65
+ "repository": self.repository,
66
+ "server": self.server,
67
+ "files": [i.to_dict() for i in self.items],
68
+ "summary": self.summary,
69
+ "warnings": self.warnings,
70
+ **self.data,
71
+ }
72
+ if self.text is not None:
73
+ doc["text"] = self.text
74
+ if self.table is not None:
75
+ doc["table"] = self.table
76
+ if self.error is not None:
77
+ doc["error"] = self.error.to_dict()
78
+ return doc
79
+
80
+
81
+ class Output:
82
+ def __init__(self, *, json_mode: bool, no_color: bool, quiet: bool, verbose: bool) -> None:
83
+ self.json_mode = json_mode
84
+ self.quiet = quiet
85
+ self.verbose = verbose
86
+ color_off = no_color or json_mode or bool(os.environ.get("NO_COLOR"))
87
+ self.out = Console(
88
+ file=sys.stdout,
89
+ no_color=color_off,
90
+ color_system=None if color_off else "auto",
91
+ highlight=False,
92
+ soft_wrap=True,
93
+ )
94
+ self.err = Console(
95
+ file=sys.stderr,
96
+ no_color=color_off,
97
+ color_system=None if color_off else "auto",
98
+ highlight=False,
99
+ soft_wrap=True,
100
+ )
101
+
102
+ def debug(self, msg: str) -> None:
103
+ if self.verbose and not self.json_mode:
104
+ self.err.print(f"[grey50]{escape(msg)}[/]")
105
+
106
+ def emit(self, report: Report) -> None:
107
+ if self.json_mode:
108
+ sys.stdout.write(json.dumps(report.to_dict(), ensure_ascii=False, indent=2) + "\n")
109
+ sys.stdout.flush()
110
+ return
111
+ o = self.out
112
+ if not self.quiet:
113
+ if report.repository:
114
+ o.print(f"[cyan]Repository:[/] {escape(report.repository)}")
115
+ if report.server:
116
+ o.print(f"[cyan]Server:[/] {escape(report.server)}")
117
+ width = max((len(i.path) for i in report.items), default=0)
118
+ for item in report.items:
119
+ if self.quiet and item.style in ("same", "info", "ok"):
120
+ continue
121
+ sym, color = STYLES.get(item.style, STYLES["info"])
122
+ o.print(
123
+ f"[{color}]{sym}[/] {escape(item.path.ljust(width))} [{color}]{escape(item.message)}[/]"
124
+ )
125
+ if report.table and not self.quiet:
126
+ t = Table(show_header=True, header_style="bold", box=None, pad_edge=False)
127
+ for col in report.table["columns"]:
128
+ t.add_column(col)
129
+ for row in report.table["rows"]:
130
+ t.add_row(*[escape(str(c)) for c in row])
131
+ o.print(t)
132
+ if report.text:
133
+ # raw text (diffs) without markup interpretation
134
+ sys.stdout.write(report.text if report.text.endswith("\n") else report.text + "\n")
135
+ sys.stdout.flush()
136
+ for note in report.notes:
137
+ if not self.quiet:
138
+ o.print(f"[cyan]•[/] {escape(note)}")
139
+ for w in report.warnings:
140
+ self.err.print(f"[yellow]![/] {escape(w)}")
141
+ if report.error is not None:
142
+ self.print_error(report.error)
143
+ elif report.summary:
144
+ sym, color = STYLES.get(report.summary_style, STYLES["info"])
145
+ o.print(f"[{color}]{sym} {escape(report.summary)}[/]")
146
+
147
+ def print_error(self, err: OffgitError) -> None:
148
+ if self.json_mode:
149
+ return
150
+ self.err.print(f"[red]✗ {escape(err.message)}[/]")
151
+ if err.hint:
152
+ self.err.print(f" [cyan]hint:[/] {escape(err.hint)}")
153
+
154
+ def emit_error(self, command: str, err: OffgitError) -> None:
155
+ if self.json_mode:
156
+ rep = Report(command=command, exit_code=err.exit_code, error=err)
157
+ sys.stdout.write(json.dumps(rep.to_dict(), ensure_ascii=False, indent=2) + "\n")
158
+ sys.stdout.flush()
159
+ else:
160
+ self.print_error(err)