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/protocol.py ADDED
@@ -0,0 +1,466 @@
1
+ """offgit RPC protocol v1 (shared by client and server).
2
+
3
+ One UTF-8 JSON request document on stdin (terminated by EOF), one UTF-8 JSON
4
+ response document on stdout. Documents are bounded, duplicate keys and
5
+ non-finite numbers are rejected, unexpected fields are rejected, bytes travel
6
+ as strict base64 with SHA-256 + size verification. See docs/protocol.md.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import base64
12
+ import binascii
13
+ import hashlib
14
+ import json
15
+ import re
16
+ import uuid
17
+ from collections.abc import Callable
18
+ from typing import Any
19
+
20
+ from offgit.errors import ProtocolError
21
+ from offgit.hashing import is_sha256, sha256_hex
22
+ from offgit.identity import project_key, validate_canonical
23
+ from offgit.paths import validate_rel_path
24
+
25
+ PROTOCOL_VERSION = 1
26
+ SUPPORTED_VERSIONS = (1,)
27
+
28
+ MIB = 1024 * 1024
29
+ MAX_MESSAGE_BYTES = 64 * MIB # encoded request/response cap (fixed)
30
+ MAX_STDERR_BYTES = 64 * 1024
31
+ DEFAULT_LIMITS: dict[str, int] = {
32
+ "max_file_bytes": 8 * MIB,
33
+ "max_project_bytes": 32 * MIB,
34
+ "max_paths": 256,
35
+ }
36
+ # Hard ceilings: base64(max_project_bytes) plus JSON overhead must fit MAX_MESSAGE_BYTES.
37
+ HARD_LIMITS: dict[str, int] = {
38
+ "max_file_bytes": 16 * MIB,
39
+ "max_project_bytes": 40 * MIB,
40
+ "max_paths": 1024,
41
+ }
42
+ MAX_HISTORY_LIMIT = 1000
43
+ MAX_DEVICE_LEN = 64
44
+
45
+ MUTATING_OPERATIONS = frozenset({"init", "push", "add", "remove", "restore", "settle_request"})
46
+ READ_OPERATIONS = frozenset({"hello", "manifest", "projects", "fetch", "history", "get_file"})
47
+ OPERATIONS = MUTATING_OPERATIONS | READ_OPERATIONS
48
+
49
+
50
+ def clamp_limits(limits: dict[str, int]) -> dict[str, int]:
51
+ out = dict(DEFAULT_LIMITS)
52
+ for key, val in limits.items():
53
+ if key not in HARD_LIMITS:
54
+ raise ValueError(f"unknown limit {key!r}")
55
+ if isinstance(val, bool) or not isinstance(val, int) or val < 1:
56
+ raise ValueError(f"invalid limit {key}={val!r}")
57
+ out[key] = min(val, HARD_LIMITS[key])
58
+ return out
59
+
60
+
61
+ # ---------------------------------------------------------------------------
62
+ # JSON encoding / decoding
63
+
64
+
65
+ def _reject_duplicates(pairs: list[tuple[str, Any]]) -> dict[str, Any]:
66
+ out: dict[str, Any] = {}
67
+ for key, val in pairs:
68
+ if key in out:
69
+ raise ProtocolError(f"duplicate JSON key {key!r}", code="invalid_request")
70
+ out[key] = val
71
+ return out
72
+
73
+
74
+ def _reject_constant(name: str) -> Any:
75
+ raise ProtocolError(f"non-finite number {name} not allowed", code="invalid_request")
76
+
77
+
78
+ def loads_strict(data: bytes, *, max_bytes: int = MAX_MESSAGE_BYTES) -> Any:
79
+ if len(data) > max_bytes:
80
+ raise ProtocolError("message exceeds size limit", code="message_too_large")
81
+ try:
82
+ text = data.decode("utf-8")
83
+ except UnicodeDecodeError as exc:
84
+ raise ProtocolError("message is not valid UTF-8", code="invalid_request") from exc
85
+ try:
86
+ return json.loads(
87
+ text, object_pairs_hook=_reject_duplicates, parse_constant=_reject_constant
88
+ )
89
+ except ProtocolError:
90
+ raise
91
+ except (json.JSONDecodeError, RecursionError) as exc:
92
+ raise ProtocolError(f"malformed JSON: {exc}", code="invalid_request") from exc
93
+
94
+
95
+ def dumps(doc: Any) -> bytes:
96
+ return (
97
+ json.dumps(doc, ensure_ascii=False, separators=(",", ":"), allow_nan=False) + "\n"
98
+ ).encode("utf-8")
99
+
100
+
101
+ def canonical_digest(doc: dict[str, Any]) -> str:
102
+ """Digest of a request for idempotency: everything except the request id."""
103
+ body = {k: v for k, v in doc.items() if k != "request_id"}
104
+ raw = json.dumps(body, sort_keys=True, separators=(",", ":"), ensure_ascii=True)
105
+ return hashlib.sha256(raw.encode("ascii")).hexdigest()
106
+
107
+
108
+ def encode_b64(data: bytes) -> str:
109
+ return base64.b64encode(data).decode("ascii")
110
+
111
+
112
+ _B64_RE = re.compile(r"^[A-Za-z0-9+/]*={0,2}$")
113
+
114
+
115
+ def decode_b64(text: str, *, max_bytes: int) -> bytes:
116
+ if not isinstance(text, str) or len(text) % 4 or not _B64_RE.match(text):
117
+ raise ProtocolError("malformed base64", code="invalid_request")
118
+ if len(text) // 4 * 3 > max_bytes + 3:
119
+ raise ProtocolError("encoded content exceeds the per-file limit", code="limit_exceeded")
120
+ try:
121
+ data = base64.b64decode(text, validate=True)
122
+ except (binascii.Error, ValueError) as exc:
123
+ raise ProtocolError("malformed base64", code="invalid_request") from exc
124
+ if encode_b64(data) != text:
125
+ raise ProtocolError("non-canonical base64", code="invalid_request")
126
+ return data
127
+
128
+
129
+ # ---------------------------------------------------------------------------
130
+ # Field validators
131
+
132
+
133
+ Validator = Callable[[Any, str], Any]
134
+
135
+
136
+ def _bad(where: str, what: str) -> ProtocolError:
137
+ return ProtocolError(f"{where}: {what}", code="invalid_request")
138
+
139
+
140
+ def v_uuid(val: Any, where: str) -> str:
141
+ if not isinstance(val, str):
142
+ raise _bad(where, "expected UUID string")
143
+ try:
144
+ parsed = uuid.UUID(val)
145
+ except ValueError as exc:
146
+ raise _bad(where, "expected UUID string") from exc
147
+ if str(parsed) != val:
148
+ raise _bad(where, "UUID must be lower-case canonical form")
149
+ return val
150
+
151
+
152
+ def v_sha(val: Any, where: str) -> str:
153
+ if not is_sha256(val):
154
+ raise _bad(where, "expected lower-case hex SHA-256")
155
+ return str(val)
156
+
157
+
158
+ def v_opt_sha(val: Any, where: str) -> str | None:
159
+ return None if val is None else v_sha(val, where)
160
+
161
+
162
+ def v_nonneg(val: Any, where: str) -> int:
163
+ if isinstance(val, bool) or not isinstance(val, int) or val < 0 or val > 2**62:
164
+ raise _bad(where, "expected non-negative integer")
165
+ return val
166
+
167
+
168
+ def v_pos(val: Any, where: str) -> int:
169
+ v = v_nonneg(val, where)
170
+ if v < 1:
171
+ raise _bad(where, "expected positive integer")
172
+ return v
173
+
174
+
175
+ def v_opt_nonneg(val: Any, where: str) -> int | None:
176
+ return None if val is None else v_nonneg(val, where)
177
+
178
+
179
+ def v_bool(val: Any, where: str) -> bool:
180
+ if not isinstance(val, bool):
181
+ raise _bad(where, "expected boolean")
182
+ return val
183
+
184
+
185
+ def v_path(val: Any, where: str) -> str:
186
+ if not isinstance(val, str):
187
+ raise _bad(where, "expected path string")
188
+ try:
189
+ return validate_rel_path(val)
190
+ except Exception as exc:
191
+ raise ProtocolError(f"{where}: invalid path", code="invalid_path") from exc
192
+
193
+
194
+ def v_opt_path(val: Any, where: str) -> str | None:
195
+ return None if val is None else v_path(val, where)
196
+
197
+
198
+ def v_device(val: Any, where: str) -> str | None:
199
+ if val is None:
200
+ return None
201
+ if not isinstance(val, str) or not re.match(r"^[A-Za-z0-9._-]{1,64}$", val):
202
+ raise _bad(where, "invalid device label")
203
+ return val
204
+
205
+
206
+ def v_project(val: Any, where: str) -> dict[str, str]:
207
+ obj = _object(val, where, {"canonical_remote": None, "id": None})
208
+ canonical = obj["canonical_remote"]
209
+ if not isinstance(canonical, str):
210
+ raise _bad(where, "canonical_remote must be a string")
211
+ try:
212
+ validate_canonical(canonical)
213
+ except Exception as exc:
214
+ raise ProtocolError(f"{where}: invalid canonical identity", code="invalid_project") from exc
215
+ pid = v_sha(obj["id"], f"{where}.id")
216
+ if project_key(canonical) != pid:
217
+ raise ProtocolError(f"{where}: project id does not match identity", code="invalid_project")
218
+ return {"canonical_remote": canonical, "id": pid}
219
+
220
+
221
+ def _object(val: Any, where: str, fields: dict[str, Any], optional: set[str] | None = None) -> dict:
222
+ if not isinstance(val, dict):
223
+ raise _bad(where, "expected object")
224
+ optional = optional or set()
225
+ unknown = set(val) - set(fields)
226
+ if unknown:
227
+ raise _bad(where, f"unexpected fields {sorted(unknown)}")
228
+ missing = set(fields) - set(val) - optional
229
+ if missing:
230
+ raise _bad(where, f"missing fields {sorted(missing)}")
231
+ return val
232
+
233
+
234
+ def _list(val: Any, where: str, max_items: int) -> list[Any]:
235
+ if not isinstance(val, list):
236
+ raise _bad(where, "expected list")
237
+ if len(val) > max_items:
238
+ raise ProtocolError(f"{where}: too many items", code="limit_exceeded")
239
+ return val
240
+
241
+
242
+ def decode_content(item: Any, where: str, limits: dict[str, int], *, with_expected: bool) -> dict:
243
+ """Validate a ``{path, sha256, size, data_b64[, expected_sha256]}`` object and decode it."""
244
+ fields = {"path": None, "sha256": None, "size": None, "data_b64": None}
245
+ if with_expected:
246
+ fields["expected_sha256"] = None
247
+ obj = _object(item, where, fields)
248
+ path = v_path(obj["path"], f"{where}.path")
249
+ digest = v_sha(obj["sha256"], f"{where}.sha256")
250
+ size = v_nonneg(obj["size"], f"{where}.size")
251
+ if size > limits["max_file_bytes"]:
252
+ raise ProtocolError(f"{where}: {path} exceeds the per-file limit", code="limit_exceeded")
253
+ data = decode_b64(obj["data_b64"], max_bytes=limits["max_file_bytes"])
254
+ if len(data) != size:
255
+ raise ProtocolError(f"{where}: {path} size mismatch", code="integrity_error")
256
+ if sha256_hex(data) != digest:
257
+ raise ProtocolError(f"{where}: {path} hash mismatch", code="integrity_error")
258
+ out = {"path": path, "sha256": digest, "size": size, "data": data}
259
+ if with_expected:
260
+ out["expected_sha256"] = v_opt_sha(obj["expected_sha256"], f"{where}.expected_sha256")
261
+ return out
262
+
263
+
264
+ def _paths_unique(paths: list[str], where: str) -> None:
265
+ if len(set(paths)) != len(paths):
266
+ raise _bad(where, "duplicate paths")
267
+
268
+
269
+ # ---------------------------------------------------------------------------
270
+ # Request validation (server side; the client constructs the same shapes)
271
+
272
+ _ENVELOPE = {"version", "request_id", "operation", "device", "client_version"}
273
+ _MUTATION_BASE = {"project": v_project, "expected_server_epoch": v_uuid}
274
+
275
+ _OP_FIELDS: dict[str, dict[str, Validator]] = {
276
+ "hello": {},
277
+ "projects": {},
278
+ "manifest": {"project": v_project},
279
+ "fetch": {"project": v_project, "expected_revision": v_opt_nonneg, "paths": lambda v, w: v},
280
+ "history": {"project": v_project, "path": v_opt_path, "limit": v_pos},
281
+ "get_file": {"project": v_project, "revision": v_pos, "path": v_path},
282
+ "init": {**_MUTATION_BASE, "files": lambda v, w: v},
283
+ "push": {**_MUTATION_BASE, "expected_revision": v_nonneg, "changes": lambda v, w: v},
284
+ "add": {**_MUTATION_BASE, "expected_revision": v_nonneg, "files": lambda v, w: v},
285
+ "remove": {**_MUTATION_BASE, "expected_revision": v_nonneg, "paths": lambda v, w: v},
286
+ "restore": {
287
+ **_MUTATION_BASE,
288
+ "expected_revision": v_nonneg,
289
+ "path": v_path,
290
+ "revision": v_pos,
291
+ },
292
+ "settle_request": {**_MUTATION_BASE, "target_request_id": v_uuid},
293
+ }
294
+
295
+
296
+ def validate_request(doc: Any, limits: dict[str, int]) -> dict[str, Any]:
297
+ """Validate an untrusted request document; returns a normalized request dict.
298
+
299
+ Content items are decoded and verified (``data`` holds bytes).
300
+ """
301
+ if not isinstance(doc, dict):
302
+ raise _bad("request", "expected JSON object")
303
+ version = doc.get("version")
304
+ if isinstance(version, bool) or not isinstance(version, int):
305
+ raise _bad("request.version", "expected integer")
306
+ if version not in SUPPORTED_VERSIONS:
307
+ raise ProtocolError(
308
+ f"unsupported protocol version {version}",
309
+ code="unsupported_version",
310
+ details={"supported": list(SUPPORTED_VERSIONS)},
311
+ )
312
+ op = doc.get("operation")
313
+ if op not in OPERATIONS:
314
+ raise ProtocolError(f"unknown operation {op!r}", code="unknown_operation")
315
+ spec = _OP_FIELDS[op]
316
+ allowed = _ENVELOPE | set(spec)
317
+ unknown = set(doc) - allowed
318
+ if unknown:
319
+ raise _bad("request", f"unexpected fields {sorted(unknown)}")
320
+ missing = ({"version", "request_id", "operation"} | set(spec)) - set(doc)
321
+ if missing:
322
+ raise _bad("request", f"missing fields {sorted(missing)}")
323
+ out: dict[str, Any] = {
324
+ "version": version,
325
+ "request_id": v_uuid(doc["request_id"], "request.request_id"),
326
+ "operation": op,
327
+ "device": v_device(doc.get("device"), "request.device"),
328
+ }
329
+ cv = doc.get("client_version")
330
+ if cv is not None and (not isinstance(cv, str) or len(cv) > 64):
331
+ raise _bad("request.client_version", "invalid")
332
+ for name, validator in spec.items():
333
+ out[name] = validator(doc[name], f"request.{name}")
334
+
335
+ max_paths = limits["max_paths"]
336
+ if op in ("init", "add"):
337
+ items = _list(doc["files"], "request.files", max_paths)
338
+ if not items:
339
+ raise _bad("request.files", "at least one file is required")
340
+ out["files"] = [
341
+ decode_content(it, f"request.files[{i}]", limits, with_expected=False)
342
+ for i, it in enumerate(items)
343
+ ]
344
+ _paths_unique([f["path"] for f in out["files"]], "request.files")
345
+ elif op == "push":
346
+ items = _list(doc["changes"], "request.changes", max_paths)
347
+ if not items:
348
+ raise _bad("request.changes", "at least one change is required")
349
+ out["changes"] = [
350
+ decode_content(it, f"request.changes[{i}]", limits, with_expected=True)
351
+ for i, it in enumerate(items)
352
+ ]
353
+ _paths_unique([c["path"] for c in out["changes"]], "request.changes")
354
+ elif op == "remove":
355
+ items = _list(doc["paths"], "request.paths", max_paths)
356
+ if not items:
357
+ raise _bad("request.paths", "at least one path is required")
358
+ out["paths"] = [v_path(p, f"request.paths[{i}]") for i, p in enumerate(items)]
359
+ _paths_unique(out["paths"], "request.paths")
360
+ elif op == "fetch":
361
+ if doc["paths"] is None:
362
+ out["paths"] = None
363
+ else:
364
+ items = _list(doc["paths"], "request.paths", max_paths)
365
+ out["paths"] = [v_path(p, f"request.paths[{i}]") for i, p in enumerate(items)]
366
+ _paths_unique(out["paths"], "request.paths")
367
+ elif op == "history" and out["limit"] > MAX_HISTORY_LIMIT:
368
+ raise ProtocolError("history limit too large", code="limit_exceeded")
369
+ return out
370
+
371
+
372
+ # ---------------------------------------------------------------------------
373
+ # Response helpers
374
+
375
+
376
+ def ok_response(request_id: str | None, server: dict[str, Any], result: Any) -> dict[str, Any]:
377
+ return {
378
+ "version": PROTOCOL_VERSION,
379
+ "request_id": request_id,
380
+ "ok": True,
381
+ "server": server,
382
+ "result": result,
383
+ }
384
+
385
+
386
+ def error_response(
387
+ request_id: str | None,
388
+ server: dict[str, Any] | None,
389
+ code: str,
390
+ message: str,
391
+ details: dict[str, Any] | None = None,
392
+ ) -> dict[str, Any]:
393
+ return {
394
+ "version": PROTOCOL_VERSION,
395
+ "request_id": request_id,
396
+ "ok": False,
397
+ "server": server,
398
+ "error": {"code": code, "message": message, "details": details or {}},
399
+ }
400
+
401
+
402
+ def validate_manifest_entries(
403
+ entries: Any, limits: dict[str, int], where: str
404
+ ) -> list[dict[str, Any]]:
405
+ """Client-side validation of a manifest list returned by the server."""
406
+ items = _list(entries, where, HARD_LIMITS["max_paths"] * 4)
407
+ out: list[dict[str, Any]] = []
408
+ for i, it in enumerate(items):
409
+ w = f"{where}[{i}]"
410
+ obj = _object(
411
+ it,
412
+ w,
413
+ {
414
+ "path": None,
415
+ "sha256": None,
416
+ "size": None,
417
+ "registered": None,
418
+ "changed_revision": None,
419
+ "changed_at": None,
420
+ },
421
+ )
422
+ out.append(
423
+ {
424
+ "path": v_path(obj["path"], f"{w}.path"),
425
+ "sha256": v_sha(obj["sha256"], f"{w}.sha256"),
426
+ "size": v_nonneg(obj["size"], f"{w}.size"),
427
+ "registered": v_bool(obj["registered"], f"{w}.registered"),
428
+ "changed_revision": v_nonneg(obj["changed_revision"], f"{w}.changed_revision"),
429
+ "changed_at": obj["changed_at"] if isinstance(obj["changed_at"], str) else None,
430
+ }
431
+ )
432
+ _paths_unique([e["path"] for e in out], where)
433
+ return out
434
+
435
+
436
+ def validate_server_block(val: Any) -> dict[str, Any]:
437
+ obj = _object(val, "response.server", {"id": None, "epoch": None, "version": None})
438
+ v_uuid(obj["id"], "response.server.id")
439
+ v_uuid(obj["epoch"], "response.server.epoch")
440
+ if not isinstance(obj["version"], str):
441
+ raise ProtocolError("response.server.version: expected string")
442
+ return obj
443
+
444
+
445
+ def validate_response_envelope(doc: Any, request_id: str) -> dict[str, Any]:
446
+ if not isinstance(doc, dict):
447
+ raise ProtocolError("response is not a JSON object")
448
+ ok = doc.get("ok")
449
+ expected = {"version", "request_id", "ok", "server", "result" if ok is True else "error"}
450
+ if set(doc) != expected:
451
+ raise ProtocolError("response has unexpected shape")
452
+ if doc["version"] != PROTOCOL_VERSION:
453
+ raise ProtocolError(f"server answered with protocol version {doc['version']!r}")
454
+ if doc["request_id"] not in (request_id, None):
455
+ raise ProtocolError("response request_id does not match request")
456
+ if ok is True:
457
+ validate_server_block(doc["server"])
458
+ if not isinstance(doc["result"], dict):
459
+ raise ProtocolError("response result must be an object")
460
+ else:
461
+ if doc["server"] is not None:
462
+ validate_server_block(doc["server"])
463
+ err = doc["error"]
464
+ if not isinstance(err, dict) or not isinstance(err.get("code"), str):
465
+ raise ProtocolError("malformed error response")
466
+ return doc
offgit/reconcile.py ADDED
@@ -0,0 +1,169 @@
1
+ """Three-way reconciliation planner (pure functions, no I/O).
2
+
3
+ B = last verified common base in this worktree (or unknown),
4
+ L = current local hash (or missing), R = authoritative server hash (or unregistered).
5
+
6
+ | Condition | push | pull | sync | status |
7
+ |---------------------------|-----------------|------------------|----------|--------------|
8
+ | L = R | no-op, base:=R | no-op, base:=R | no-op | in sync |
9
+ | L != B, R = B | upload L | keep, report | upload | local ahead |
10
+ | L = B, R != B | keep, report | download R | download | remote ahead |
11
+ | L != B, R != B, L != R | conflict | conflict | conflict | conflict |
12
+
13
+ Unknown B: L missing -> download on pull/sync; L = R -> adopt; L != R -> conflict.
14
+ Missing L is never a deletion. Mtimes are never consulted.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ from dataclasses import dataclass, field
20
+ from enum import StrEnum
21
+ from typing import Any
22
+
23
+ from offgit.local_state import FileBase
24
+
25
+
26
+ class Kind(StrEnum):
27
+ IN_SYNC = "in_sync"
28
+ LOCAL_AHEAD = "local_ahead"
29
+ REMOTE_AHEAD = "remote_ahead"
30
+ CONFLICT = "conflict"
31
+ MISSING = "missing" # registered on server, absent locally
32
+ UNREGISTERED = "unregistered" # removed on server; local untouched
33
+ UNREGISTERED_MODIFIED = "unregistered_modified"
34
+ UNSAFE = "unsafe"
35
+
36
+
37
+ @dataclass
38
+ class Observation:
39
+ path: str
40
+ exists: bool
41
+ sha256: str | None = None
42
+ size: int | None = None
43
+ data: bytes | None = None
44
+ unsafe: str | None = None
45
+
46
+
47
+ @dataclass
48
+ class Remote:
49
+ path: str
50
+ sha256: str
51
+ size: int
52
+ registered: bool
53
+ changed_revision: int = 0
54
+
55
+ @classmethod
56
+ def from_entry(cls, e: dict[str, Any]) -> Remote:
57
+ return cls(e["path"], e["sha256"], e["size"], e["registered"], e.get("changed_revision", 0))
58
+
59
+
60
+ @dataclass
61
+ class FileStatus:
62
+ path: str
63
+ kind: Kind
64
+ base: str | None
65
+ local: str | None
66
+ remote: str | None
67
+ local_exists: bool
68
+ remote_size: int | None = None
69
+ detail: str | None = None
70
+
71
+ def to_dict(self) -> dict[str, Any]:
72
+ return {
73
+ "path": self.path,
74
+ "state": self.kind.value,
75
+ "base_sha256": self.base,
76
+ "local_sha256": self.local,
77
+ "remote_sha256": self.remote,
78
+ "local_exists": self.local_exists,
79
+ "remote_size": self.remote_size,
80
+ "detail": self.detail,
81
+ }
82
+
83
+
84
+ def classify(
85
+ path: str, base: FileBase | None, local: Observation, remote: Remote | None
86
+ ) -> FileStatus:
87
+ b = base.base_sha256 if base is not None else None
88
+ lh = local.sha256 if local.exists else None
89
+ if remote is None or not remote.registered:
90
+ if local.unsafe is None and local.exists and b is not None and lh != b:
91
+ kind = Kind.UNREGISTERED_MODIFIED
92
+ else:
93
+ kind = Kind.UNREGISTERED
94
+ return FileStatus(path, kind, b, lh, None, local.exists)
95
+ r = remote.sha256
96
+ fs = FileStatus(path, Kind.IN_SYNC, b, lh, r, local.exists, remote.size)
97
+ if local.unsafe is not None:
98
+ fs.kind, fs.detail = Kind.UNSAFE, local.unsafe
99
+ return fs
100
+ if not local.exists:
101
+ fs.kind = Kind.MISSING
102
+ return fs
103
+ if lh == r:
104
+ fs.kind = Kind.IN_SYNC
105
+ elif b is None:
106
+ fs.kind = Kind.CONFLICT
107
+ fs.detail = "no common base: local file differs from the server copy"
108
+ elif lh != b and r == b:
109
+ fs.kind = Kind.LOCAL_AHEAD
110
+ elif lh == b and r != b:
111
+ fs.kind = Kind.REMOTE_AHEAD
112
+ else:
113
+ fs.kind = Kind.CONFLICT
114
+ fs.detail = "changed locally and on the server"
115
+ return fs
116
+
117
+
118
+ @dataclass
119
+ class Plan:
120
+ statuses: list[FileStatus]
121
+ uploads: list[FileStatus] = field(default_factory=list)
122
+ downloads: list[FileStatus] = field(default_factory=list)
123
+ adopt: list[FileStatus] = field(default_factory=list) # L == R, base update only
124
+ skipped: list[FileStatus] = field(default_factory=list) # opposite direction / missing
125
+ conflicts: list[FileStatus] = field(default_factory=list)
126
+ unsafe: list[FileStatus] = field(default_factory=list)
127
+ unregistered: list[FileStatus] = field(default_factory=list)
128
+ forced: list[FileStatus] = field(default_factory=list) # explicit resolutions
129
+
130
+ @property
131
+ def blocked(self) -> bool:
132
+ return bool(self.conflicts or self.unsafe)
133
+
134
+
135
+ def make_plan(
136
+ statuses: list[FileStatus],
137
+ *,
138
+ direction: str,
139
+ prefer_local: set[str] | None = None,
140
+ prefer_remote: set[str] | None = None,
141
+ ) -> Plan:
142
+ """Build an operation plan. ``direction`` is ``push``, ``pull`` or ``sync``."""
143
+ prefer_local = prefer_local or set()
144
+ prefer_remote = prefer_remote or set()
145
+ up = direction in ("push", "sync")
146
+ down = direction in ("pull", "sync")
147
+ plan = Plan(statuses=statuses)
148
+ for s in statuses:
149
+ if s.kind is Kind.IN_SYNC:
150
+ if s.base != s.remote:
151
+ plan.adopt.append(s)
152
+ elif s.kind is Kind.LOCAL_AHEAD:
153
+ (plan.uploads if up else plan.skipped).append(s)
154
+ elif s.kind is Kind.REMOTE_AHEAD or s.kind is Kind.MISSING:
155
+ (plan.downloads if down else plan.skipped).append(s)
156
+ elif s.kind is Kind.CONFLICT:
157
+ if s.path in prefer_local and up:
158
+ plan.uploads.append(s)
159
+ plan.forced.append(s)
160
+ elif s.path in prefer_remote and down:
161
+ plan.downloads.append(s)
162
+ plan.forced.append(s)
163
+ else:
164
+ plan.conflicts.append(s)
165
+ elif s.kind is Kind.UNSAFE:
166
+ plan.unsafe.append(s)
167
+ else:
168
+ plan.unregistered.append(s)
169
+ return plan
@@ -0,0 +1 @@
1
+ """offgit server: authoritative SQLite store, SSH-launched RPC, admin tooling."""