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/__init__.py +4 -0
- offgit/cli.py +498 -0
- offgit/client.py +1636 -0
- offgit/config.py +281 -0
- offgit/errors.py +115 -0
- offgit/gitrepo.py +186 -0
- offgit/hashing.py +22 -0
- offgit/identity.py +243 -0
- offgit/local_state.py +255 -0
- offgit/output.py +160 -0
- offgit/paths.py +367 -0
- offgit/protocol.py +466 -0
- offgit/reconcile.py +169 -0
- offgit/server/__init__.py +1 -0
- offgit/server/backup.py +401 -0
- offgit/server/cli.py +391 -0
- offgit/server/export.py +75 -0
- offgit/server/health.py +59 -0
- offgit/server/locks.py +48 -0
- offgit/server/migrate.py +59 -0
- offgit/server/migrations/__init__.py +12 -0
- offgit/server/migrations/v001_initial.py +57 -0
- offgit/server/restore.py +207 -0
- offgit/server/rpc.py +187 -0
- offgit/server/schema.py +228 -0
- offgit/server/settings.py +140 -0
- offgit/server/store.py +658 -0
- offgit/transport.py +304 -0
- offgit-0.1.0.dist-info/METADATA +171 -0
- offgit-0.1.0.dist-info/RECORD +33 -0
- offgit-0.1.0.dist-info/WHEEL +4 -0
- offgit-0.1.0.dist-info/entry_points.txt +3 -0
- offgit-0.1.0.dist-info/licenses/LICENSE +21 -0
offgit/config.py
ADDED
|
@@ -0,0 +1,281 @@
|
|
|
1
|
+
"""Global client configuration (``$XDG_CONFIG_HOME/offgit/config.toml``).
|
|
2
|
+
|
|
3
|
+
Precedence: command-line flags > ``OFFGIT_CONFIG`` (path override) > default path.
|
|
4
|
+
The file never contains passwords or key material, only an optional *path* to
|
|
5
|
+
an SSH identity file.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import contextlib
|
|
11
|
+
import json
|
|
12
|
+
import os
|
|
13
|
+
import re
|
|
14
|
+
import socket
|
|
15
|
+
import tomllib
|
|
16
|
+
from dataclasses import dataclass, field
|
|
17
|
+
from pathlib import Path
|
|
18
|
+
from typing import Any
|
|
19
|
+
|
|
20
|
+
from offgit.errors import ConfigError
|
|
21
|
+
|
|
22
|
+
DEFAULT_SERVER_BINARY = "/opt/offgit/venv/bin/offgit-server"
|
|
23
|
+
DEFAULT_CONNECT_TIMEOUT = 10
|
|
24
|
+
DEFAULT_OPERATION_TIMEOUT = 120
|
|
25
|
+
|
|
26
|
+
_HOST_RE = re.compile(r"^[A-Za-z0-9_][A-Za-z0-9._-]{0,252}$")
|
|
27
|
+
_USER_RE = re.compile(r"^[A-Za-z_][A-Za-z0-9._-]{0,31}$")
|
|
28
|
+
_BIN_RE = re.compile(r"^/[A-Za-z0-9._/+-]{1,255}$")
|
|
29
|
+
_REMOTE_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._/-]{0,99}$")
|
|
30
|
+
_DEVICE_RE = re.compile(r"[^A-Za-z0-9._-]")
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def config_path() -> Path:
|
|
34
|
+
override = os.environ.get("OFFGIT_CONFIG")
|
|
35
|
+
if override:
|
|
36
|
+
return Path(override).expanduser()
|
|
37
|
+
base = os.environ.get("XDG_CONFIG_HOME") or str(Path.home() / ".config")
|
|
38
|
+
return Path(base) / "offgit" / "config.toml"
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def default_device_name() -> str:
|
|
42
|
+
name = _DEVICE_RE.sub("-", socket.gethostname().split(".")[0])[:64]
|
|
43
|
+
return name or "device"
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def validate_host(host: str) -> str:
|
|
47
|
+
if not isinstance(host, str) or not _HOST_RE.match(host) or ".." in host:
|
|
48
|
+
raise ConfigError(
|
|
49
|
+
f"Invalid server host {host!r}",
|
|
50
|
+
hint="Use a host name, Tailscale name, IP address or ~/.ssh/config alias",
|
|
51
|
+
)
|
|
52
|
+
return host
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def validate_user(user: str) -> str:
|
|
56
|
+
if not isinstance(user, str) or not _USER_RE.match(user):
|
|
57
|
+
raise ConfigError(f"Invalid SSH user name {user!r}")
|
|
58
|
+
return user
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def validate_port(port: int) -> int:
|
|
62
|
+
if isinstance(port, bool) or not isinstance(port, int) or not 1 <= port <= 65535:
|
|
63
|
+
raise ConfigError(f"Invalid SSH port {port!r}")
|
|
64
|
+
return port
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def validate_identity(path: str) -> str:
|
|
68
|
+
if not isinstance(path, str) or not path or path.startswith("-") or "\n" in path:
|
|
69
|
+
raise ConfigError(f"Invalid identity file path {path!r}")
|
|
70
|
+
if "\0" in path:
|
|
71
|
+
raise ConfigError("Identity file path contains NUL")
|
|
72
|
+
return path
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def validate_server_binary(path: str) -> str:
|
|
76
|
+
if not isinstance(path, str) or not _BIN_RE.match(path) or "/../" in path + "/":
|
|
77
|
+
raise ConfigError(
|
|
78
|
+
f"Invalid server binary path {path!r}",
|
|
79
|
+
hint="Use an absolute path such as /opt/offgit/venv/bin/offgit-server",
|
|
80
|
+
)
|
|
81
|
+
return path
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def validate_remote_name(name: str) -> str:
|
|
85
|
+
if not isinstance(name, str) or not _REMOTE_RE.match(name):
|
|
86
|
+
raise ConfigError(f"Invalid Git remote name {name!r}")
|
|
87
|
+
return name
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
@dataclass
|
|
91
|
+
class ServerConfig:
|
|
92
|
+
host: str
|
|
93
|
+
user: str | None = None
|
|
94
|
+
port: int | None = None
|
|
95
|
+
identity_file: str | None = None
|
|
96
|
+
connect_timeout: int = DEFAULT_CONNECT_TIMEOUT
|
|
97
|
+
operation_timeout: int = DEFAULT_OPERATION_TIMEOUT
|
|
98
|
+
server_binary: str = DEFAULT_SERVER_BINARY
|
|
99
|
+
|
|
100
|
+
def validate(self) -> None:
|
|
101
|
+
validate_host(self.host)
|
|
102
|
+
if self.user is not None:
|
|
103
|
+
validate_user(self.user)
|
|
104
|
+
if self.port is not None:
|
|
105
|
+
validate_port(self.port)
|
|
106
|
+
if self.identity_file is not None:
|
|
107
|
+
validate_identity(self.identity_file)
|
|
108
|
+
for name in ("connect_timeout", "operation_timeout"):
|
|
109
|
+
val = getattr(self, name)
|
|
110
|
+
if isinstance(val, bool) or not isinstance(val, int) or not 1 <= val <= 3600:
|
|
111
|
+
raise ConfigError(f"Invalid {name} {val!r} (1..3600 seconds)")
|
|
112
|
+
validate_server_binary(self.server_binary)
|
|
113
|
+
|
|
114
|
+
@property
|
|
115
|
+
def remote_command(self) -> str:
|
|
116
|
+
return f"{self.server_binary} rpc"
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
@dataclass
|
|
120
|
+
class Config:
|
|
121
|
+
server: ServerConfig | None = None
|
|
122
|
+
default_remote: str = "origin"
|
|
123
|
+
device_name: str = field(default_factory=default_device_name)
|
|
124
|
+
host_aliases: dict[str, str] = field(default_factory=dict)
|
|
125
|
+
path: Path | None = None
|
|
126
|
+
|
|
127
|
+
def require_server(self) -> ServerConfig:
|
|
128
|
+
if self.server is None:
|
|
129
|
+
raise ConfigError(
|
|
130
|
+
"offgit is not configured",
|
|
131
|
+
code="not_configured",
|
|
132
|
+
hint="Run: offgit configure --host HOST --user USER",
|
|
133
|
+
)
|
|
134
|
+
return self.server
|
|
135
|
+
|
|
136
|
+
def validate(self) -> None:
|
|
137
|
+
if self.server is not None:
|
|
138
|
+
self.server.validate()
|
|
139
|
+
validate_remote_name(self.default_remote)
|
|
140
|
+
if not re.match(r"^[A-Za-z0-9._-]{1,64}$", self.device_name):
|
|
141
|
+
raise ConfigError(f"Invalid device_name {self.device_name!r}")
|
|
142
|
+
for alias, target in self.host_aliases.items():
|
|
143
|
+
validate_host(alias)
|
|
144
|
+
validate_host(target)
|
|
145
|
+
|
|
146
|
+
def sanitized(self) -> dict[str, Any]:
|
|
147
|
+
"""Configuration suitable for printing (no secrets are stored, but stay minimal)."""
|
|
148
|
+
server = None
|
|
149
|
+
if self.server is not None:
|
|
150
|
+
server = {
|
|
151
|
+
"host": self.server.host,
|
|
152
|
+
"user": self.server.user,
|
|
153
|
+
"port": self.server.port,
|
|
154
|
+
"identity_file": self.server.identity_file,
|
|
155
|
+
"connect_timeout": self.server.connect_timeout,
|
|
156
|
+
"operation_timeout": self.server.operation_timeout,
|
|
157
|
+
"server_binary": self.server.server_binary,
|
|
158
|
+
}
|
|
159
|
+
return {
|
|
160
|
+
"path": str(self.path) if self.path else None,
|
|
161
|
+
"server": server,
|
|
162
|
+
"default_remote": self.default_remote,
|
|
163
|
+
"device_name": self.device_name,
|
|
164
|
+
"host_aliases": dict(self.host_aliases),
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
_ALLOWED_TOP = {"server", "client", "host_aliases"}
|
|
169
|
+
_ALLOWED_SERVER = {
|
|
170
|
+
"host",
|
|
171
|
+
"user",
|
|
172
|
+
"port",
|
|
173
|
+
"identity_file",
|
|
174
|
+
"connect_timeout",
|
|
175
|
+
"operation_timeout",
|
|
176
|
+
"server_binary",
|
|
177
|
+
}
|
|
178
|
+
_ALLOWED_CLIENT = {"default_remote", "device_name"}
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
def load_config(path: Path | None = None) -> Config:
|
|
182
|
+
path = path or config_path()
|
|
183
|
+
if not path.exists():
|
|
184
|
+
return Config(path=path)
|
|
185
|
+
try:
|
|
186
|
+
raw = tomllib.loads(path.read_text(encoding="utf-8"))
|
|
187
|
+
except (OSError, UnicodeDecodeError, tomllib.TOMLDecodeError) as exc:
|
|
188
|
+
raise ConfigError(f"Cannot read config {path}: {exc}") from exc
|
|
189
|
+
unknown = set(raw) - _ALLOWED_TOP
|
|
190
|
+
if unknown:
|
|
191
|
+
raise ConfigError(f"Unknown config sections in {path}: {sorted(unknown)}")
|
|
192
|
+
cfg = Config(path=path)
|
|
193
|
+
srv = raw.get("server")
|
|
194
|
+
if srv is not None:
|
|
195
|
+
if not isinstance(srv, dict) or set(srv) - _ALLOWED_SERVER or "host" not in srv:
|
|
196
|
+
raise ConfigError(f"Invalid [server] section in {path}")
|
|
197
|
+
cfg.server = ServerConfig(**srv)
|
|
198
|
+
cli = raw.get("client", {})
|
|
199
|
+
if not isinstance(cli, dict) or set(cli) - _ALLOWED_CLIENT:
|
|
200
|
+
raise ConfigError(f"Invalid [client] section in {path}")
|
|
201
|
+
if "default_remote" in cli:
|
|
202
|
+
cfg.default_remote = cli["default_remote"]
|
|
203
|
+
if "device_name" in cli:
|
|
204
|
+
cfg.device_name = cli["device_name"]
|
|
205
|
+
aliases = raw.get("host_aliases", {})
|
|
206
|
+
if not isinstance(aliases, dict) or not all(
|
|
207
|
+
isinstance(k, str) and isinstance(v, str) for k, v in aliases.items()
|
|
208
|
+
):
|
|
209
|
+
raise ConfigError(f"Invalid [host_aliases] section in {path}")
|
|
210
|
+
cfg.host_aliases = {k.lower(): v.lower() for k, v in aliases.items()}
|
|
211
|
+
try:
|
|
212
|
+
cfg.validate()
|
|
213
|
+
except ConfigError as exc:
|
|
214
|
+
raise ConfigError(f"{path}: {exc.message}", hint=exc.hint) from exc
|
|
215
|
+
return cfg
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
def _toml_str(value: str) -> str:
|
|
219
|
+
# JSON string escapes are a subset of TOML basic-string escapes.
|
|
220
|
+
return json.dumps(value, ensure_ascii=True)
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
def dump_config(cfg: Config) -> str:
|
|
224
|
+
lines = ["# offgit client configuration (no secrets belong here)", ""]
|
|
225
|
+
if cfg.server is not None:
|
|
226
|
+
s = cfg.server
|
|
227
|
+
lines.append("[server]")
|
|
228
|
+
lines.append(f"host = {_toml_str(s.host)}")
|
|
229
|
+
if s.user is not None:
|
|
230
|
+
lines.append(f"user = {_toml_str(s.user)}")
|
|
231
|
+
if s.port is not None:
|
|
232
|
+
lines.append(f"port = {int(s.port)}")
|
|
233
|
+
if s.identity_file is not None:
|
|
234
|
+
lines.append(f"identity_file = {_toml_str(s.identity_file)}")
|
|
235
|
+
lines.append(f"connect_timeout = {int(s.connect_timeout)}")
|
|
236
|
+
lines.append(f"operation_timeout = {int(s.operation_timeout)}")
|
|
237
|
+
lines.append(f"server_binary = {_toml_str(s.server_binary)}")
|
|
238
|
+
lines.append("")
|
|
239
|
+
lines.append("[client]")
|
|
240
|
+
lines.append(f"default_remote = {_toml_str(cfg.default_remote)}")
|
|
241
|
+
lines.append(f"device_name = {_toml_str(cfg.device_name)}")
|
|
242
|
+
lines.append("")
|
|
243
|
+
if cfg.host_aliases:
|
|
244
|
+
lines.append("[host_aliases]")
|
|
245
|
+
for k in sorted(cfg.host_aliases):
|
|
246
|
+
lines.append(f"{_toml_str(k)} = {_toml_str(cfg.host_aliases[k])}")
|
|
247
|
+
lines.append("")
|
|
248
|
+
text = "\n".join(lines)
|
|
249
|
+
tomllib.loads(text) # self-check: our writer must produce valid TOML
|
|
250
|
+
return text
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
def atomic_write_private(path: Path, text: str) -> None:
|
|
254
|
+
"""Write ``text`` to ``path`` atomically with mode 0600 (parent dir 0700 if created)."""
|
|
255
|
+
path.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
|
|
256
|
+
tmp = path.with_name(f".{path.name}.tmp-{os.getpid()}")
|
|
257
|
+
fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC | getattr(os, "O_NOFOLLOW", 0), 0o600)
|
|
258
|
+
try:
|
|
259
|
+
with os.fdopen(fd, "w", encoding="utf-8") as fh:
|
|
260
|
+
fh.write(text)
|
|
261
|
+
fh.flush()
|
|
262
|
+
os.fsync(fh.fileno())
|
|
263
|
+
os.chmod(tmp, 0o600)
|
|
264
|
+
os.replace(tmp, path)
|
|
265
|
+
except BaseException:
|
|
266
|
+
with contextlib.suppress(OSError):
|
|
267
|
+
os.unlink(tmp)
|
|
268
|
+
raise
|
|
269
|
+
dfd = os.open(path.parent, os.O_RDONLY)
|
|
270
|
+
try:
|
|
271
|
+
os.fsync(dfd)
|
|
272
|
+
finally:
|
|
273
|
+
os.close(dfd)
|
|
274
|
+
|
|
275
|
+
|
|
276
|
+
def save_config(cfg: Config, path: Path | None = None) -> Path:
|
|
277
|
+
cfg.validate()
|
|
278
|
+
path = path or cfg.path or config_path()
|
|
279
|
+
atomic_write_private(path, dump_config(cfg))
|
|
280
|
+
cfg.path = path
|
|
281
|
+
return path
|
offgit/errors.py
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
"""Error types and the exit-code contract.
|
|
2
|
+
|
|
3
|
+
Exit codes (stable, documented in README and docs/protocol.md):
|
|
4
|
+
|
|
5
|
+
* 0 success / no-op (``status`` reports dirty files as data, not failure)
|
|
6
|
+
* 1 unexpected internal or local I/O failure
|
|
7
|
+
* 2 usage, configuration, invalid path, wrong directory, not registered
|
|
8
|
+
* 3 connectivity, authentication, protocol, timeout, server-side failure
|
|
9
|
+
* 4 unresolved conflict, or stale compare-and-swap after bounded retries
|
|
10
|
+
* 5 partial or unknown mutation outcome, or recovery required
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
from typing import Any
|
|
16
|
+
|
|
17
|
+
EXIT_OK = 0
|
|
18
|
+
EXIT_INTERNAL = 1
|
|
19
|
+
EXIT_USAGE = 2
|
|
20
|
+
EXIT_CONNECTIVITY = 3
|
|
21
|
+
EXIT_CONFLICT = 4
|
|
22
|
+
EXIT_PARTIAL = 5
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class OffgitError(Exception):
|
|
26
|
+
"""Base error. ``code`` is a stable machine-readable identifier."""
|
|
27
|
+
|
|
28
|
+
exit_code = EXIT_INTERNAL
|
|
29
|
+
default_code = "internal_error"
|
|
30
|
+
|
|
31
|
+
def __init__(
|
|
32
|
+
self,
|
|
33
|
+
message: str,
|
|
34
|
+
*,
|
|
35
|
+
code: str | None = None,
|
|
36
|
+
hint: str | None = None,
|
|
37
|
+
details: dict[str, Any] | None = None,
|
|
38
|
+
) -> None:
|
|
39
|
+
super().__init__(message)
|
|
40
|
+
self.message = message
|
|
41
|
+
self.code = code or self.default_code
|
|
42
|
+
self.hint = hint
|
|
43
|
+
self.details = details or {}
|
|
44
|
+
|
|
45
|
+
def to_dict(self) -> dict[str, Any]:
|
|
46
|
+
data: dict[str, Any] = {"code": self.code, "message": self.message}
|
|
47
|
+
if self.hint:
|
|
48
|
+
data["hint"] = self.hint
|
|
49
|
+
if self.details:
|
|
50
|
+
data["details"] = self.details
|
|
51
|
+
return data
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
class UsageError(OffgitError):
|
|
55
|
+
exit_code = EXIT_USAGE
|
|
56
|
+
default_code = "usage_error"
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
class ConfigError(UsageError):
|
|
60
|
+
default_code = "config_error"
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
class PathError(UsageError):
|
|
64
|
+
default_code = "invalid_path"
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
class RepoError(UsageError):
|
|
68
|
+
default_code = "repository_error"
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
class IdentityError(UsageError):
|
|
72
|
+
default_code = "invalid_remote"
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
class ConnectivityError(OffgitError):
|
|
76
|
+
exit_code = EXIT_CONNECTIVITY
|
|
77
|
+
default_code = "connectivity_error"
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
class ProtocolError(ConnectivityError):
|
|
81
|
+
default_code = "protocol_error"
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
class ServerError(ConnectivityError):
|
|
85
|
+
"""The server answered with a structured error that is not more specific."""
|
|
86
|
+
|
|
87
|
+
default_code = "server_error"
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
class ConflictError(OffgitError):
|
|
91
|
+
exit_code = EXIT_CONFLICT
|
|
92
|
+
default_code = "conflict"
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
class PartialError(OffgitError):
|
|
96
|
+
exit_code = EXIT_PARTIAL
|
|
97
|
+
default_code = "partial_failure"
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
class RecoveryRequired(OffgitError):
|
|
101
|
+
exit_code = EXIT_PARTIAL
|
|
102
|
+
default_code = "recovery_required"
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
class UnsafeLocalFile(PathError):
|
|
106
|
+
"""A local path failed a safety check (symlink, special file, not ignored...)."""
|
|
107
|
+
|
|
108
|
+
default_code = "unsafe_path"
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
class LocalChangedError(OffgitError):
|
|
112
|
+
"""A local file changed while offgit was working on it."""
|
|
113
|
+
|
|
114
|
+
exit_code = EXIT_CONFLICT
|
|
115
|
+
default_code = "local_changed"
|
offgit/gitrepo.py
ADDED
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
"""Thin, read-only wrapper around the ``git`` executable.
|
|
2
|
+
|
|
3
|
+
offgit never edits Git configuration, ignore files, the index or history, and
|
|
4
|
+
never contacts a remote. Paths are passed with ``GIT_LITERAL_PATHSPECS=1`` so
|
|
5
|
+
pathspec magic and globbing never apply.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import os
|
|
11
|
+
import shutil
|
|
12
|
+
import subprocess
|
|
13
|
+
from collections.abc import Iterable
|
|
14
|
+
from dataclasses import dataclass
|
|
15
|
+
|
|
16
|
+
from offgit.errors import ConfigError, RepoError
|
|
17
|
+
|
|
18
|
+
GIT_TIMEOUT = 30
|
|
19
|
+
MAX_GIT_OUTPUT = 8 * 1024 * 1024
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _git_env(literal: bool = True) -> dict[str, str]:
|
|
23
|
+
env = dict(os.environ)
|
|
24
|
+
if literal:
|
|
25
|
+
env["GIT_LITERAL_PATHSPECS"] = "1"
|
|
26
|
+
else:
|
|
27
|
+
env.pop("GIT_LITERAL_PATHSPECS", None)
|
|
28
|
+
env["GIT_TERMINAL_PROMPT"] = "0"
|
|
29
|
+
env["GIT_OPTIONAL_LOCKS"] = "0"
|
|
30
|
+
for var in ("GIT_DIR", "GIT_WORK_TREE", "GIT_INDEX_FILE", "GIT_PREFIX"):
|
|
31
|
+
env.pop(var, None)
|
|
32
|
+
return env
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def git_executable() -> str:
|
|
36
|
+
exe = shutil.which("git")
|
|
37
|
+
if not exe:
|
|
38
|
+
raise ConfigError("git executable not found on PATH", code="git_missing")
|
|
39
|
+
return exe
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def run_git(
|
|
43
|
+
args: list[str],
|
|
44
|
+
cwd: str,
|
|
45
|
+
*,
|
|
46
|
+
input_bytes: bytes | None = None,
|
|
47
|
+
check: bool = True,
|
|
48
|
+
literal: bool = True,
|
|
49
|
+
) -> subprocess.CompletedProcess[bytes]:
|
|
50
|
+
try:
|
|
51
|
+
proc = subprocess.run(
|
|
52
|
+
[git_executable(), "-c", "core.quotepath=off", *args],
|
|
53
|
+
cwd=cwd,
|
|
54
|
+
input=input_bytes,
|
|
55
|
+
stdin=None if input_bytes is not None else subprocess.DEVNULL,
|
|
56
|
+
capture_output=True,
|
|
57
|
+
env=_git_env(literal),
|
|
58
|
+
timeout=GIT_TIMEOUT,
|
|
59
|
+
check=False,
|
|
60
|
+
)
|
|
61
|
+
except subprocess.TimeoutExpired as exc:
|
|
62
|
+
raise RepoError(f"git {args[0]} timed out", code="git_timeout") from exc
|
|
63
|
+
if len(proc.stdout) > MAX_GIT_OUTPUT:
|
|
64
|
+
raise RepoError(f"git {args[0]} produced too much output", code="git_output")
|
|
65
|
+
if check and proc.returncode != 0:
|
|
66
|
+
msg = proc.stderr.decode("utf-8", "replace").strip().splitlines()
|
|
67
|
+
raise RepoError(
|
|
68
|
+
f"git {args[0]} failed: {msg[-1] if msg else 'exit ' + str(proc.returncode)}",
|
|
69
|
+
code="git_failed",
|
|
70
|
+
)
|
|
71
|
+
return proc
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
@dataclass(frozen=True)
|
|
75
|
+
class Worktree:
|
|
76
|
+
root: str # resolved top-level directory
|
|
77
|
+
git_dir: str # absolute per-worktree git dir
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def find_worktree(cwd: str | None = None) -> Worktree:
|
|
81
|
+
"""Return the worktree whose top-level directory is exactly ``cwd``.
|
|
82
|
+
|
|
83
|
+
Never walks up silently: launching from a subdirectory is an error.
|
|
84
|
+
"""
|
|
85
|
+
cwd = cwd or os.getcwd()
|
|
86
|
+
probe = run_git(
|
|
87
|
+
["rev-parse", "--is-bare-repository", "--is-inside-work-tree"], cwd, check=False
|
|
88
|
+
)
|
|
89
|
+
if probe.returncode != 0:
|
|
90
|
+
raise RepoError(
|
|
91
|
+
"Not inside a Git working tree",
|
|
92
|
+
code="not_a_git_repository",
|
|
93
|
+
hint="Run offgit from the top-level directory of a Git clone",
|
|
94
|
+
)
|
|
95
|
+
lines = probe.stdout.decode().split()
|
|
96
|
+
if lines and lines[0] == "true":
|
|
97
|
+
raise RepoError("offgit does not operate on bare repositories", code="bare_repository")
|
|
98
|
+
if len(lines) < 2 or lines[1] != "true":
|
|
99
|
+
raise RepoError(
|
|
100
|
+
"Not inside a Git working tree",
|
|
101
|
+
code="not_a_git_repository",
|
|
102
|
+
hint="Run offgit from the top-level directory of a Git clone",
|
|
103
|
+
)
|
|
104
|
+
out = run_git(["rev-parse", "--show-toplevel", "--absolute-git-dir"], cwd).stdout
|
|
105
|
+
parts = out.decode("utf-8", "surrogateescape").splitlines()
|
|
106
|
+
if len(parts) != 2:
|
|
107
|
+
raise RepoError("Unexpected output from git rev-parse", code="git_output")
|
|
108
|
+
toplevel, git_dir = parts
|
|
109
|
+
real_cwd = os.path.realpath(cwd)
|
|
110
|
+
real_top = os.path.realpath(toplevel)
|
|
111
|
+
if real_cwd != real_top:
|
|
112
|
+
raise RepoError(
|
|
113
|
+
"offgit must be run from the top-level directory of the Git working tree",
|
|
114
|
+
code="not_repository_root",
|
|
115
|
+
hint=f"cd {real_top}",
|
|
116
|
+
details={"root": real_top},
|
|
117
|
+
)
|
|
118
|
+
return Worktree(root=real_top, git_dir=os.path.realpath(git_dir))
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def list_remotes(root: str) -> list[str]:
|
|
122
|
+
out = run_git(["remote"], root).stdout.decode("utf-8", "replace")
|
|
123
|
+
return [r for r in out.splitlines() if r]
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def remote_url(root: str, name: str) -> str:
|
|
127
|
+
"""Return the fetch URL of remote ``name`` (``git remote get-url``; no network)."""
|
|
128
|
+
if not name or name.startswith("-") or "\n" in name:
|
|
129
|
+
raise ConfigError(f"Invalid remote name {name!r}")
|
|
130
|
+
proc = run_git(["remote", "get-url", "--", name], root, check=False)
|
|
131
|
+
if proc.returncode != 0:
|
|
132
|
+
remotes = list_remotes(root)
|
|
133
|
+
hint = (
|
|
134
|
+
f"Available remotes: {', '.join(remotes)}. Select one with --remote NAME"
|
|
135
|
+
if remotes
|
|
136
|
+
else "Add a Git remote (e.g. git remote add origin <url>) first"
|
|
137
|
+
)
|
|
138
|
+
raise RepoError(f"Git remote {name!r} is not configured", code="remote_missing", hint=hint)
|
|
139
|
+
url = proc.stdout.decode("utf-8", "replace").strip()
|
|
140
|
+
if not url or "\n" in url:
|
|
141
|
+
raise RepoError(f"Git remote {name!r} has no single URL", code="remote_missing")
|
|
142
|
+
return url
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def _nul_list(data: bytes) -> list[str]:
|
|
146
|
+
return [p.decode("utf-8", "surrogateescape") for p in data.split(b"\0") if p]
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def ignored_paths(root: str, paths: Iterable[str]) -> set[str]:
|
|
150
|
+
"""Subset of ``paths`` that Git considers ignored (all ignore sources, via git itself).
|
|
151
|
+
|
|
152
|
+
``check-ignore`` does not support ``GIT_LITERAL_PATHSPECS``; it matches each
|
|
153
|
+
pathname literally (no globbing) but would interpret a leading ``:(magic)``.
|
|
154
|
+
Prefixing ``./`` to a path starting with ``:`` disables magic; git echoes
|
|
155
|
+
the input form back. (Always prefixing would break literal ``*`` names.)
|
|
156
|
+
"""
|
|
157
|
+
plist = list(paths)
|
|
158
|
+
if not plist:
|
|
159
|
+
return set()
|
|
160
|
+
payload = b"".join(
|
|
161
|
+
(b"./" if p.startswith(":") else b"") + p.encode("utf-8") + b"\0" for p in plist
|
|
162
|
+
)
|
|
163
|
+
proc = run_git(
|
|
164
|
+
["check-ignore", "-z", "--stdin"], root, input_bytes=payload, check=False, literal=False
|
|
165
|
+
)
|
|
166
|
+
if proc.returncode not in (0, 1):
|
|
167
|
+
msg = proc.stderr.decode("utf-8", "replace").strip()
|
|
168
|
+
raise RepoError(f"git check-ignore failed: {msg}", code="git_failed")
|
|
169
|
+
out = {p[2:] if p.startswith("./:") else p for p in _nul_list(proc.stdout)}
|
|
170
|
+
return out & set(plist)
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def tracked_paths(root: str, paths: Iterable[str]) -> set[str]:
|
|
174
|
+
"""Subset of ``paths`` that are tracked in the index (literal pathspecs)."""
|
|
175
|
+
plist = list(paths)
|
|
176
|
+
if not plist:
|
|
177
|
+
return set()
|
|
178
|
+
out = run_git(["ls-files", "-z", "--cached", "--", *plist], root).stdout
|
|
179
|
+
return set(_nul_list(out)) & set(plist)
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
def ignore_hint(path: str) -> str:
|
|
183
|
+
return (
|
|
184
|
+
f"Add an exact ignore rule, e.g. append '/{path}' to .git/info/exclude (private) "
|
|
185
|
+
f"or .gitignore (shared), then retry. offgit never edits ignore files."
|
|
186
|
+
)
|
offgit/hashing.py
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
"""Content hashing. offgit hashes exact bytes with SHA-256 (no newline/encoding normalization)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import hashlib
|
|
6
|
+
import re
|
|
7
|
+
|
|
8
|
+
SHA256_RE = re.compile(r"^[0-9a-f]{64}$")
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def sha256_hex(data: bytes) -> str:
|
|
12
|
+
return hashlib.sha256(data).hexdigest()
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def is_sha256(value: object) -> bool:
|
|
16
|
+
return isinstance(value, str) and bool(SHA256_RE.match(value))
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def short(digest: str | None, n: int = 12) -> str:
|
|
20
|
+
if not digest:
|
|
21
|
+
return "-"
|
|
22
|
+
return digest[:n] + "…"
|