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/client.py ADDED
@@ -0,0 +1,1636 @@
1
+ """Client operations: init, push, pull, sync, status, add, remove, diff, history,
2
+ restore, rebaseline, list, projects, doctor.
3
+
4
+ Each operation returns a :class:`~offgit.output.Report`. Errors that abort an
5
+ operation before anything happened are raised as :class:`OffgitError`.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import difflib
11
+ import os
12
+ import shutil
13
+ import time
14
+ from collections.abc import Callable, Iterable
15
+ from dataclasses import dataclass
16
+ from pathlib import Path
17
+ from typing import Any
18
+
19
+ from offgit import gitrepo
20
+ from offgit.config import Config
21
+ from offgit.errors import (
22
+ EXIT_CONFLICT,
23
+ EXIT_CONNECTIVITY,
24
+ EXIT_PARTIAL,
25
+ EXIT_USAGE,
26
+ ConflictError,
27
+ LocalChangedError,
28
+ OffgitError,
29
+ PartialError,
30
+ RecoveryRequired,
31
+ RepoError,
32
+ UnsafeLocalFile,
33
+ UsageError,
34
+ )
35
+ from offgit.hashing import sha256_hex, short
36
+ from offgit.identity import ProjectIdentity, identity_from_url, redact_url
37
+ from offgit.local_state import FileBase, LocalStore, State, utcnow
38
+ from offgit.output import Report
39
+ from offgit.paths import Root, check_collisions, make_temp_name, normalize_user_path
40
+ from offgit.protocol import (
41
+ DEFAULT_LIMITS,
42
+ HARD_LIMITS,
43
+ decode_b64,
44
+ encode_b64,
45
+ validate_manifest_entries,
46
+ )
47
+ from offgit.reconcile import FileStatus, Kind, Observation, Plan, Remote, classify, make_plan
48
+ from offgit.transport import RemoteError, RpcClient, SSHTransport, Transport, TransportError
49
+
50
+ MAX_CAS_ATTEMPTS = 3
51
+ Confirm = Callable[[str], bool]
52
+
53
+
54
+ # ---------------------------------------------------------------------------
55
+ # context
56
+
57
+
58
+ @dataclass
59
+ class Context:
60
+ cfg: Config
61
+ worktree: gitrepo.Worktree
62
+ remote_name: str
63
+ identity: ProjectIdentity
64
+ local: LocalStore
65
+ rpc: RpcClient
66
+ server_label: str
67
+ started: float
68
+
69
+ def report(self, command: str) -> Report:
70
+ return Report(command=command, repository=self.identity.canonical, server=self.server_label)
71
+
72
+
73
+ def make_rpc(cfg: Config, transport: Transport | None = None) -> tuple[RpcClient, str]:
74
+ server = cfg.require_server()
75
+ transport = transport or SSHTransport(server)
76
+ return (
77
+ RpcClient(transport, device=cfg.device_name, timeout=float(server.operation_timeout)),
78
+ transport.describe(),
79
+ )
80
+
81
+
82
+ def open_context(
83
+ cfg: Config,
84
+ *,
85
+ cwd: str | None = None,
86
+ remote: str | None = None,
87
+ transport: Transport | None = None,
88
+ ) -> Context:
89
+ wt = gitrepo.find_worktree(cwd)
90
+ local = LocalStore(wt.git_dir)
91
+ state = local.load()
92
+ stored = local.load_settings().get("remote_name")
93
+ remote_name = remote or (state.remote_name if state else None) or stored or cfg.default_remote
94
+ url = gitrepo.remote_url(wt.root, remote_name)
95
+ identity = identity_from_url(url, cfg.host_aliases)
96
+ if state is not None and state.project_id != identity.project_id:
97
+ raise RepoError(
98
+ f"Git remote {remote_name!r} now identifies {identity.canonical}, but this worktree's "
99
+ f"offgit state belongs to {state.canonical_remote}",
100
+ code="remote_changed",
101
+ hint=(
102
+ "If you switched remotes by mistake, restore the old URL or pass --remote. If the "
103
+ f"repository was renamed, move {local.state_path} aside and ask the server admin to "
104
+ "migrate the project (docs/server-setup.md#renames). offgit never merges identities."
105
+ ),
106
+ details={"state_remote": state.canonical_remote, "current_remote": identity.canonical},
107
+ )
108
+ rpc, label = make_rpc(cfg, transport)
109
+ return Context(
110
+ cfg=cfg,
111
+ worktree=wt,
112
+ remote_name=remote_name,
113
+ identity=identity,
114
+ local=local,
115
+ rpc=rpc,
116
+ server_label=f"{cfg.require_server().host} ({'SSH' if transport is None else label})",
117
+ started=time.monotonic(),
118
+ )
119
+
120
+
121
+ def _project(ctx: Context) -> dict[str, str]:
122
+ return {"canonical_remote": ctx.identity.canonical, "id": ctx.identity.project_id}
123
+
124
+
125
+ # ---------------------------------------------------------------------------
126
+ # remote snapshot
127
+
128
+
129
+ @dataclass
130
+ class RemoteView:
131
+ exists: bool
132
+ revision: int
133
+ entries: dict[str, Remote]
134
+ server_id: str
135
+ server_epoch: str
136
+ limits: dict[str, int]
137
+ backup: dict[str, Any]
138
+
139
+ @property
140
+ def registered(self) -> dict[str, Remote]:
141
+ return {p: e for p, e in self.entries.items() if e.registered}
142
+
143
+
144
+ def _limits(raw: Any) -> dict[str, int]:
145
+ out = dict(DEFAULT_LIMITS)
146
+ if isinstance(raw, dict):
147
+ for k, v in raw.items():
148
+ if k in HARD_LIMITS and isinstance(v, int) and not isinstance(v, bool) and v > 0:
149
+ out[k] = min(v, HARD_LIMITS[k])
150
+ return out
151
+
152
+
153
+ def fetch_view(ctx: Context) -> RemoteView:
154
+ res = ctx.rpc.call("manifest", project=_project(ctx))
155
+ limits = _limits(res.get("limits"))
156
+ entries = validate_manifest_entries(res.get("manifest", []), limits, "manifest")
157
+ server = ctx.rpc.last_server or {}
158
+ rev = res.get("revision")
159
+ if not isinstance(rev, int) or isinstance(rev, bool) or rev < 0:
160
+ raise TransportError("invalid revision in server response", maybe_sent=False)
161
+ return RemoteView(
162
+ exists=bool(res.get("exists")),
163
+ revision=rev,
164
+ entries={e["path"]: Remote.from_entry(e) for e in entries},
165
+ server_id=server.get("id", ""),
166
+ server_epoch=server.get("epoch", ""),
167
+ limits=limits,
168
+ backup=backup if isinstance(backup := res.get("backup"), dict) else {},
169
+ )
170
+
171
+
172
+ def require_project(ctx: Context, view: RemoteView) -> None:
173
+ if not view.exists:
174
+ raise UsageError(
175
+ f"{ctx.identity.canonical} is not registered on the server",
176
+ code="project_not_found",
177
+ hint="Register files once with: offgit init -f FILE...",
178
+ )
179
+
180
+
181
+ def check_epoch(ctx: Context, state: State | None, view: RemoteView) -> None:
182
+ if state is None or state.server_epoch is None:
183
+ return
184
+ if state.server_id != view.server_id or state.server_epoch != view.server_epoch:
185
+ raise RecoveryRequired(
186
+ "The server's identity or epoch changed since this worktree last synchronized "
187
+ "(server restored from backup, reset, or replaced)",
188
+ code="server_epoch_changed",
189
+ hint="Run 'offgit rebaseline' (keeps local files, re-verifies bases, never pushes)",
190
+ details={
191
+ "state_server_id": state.server_id,
192
+ "state_epoch": state.server_epoch,
193
+ "server_id": view.server_id,
194
+ "server_epoch": view.server_epoch,
195
+ },
196
+ )
197
+
198
+
199
+ # ---------------------------------------------------------------------------
200
+ # local observation
201
+
202
+
203
+ def observe(
204
+ ctx: Context, paths: Iterable[str], *, max_bytes: int, git_checks: bool = True
205
+ ) -> dict[str, Observation]:
206
+ plist = sorted(set(paths))
207
+ ignored = gitrepo.ignored_paths(ctx.worktree.root, plist) if git_checks else set(plist)
208
+ tracked = gitrepo.tracked_paths(ctx.worktree.root, plist) if git_checks else set()
209
+ out: dict[str, Observation] = {}
210
+ with Root(ctx.worktree.root) as root:
211
+ for p in plist:
212
+ if p in tracked:
213
+ out[p] = Observation(
214
+ p, exists=True, unsafe="tracked by Git (offgit only syncs ignored files)"
215
+ )
216
+ continue
217
+ try:
218
+ lf = root.inspect(p, max_bytes=max_bytes)
219
+ except UnsafeLocalFile as exc:
220
+ out[p] = Observation(p, exists=True, unsafe=exc.message.split(": ", 1)[-1])
221
+ continue
222
+ if p not in ignored:
223
+ out[p] = Observation(
224
+ p,
225
+ exists=lf.exists,
226
+ sha256=lf.sha256,
227
+ size=lf.size,
228
+ data=lf.data,
229
+ unsafe="not ignored by Git; " + gitrepo.ignore_hint(p),
230
+ )
231
+ continue
232
+ out[p] = Observation(p, exists=lf.exists, sha256=lf.sha256, size=lf.size, data=lf.data)
233
+ return out
234
+
235
+
236
+ def compute_statuses(
237
+ ctx: Context, state: State | None, view: RemoteView
238
+ ) -> tuple[list[FileStatus], dict[str, Observation]]:
239
+ paths = set(view.registered) | set(state.files if state else {})
240
+ obs = observe(ctx, paths, max_bytes=view.limits["max_file_bytes"])
241
+ statuses = []
242
+ for p in sorted(paths):
243
+ base = state.files.get(p) if state else None
244
+ statuses.append(classify(p, base, obs[p], view.entries.get(p)))
245
+ return statuses, obs
246
+
247
+
248
+ # ---------------------------------------------------------------------------
249
+ # pending mutations (unknown outcomes)
250
+
251
+
252
+ def _pending_record(
253
+ ctx: Context,
254
+ request: dict[str, Any],
255
+ view_epoch: str,
256
+ server_id: str,
257
+ set_bases: dict[str, str],
258
+ drop_bases: list[str],
259
+ ) -> dict[str, Any]:
260
+ return {
261
+ "request_id": request["request_id"],
262
+ "operation": request["operation"],
263
+ "project_id": ctx.identity.project_id,
264
+ "canonical_remote": ctx.identity.canonical,
265
+ "remote_name": ctx.remote_name,
266
+ "server_id": server_id,
267
+ "server_epoch": view_epoch,
268
+ "expected_revision": request.get("expected_revision"),
269
+ "set_bases": set_bases,
270
+ "drop_bases": drop_bases,
271
+ "created_at": utcnow(),
272
+ }
273
+
274
+
275
+ def _apply_commit(
276
+ ctx: Context, state: State | None, pending: dict[str, Any], revision: int
277
+ ) -> State:
278
+ if state is None:
279
+ state = State(
280
+ project_id=ctx.identity.project_id,
281
+ canonical_remote=ctx.identity.canonical,
282
+ remote_name=ctx.remote_name,
283
+ )
284
+ state.server_id = pending["server_id"]
285
+ state.server_epoch = pending["server_epoch"]
286
+ for path, sha in pending.get("set_bases", {}).items():
287
+ state.files[path] = FileBase(sha, True, revision)
288
+ for path in pending.get("drop_bases", []):
289
+ state.files.pop(path, None)
290
+ state.last_seen_revision = max(state.last_seen_revision, revision)
291
+ return state
292
+
293
+
294
+ def settle_pending(ctx: Context, state: State | None, report: Report) -> State | None:
295
+ pending = ctx.local.load_pending()
296
+ if pending is None:
297
+ return state
298
+ if pending.get("project_id") != ctx.identity.project_id:
299
+ raise RecoveryRequired(
300
+ "A pending operation for a different project is recorded in this worktree",
301
+ code="pending_mismatch",
302
+ hint=f"Inspect and remove {ctx.local.pending_path}",
303
+ )
304
+ try:
305
+ res = ctx.rpc.call(
306
+ "settle_request",
307
+ project=_project(ctx),
308
+ expected_server_epoch=pending["server_epoch"],
309
+ target_request_id=pending["request_id"],
310
+ )
311
+ except RemoteError as exc:
312
+ if exc.code == "epoch_mismatch":
313
+ raise RecoveryRequired(
314
+ "An interrupted operation cannot be settled because the server epoch changed",
315
+ code="server_epoch_changed",
316
+ hint="Run 'offgit rebaseline'",
317
+ ) from exc
318
+ raise
319
+ if res.get("status") == "committed":
320
+ resp = res.get("response") or {}
321
+ revision = int(resp.get("revision", 0))
322
+ state = _apply_commit(ctx, state, pending, revision)
323
+ ctx.local.save(state)
324
+ report.warnings.append(
325
+ f"Recovered interrupted {pending['operation']}: it was committed as revision {revision}"
326
+ )
327
+ else:
328
+ report.warnings.append(
329
+ f"Recovered interrupted {pending['operation']}: it was not committed (no change on server)"
330
+ )
331
+ ctx.local.clear_pending()
332
+ return state
333
+
334
+
335
+ def send_mutation(
336
+ ctx: Context,
337
+ state: State | None,
338
+ request: dict[str, Any],
339
+ record: dict[str, Any],
340
+ ) -> tuple[dict[str, Any], State]:
341
+ """Send a mutation with a durable pending record; resolve unknown outcomes."""
342
+ ctx.local.write_pending(record)
343
+ try:
344
+ result = ctx.rpc.send(request)
345
+ except RemoteError:
346
+ ctx.local.clear_pending() # structured error => definitely not committed
347
+ raise
348
+ except TransportError as exc:
349
+ # Outcome unknown: try once to settle it right away.
350
+ try:
351
+ settled = ctx.rpc.call(
352
+ "settle_request",
353
+ project=_project(ctx),
354
+ expected_server_epoch=record["server_epoch"],
355
+ target_request_id=request["request_id"],
356
+ )
357
+ except OffgitError:
358
+ raise PartialError(
359
+ f"Outcome of {request['operation']} is unknown: {exc.message}",
360
+ code="outcome_unknown",
361
+ hint="Nothing local was changed. Re-run any offgit command when the server is "
362
+ "reachable; offgit will settle the interrupted request first.",
363
+ ) from exc
364
+ if settled.get("status") != "committed":
365
+ ctx.local.clear_pending()
366
+ raise
367
+ result = settled.get("response") or {}
368
+ revision = int(result.get("revision", 0))
369
+ state = _apply_commit(ctx, state, record, revision)
370
+ ctx.local.save(state)
371
+ ctx.local.clear_pending()
372
+ return result, state
373
+
374
+
375
+ # ---------------------------------------------------------------------------
376
+ # pull journal (staged downloads)
377
+
378
+
379
+ def recover_journals(ctx: Context, state: State | None, report: Report) -> State | None:
380
+ for op_dir, journal in ctx.local.open_journals():
381
+ state = _recover_one(ctx, state, op_dir, journal, report)
382
+ return state
383
+
384
+
385
+ def _recover_one(
386
+ ctx: Context, state: State | None, op_dir: Path, journal: dict[str, Any], report: Report
387
+ ) -> State | None:
388
+ if journal.get("status") == "corrupt":
389
+ raise RecoveryRequired(
390
+ f"A recovery journal is unreadable: {op_dir}",
391
+ code="journal_corrupt",
392
+ hint="Inspect the directory (it holds pre-write copies of your files), then move it aside",
393
+ )
394
+ same_epoch = state is not None and journal.get("server_epoch") == state.server_epoch
395
+ keep = bool(journal.get("keep"))
396
+ unresolved = []
397
+ with Root(ctx.worktree.root) as root:
398
+ for e in journal.get("entries", []):
399
+ path = e["path"]
400
+ if e.get("temp_name"):
401
+ root.remove_temp(path, e["temp_name"])
402
+ try:
403
+ lf = root.inspect(path, max_bytes=HARD_LIMITS["max_file_bytes"])
404
+ except (UnsafeLocalFile, LocalChangedError):
405
+ unresolved.append(path)
406
+ continue
407
+ current = lf.sha256 if lf.exists else None
408
+ if current == e["planned_sha256"]:
409
+ if same_epoch and state is not None:
410
+ state.files[path] = FileBase(e["planned_sha256"], True, journal["revision"])
411
+ e["applied"] = True
412
+ elif current == e.get("prewrite_sha256"):
413
+ e["applied"] = False
414
+ else:
415
+ unresolved.append(path)
416
+ journal["status"] = "recovered"
417
+ journal["recovered_at"] = utcnow()
418
+ ctx.local.write_journal(op_dir, journal)
419
+ if state is not None:
420
+ ctx.local.save(state)
421
+ if unresolved or keep:
422
+ report.warnings.append(
423
+ f"Recovered an interrupted {journal.get('operation', 'pull')}; pre-write copies kept in "
424
+ f"{op_dir}" + (f" (check: {', '.join(unresolved)})" if unresolved else "")
425
+ )
426
+ else:
427
+ ctx.local.remove_operation_dir(op_dir)
428
+ report.warnings.append(f"Recovered an interrupted {journal.get('operation', 'pull')}")
429
+ return state
430
+
431
+
432
+ def fetch_contents(ctx: Context, view: RemoteView, statuses: list[FileStatus]) -> dict[str, bytes]:
433
+ if not statuses:
434
+ return {}
435
+ res = ctx.rpc.call(
436
+ "fetch",
437
+ project=_project(ctx),
438
+ expected_revision=view.revision,
439
+ paths=[s.path for s in statuses],
440
+ )
441
+ if res.get("revision") != view.revision:
442
+ raise TransportError("server returned a different revision than pinned", maybe_sent=False)
443
+ out: dict[str, bytes] = {}
444
+ want = {s.path: s for s in statuses}
445
+ for item in res.get("contents", []):
446
+ path = item.get("path")
447
+ if path not in want or path in out:
448
+ raise TransportError("server returned unexpected content", maybe_sent=False)
449
+ data = decode_b64(item.get("data_b64", ""), max_bytes=view.limits["max_file_bytes"])
450
+ expected = want[path].remote
451
+ if (
452
+ len(data) != item.get("size")
453
+ or sha256_hex(data) != expected
454
+ or item.get("sha256") != expected
455
+ ):
456
+ raise OffgitError(
457
+ f"{path}: downloaded content failed verification; nothing was written",
458
+ code="integrity_error",
459
+ )
460
+ out[path] = data
461
+ if set(out) != set(want):
462
+ raise TransportError("server omitted requested content", maybe_sent=False)
463
+ return out
464
+
465
+
466
+ def apply_downloads(
467
+ ctx: Context,
468
+ state: State,
469
+ downloads: list[FileStatus],
470
+ contents: dict[str, bytes],
471
+ revision: int,
472
+ *,
473
+ keep_paths: set[str],
474
+ operation: str,
475
+ ) -> list[str]:
476
+ """Write verified downloads with a durable journal. Returns applied paths."""
477
+ if not downloads:
478
+ return []
479
+ paths = [s.path for s in downloads]
480
+ # Fresh safety re-check immediately before writing.
481
+ recheck = observe(ctx, paths, max_bytes=HARD_LIMITS["max_file_bytes"])
482
+ for s in downloads:
483
+ ob = recheck[s.path]
484
+ if ob.unsafe:
485
+ raise UnsafeLocalFile(f"{s.path}: {ob.unsafe}; nothing was written", code="unsafe_path")
486
+ now = ob.sha256 if ob.exists else None
487
+ if now != s.local:
488
+ raise LocalChangedError(
489
+ f"{s.path} changed locally while offgit was working; nothing was written",
490
+ hint="Re-run the command",
491
+ )
492
+ op_id, op_dir = ctx.local.new_operation_dir()
493
+ entries: list[dict[str, Any]] = []
494
+ for s in downloads:
495
+ ob = recheck[s.path]
496
+ backup = None
497
+ if ob.exists and ob.data is not None:
498
+ backup = f"files/{len(entries):04d}"
499
+ bpath = op_dir / backup
500
+ bpath.parent.mkdir(mode=0o700, exist_ok=True)
501
+ atomic_write_private_bytes(bpath, ob.data)
502
+ entries.append(
503
+ {
504
+ "path": s.path,
505
+ "expected_base": s.base,
506
+ "prewrite_sha256": ob.sha256 if ob.exists else None,
507
+ "planned_sha256": s.remote,
508
+ "backup": backup,
509
+ "temp_name": None,
510
+ "applied": False,
511
+ }
512
+ )
513
+ journal = {
514
+ "operation_id": op_id,
515
+ "operation": operation,
516
+ "status": "applying",
517
+ "created_at": utcnow(),
518
+ "canonical_remote": ctx.identity.canonical,
519
+ "server_epoch": state.server_epoch,
520
+ "revision": revision,
521
+ "keep": bool(keep_paths & set(paths)),
522
+ "entries": entries,
523
+ }
524
+ ctx.local.write_journal(op_dir, journal) # durable before any write
525
+ applied: list[str] = []
526
+ try:
527
+ with Root(ctx.worktree.root) as root:
528
+ for e in entries:
529
+ e["temp_name"] = make_temp_name(e["path"].split("/")[-1])
530
+ ctx.local.write_journal(op_dir, journal)
531
+ root.atomic_write(
532
+ e["path"],
533
+ contents[e["path"]],
534
+ expected_sha256=e["prewrite_sha256"],
535
+ max_bytes=HARD_LIMITS["max_file_bytes"],
536
+ temp_name=e["temp_name"],
537
+ )
538
+ e["applied"] = True
539
+ ctx.local.write_journal(op_dir, journal)
540
+ state.files[e["path"]] = FileBase(e["planned_sha256"], True, revision)
541
+ applied.append(e["path"])
542
+ except (OSError, OffgitError) as exc:
543
+ ctx.local.save(state)
544
+ rep = Report(command=operation)
545
+ _recover_one(ctx, state, op_dir, journal, rep)
546
+ raise PartialError(
547
+ f"{operation} stopped after writing {len(applied)} of {len(entries)} files: "
548
+ f"{getattr(exc, 'message', None) or exc}",
549
+ code="partial_apply",
550
+ hint=f"Local copies from before the write are in {op_dir}. Run 'offgit status'.",
551
+ details={"applied": applied, "recovery_dir": str(op_dir)},
552
+ ) from exc
553
+ ctx.local.save(state)
554
+ journal["status"] = "complete"
555
+ journal["completed_at"] = utcnow()
556
+ ctx.local.write_journal(op_dir, journal)
557
+ if not journal["keep"]:
558
+ ctx.local.remove_operation_dir(op_dir)
559
+ return applied
560
+
561
+
562
+ def atomic_write_private_bytes(path: Path, data: bytes) -> None:
563
+ tmp = path.with_name(path.name + ".tmp")
564
+ fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC | getattr(os, "O_NOFOLLOW", 0), 0o600)
565
+ try:
566
+ view = memoryview(data)
567
+ while view:
568
+ n = os.write(fd, view)
569
+ view = view[n:]
570
+ os.fsync(fd)
571
+ finally:
572
+ os.close(fd)
573
+ os.replace(tmp, path)
574
+
575
+
576
+ # ---------------------------------------------------------------------------
577
+ # report helpers
578
+
579
+ _KIND_TEXT = {
580
+ Kind.IN_SYNC: ("in sync", "same"),
581
+ Kind.LOCAL_AHEAD: ("local ahead", "warn"),
582
+ Kind.REMOTE_AHEAD: ("remote ahead", "warn"),
583
+ Kind.CONFLICT: ("conflict", "error"),
584
+ Kind.MISSING: ("missing locally", "warn"),
585
+ Kind.UNREGISTERED: ("unregistered on server (local file kept)", "warn"),
586
+ Kind.UNREGISTERED_MODIFIED: (
587
+ "unregistered on server, modified locally (run 'offgit add' to re-register)",
588
+ "error",
589
+ ),
590
+ Kind.UNSAFE: ("unsafe", "error"),
591
+ }
592
+
593
+
594
+ def _conflict_line(s: FileStatus) -> str:
595
+ return (
596
+ f"has local and remote changes (base {short(s.base)}, local {short(s.local)}, "
597
+ f"remote {short(s.remote)})"
598
+ )
599
+
600
+
601
+ def report_blocked(report: Report, plan: Plan, command: str) -> Report:
602
+ for s in plan.conflicts:
603
+ report.add(
604
+ s.path,
605
+ _conflict_line(s) if s.base else (s.detail or "conflict"),
606
+ "error",
607
+ state="conflict",
608
+ )
609
+ for s in plan.unsafe:
610
+ report.add(s.path, f"unsafe: {s.detail}", "error", state="unsafe")
611
+ if plan.conflicts:
612
+ names = " ".join(s.path for s in plan.conflicts)
613
+ report.summary = "No files changed. Inspect: offgit diff " + names
614
+ report.notes.append(
615
+ "Resolve explicitly with 'offgit push --prefer-local FILE' or "
616
+ "'offgit pull --prefer-remote FILE' after reviewing the diff"
617
+ )
618
+ report.exit_code = EXIT_CONFLICT
619
+ else:
620
+ report.summary = "No files changed: unsafe paths must be fixed first"
621
+ report.exit_code = EXIT_USAGE
622
+ report.summary_style = "error"
623
+ report.data["conflicts"] = [s.to_dict() for s in plan.conflicts]
624
+ report.data["unsafe"] = [s.to_dict() for s in plan.unsafe]
625
+ return report
626
+
627
+
628
+ def _finish(report: Report, ctx: Context) -> Report:
629
+ report.data["duration_seconds"] = round(time.monotonic() - ctx.started, 3)
630
+ report.data["bytes_sent"] = ctx.rpc.bytes_sent
631
+ report.data["bytes_received"] = ctx.rpc.bytes_received
632
+ return report
633
+
634
+
635
+ def _validate_resolution(plan_statuses: list[FileStatus], paths: set[str]) -> None:
636
+ by = {s.path: s for s in plan_statuses}
637
+ for p in sorted(paths):
638
+ s = by.get(p)
639
+ if s is None:
640
+ raise UsageError(f"{p} is not registered", code="not_registered")
641
+ if s.kind is not Kind.CONFLICT:
642
+ raise UsageError(
643
+ f"{p} is not in conflict ({_KIND_TEXT[s.kind][0]}); explicit resolution only applies "
644
+ "to conflicted files",
645
+ code="not_conflicted",
646
+ )
647
+
648
+
649
+ def _require_confirm(confirm: Confirm | None, yes: bool, prompt: str) -> None:
650
+ if yes:
651
+ return
652
+ if confirm is None:
653
+ raise UsageError(
654
+ "Confirmation required; re-run with --yes",
655
+ code="confirmation_required",
656
+ hint="Non-interactive and --json modes never prompt",
657
+ )
658
+ if not confirm(prompt):
659
+ raise UsageError("Aborted; nothing changed", code="aborted")
660
+
661
+
662
+ def _prepare(ctx: Context, *, mutate: bool, report: Report) -> tuple[State | None, RemoteView]:
663
+ state = ctx.local.load()
664
+ view = fetch_view(ctx)
665
+ require_project(ctx, view)
666
+ if mutate:
667
+ pending = ctx.local.load_pending()
668
+ if pending is not None and (
669
+ pending.get("server_epoch") != view.server_epoch
670
+ or pending.get("server_id") != view.server_id
671
+ ):
672
+ raise RecoveryRequired(
673
+ "An interrupted operation was recorded against a different server epoch",
674
+ code="server_epoch_changed",
675
+ hint="Run 'offgit rebaseline'",
676
+ )
677
+ check_epoch(ctx, state, view)
678
+ state = settle_pending(ctx, state, report)
679
+ state = recover_journals(ctx, state, report)
680
+ if pending is not None:
681
+ view = fetch_view(ctx)
682
+ else:
683
+ check_epoch(ctx, state, view)
684
+ if ctx.local.load_pending() is not None:
685
+ report.warnings.append(
686
+ "An interrupted operation is pending; the next push/pull settles it"
687
+ )
688
+ if ctx.local.open_journals():
689
+ report.warnings.append(
690
+ "An interrupted pull journal exists; the next push/pull recovers it"
691
+ )
692
+ return state, view
693
+
694
+
695
+ def _new_state(ctx: Context, view: RemoteView, state: State | None) -> State:
696
+ if state is None:
697
+ state = State(
698
+ project_id=ctx.identity.project_id,
699
+ canonical_remote=ctx.identity.canonical,
700
+ remote_name=ctx.remote_name,
701
+ )
702
+ state.server_id = view.server_id
703
+ state.server_epoch = view.server_epoch
704
+ state.last_seen_revision = max(state.last_seen_revision, view.revision)
705
+ return state
706
+
707
+
708
+ def _handle_unregistered(state: State, plan: Plan, report: Report) -> None:
709
+ for s in plan.unregistered:
710
+ if s.kind is Kind.UNREGISTERED:
711
+ report.add(s.path, "unregistered on server; local file left untouched", "warn")
712
+ state.files.pop(s.path, None)
713
+ else:
714
+ report.add(
715
+ s.path,
716
+ "unregistered on server but modified locally; local file kept. "
717
+ "Run 'offgit add' to re-register or 'offgit remove' to acknowledge",
718
+ "error",
719
+ )
720
+
721
+
722
+ # ---------------------------------------------------------------------------
723
+ # commands
724
+
725
+
726
+ def cmd_init(ctx: Context, files: list[str]) -> Report:
727
+ report = ctx.report("init")
728
+ if not files:
729
+ raise UsageError("init needs at least one file: offgit init -f FILE...", code="no_files")
730
+ paths = [normalize_user_path(f) for f in files]
731
+ check_collisions(paths)
732
+ with ctx.local.lock():
733
+ state = ctx.local.load()
734
+ pending = ctx.local.load_pending()
735
+ view = fetch_view(ctx)
736
+ if pending is not None:
737
+ state = settle_pending(ctx, state, report)
738
+ view = fetch_view(ctx)
739
+ if (
740
+ pending.get("operation") == "init"
741
+ and state is not None
742
+ and set(pending.get("set_bases", {})) == set(state.files)
743
+ and set(paths) == set(state.files)
744
+ ):
745
+ for p in paths:
746
+ report.add(p, "uploaded (by the interrupted init)", "ok")
747
+ report.summary = f"Registered {len(paths)} files · revision {view.revision}"
748
+ report.data["revision"] = view.revision
749
+ return _finish(report, ctx)
750
+ if state is not None and state.files:
751
+ raise UsageError(
752
+ "This worktree is already initialized for offgit",
753
+ code="already_initialized",
754
+ hint="Use 'offgit add FILE...' to register more files",
755
+ )
756
+ if view.exists:
757
+ raise UsageError(
758
+ f"{ctx.identity.canonical} is already registered on the server; nothing was overwritten",
759
+ code="project_exists",
760
+ hint="Use 'offgit pull' to fetch the registered files, or 'offgit add FILE...' to register more",
761
+ )
762
+ obs = observe(ctx, paths, max_bytes=view.limits["max_file_bytes"])
763
+ _require_local_files(obs, paths)
764
+ total = sum(obs[p].size or 0 for p in paths)
765
+ if len(paths) > view.limits["max_paths"] or total > view.limits["max_project_bytes"]:
766
+ raise UsageError(
767
+ "Selected files exceed the server's project limits", code="limit_exceeded"
768
+ )
769
+ req = ctx.rpc.build(
770
+ "init",
771
+ project=_project(ctx),
772
+ expected_server_epoch=view.server_epoch,
773
+ files=[_content(obs[p]) for p in paths],
774
+ )
775
+ record = _pending_record(
776
+ ctx, req, view.server_epoch, view.server_id, {p: obs[p].sha256 or "" for p in paths}, []
777
+ )
778
+ result, _state = send_mutation(ctx, state, req, record)
779
+ ctx.local.save_settings({"remote_name": ctx.remote_name})
780
+ for p in paths:
781
+ report.add(p, "uploaded", "ok", sha256=obs[p].sha256, size=obs[p].size)
782
+ report.summary = f"Registered {len(paths)} file{'s' if len(paths) != 1 else ''} · revision {result['revision']}"
783
+ report.data["revision"] = result["revision"]
784
+ return _finish(report, ctx)
785
+
786
+
787
+ def _require_local_files(obs: dict[str, Observation], paths: list[str]) -> None:
788
+ for p in paths:
789
+ ob = obs[p]
790
+ if ob.unsafe:
791
+ raise UnsafeLocalFile(f"{p}: {ob.unsafe}", code="unsafe_path")
792
+ if not ob.exists:
793
+ raise UsageError(
794
+ f"{p} does not exist; offgit only registers existing regular files",
795
+ code="file_missing",
796
+ )
797
+
798
+
799
+ def _content(
800
+ ob: Observation, expected: str | None = None, with_expected: bool = False
801
+ ) -> dict[str, Any]:
802
+ assert ob.data is not None and ob.sha256 is not None
803
+ item: dict[str, Any] = {
804
+ "path": ob.path,
805
+ "sha256": ob.sha256,
806
+ "size": len(ob.data),
807
+ "data_b64": encode_b64(ob.data),
808
+ }
809
+ if with_expected:
810
+ item["expected_sha256"] = expected
811
+ return item
812
+
813
+
814
+ def cmd_push(
815
+ ctx: Context,
816
+ *,
817
+ dry_run: bool = False,
818
+ prefer_local: list[str] | None = None,
819
+ yes: bool = False,
820
+ confirm: Confirm | None = None,
821
+ ) -> Report:
822
+ report = ctx.report("push")
823
+ forced = {normalize_user_path(p) for p in (prefer_local or [])}
824
+ lock = _NullLock() if dry_run else ctx.local.lock()
825
+ with lock:
826
+ for _attempt in range(MAX_CAS_ATTEMPTS):
827
+ state, view = _prepare(ctx, mutate=not dry_run, report=report)
828
+ statuses, obs = compute_statuses(ctx, state, view)
829
+ if forced:
830
+ _validate_resolution(statuses, forced)
831
+ plan = make_plan(statuses, direction="push", prefer_local=forced)
832
+ if plan.blocked:
833
+ return _finish(report_blocked(report, plan, "push"), ctx)
834
+ if dry_run:
835
+ return _finish(_describe_plan(report, plan, view, "push", dry_run=True), ctx)
836
+ if plan.forced:
837
+ _require_confirm(
838
+ confirm,
839
+ yes,
840
+ "Replace the server copy of "
841
+ + ", ".join(f"{s.path} (remote {short(s.remote)})" for s in plan.forced)
842
+ + " with your local version? The old server content stays in history.",
843
+ )
844
+ state = _new_state(ctx, view, state)
845
+ for s in plan.adopt:
846
+ state.files[s.path] = FileBase(s.remote or "", True, view.revision)
847
+ _handle_unregistered(state, plan, report)
848
+ if not plan.uploads:
849
+ ctx.local.save(state)
850
+ return _finish(_describe_plan(report, plan, view, "push"), ctx)
851
+ req = ctx.rpc.build(
852
+ "push",
853
+ project=_project(ctx),
854
+ expected_server_epoch=view.server_epoch,
855
+ expected_revision=view.revision,
856
+ changes=[_content(obs[s.path], s.remote, with_expected=True) for s in plan.uploads],
857
+ )
858
+ record = _pending_record(
859
+ ctx,
860
+ req,
861
+ view.server_epoch,
862
+ view.server_id,
863
+ {s.path: s.local or "" for s in plan.uploads},
864
+ [],
865
+ )
866
+ ctx.local.save(state)
867
+ try:
868
+ result, state = send_mutation(ctx, state, req, record)
869
+ except RemoteError as exc:
870
+ if exc.code in ("revision_conflict", "path_conflict") and not plan.forced:
871
+ report.warnings.append("Server changed during push; re-planning")
872
+ continue
873
+ if exc.code in ("revision_conflict", "path_conflict"):
874
+ raise ConflictError(
875
+ "Server changed while resolving; nothing was pushed",
876
+ hint="Review 'offgit status' and resolve again",
877
+ ) from exc
878
+ raise
879
+ return _finish(_describe_plan(report, plan, view, "push", result=result), ctx)
880
+ raise ConflictError(
881
+ "Server kept changing during push; nothing was pushed",
882
+ code="stale_revision",
883
+ hint="Run 'offgit status' and retry",
884
+ )
885
+
886
+
887
+ def cmd_pull(
888
+ ctx: Context,
889
+ *,
890
+ dry_run: bool = False,
891
+ prefer_remote: list[str] | None = None,
892
+ yes: bool = False,
893
+ confirm: Confirm | None = None,
894
+ ) -> Report:
895
+ return _pull_or_sync(
896
+ ctx, "pull", dry_run=dry_run, prefer_remote=prefer_remote, yes=yes, confirm=confirm
897
+ )
898
+
899
+
900
+ def cmd_sync(ctx: Context, *, dry_run: bool = False) -> Report:
901
+ return _pull_or_sync(ctx, "sync", dry_run=dry_run)
902
+
903
+
904
+ def _pull_or_sync(
905
+ ctx: Context,
906
+ direction: str,
907
+ *,
908
+ dry_run: bool,
909
+ prefer_remote: list[str] | None = None,
910
+ yes: bool = False,
911
+ confirm: Confirm | None = None,
912
+ ) -> Report:
913
+ report = ctx.report(direction)
914
+ forced = {normalize_user_path(p) for p in (prefer_remote or [])}
915
+ lock = _NullLock() if dry_run else ctx.local.lock()
916
+ with lock:
917
+ for _attempt in range(MAX_CAS_ATTEMPTS):
918
+ state, view = _prepare(ctx, mutate=not dry_run, report=report)
919
+ statuses, obs = compute_statuses(ctx, state, view)
920
+ if forced:
921
+ _validate_resolution(statuses, forced)
922
+ plan = make_plan(statuses, direction=direction, prefer_remote=forced)
923
+ if plan.blocked:
924
+ return _finish(report_blocked(report, plan, direction), ctx)
925
+ if dry_run:
926
+ return _finish(_describe_plan(report, plan, view, direction, dry_run=True), ctx)
927
+ if plan.forced:
928
+ _require_confirm(
929
+ confirm,
930
+ yes,
931
+ "Replace your local "
932
+ + ", ".join(f"{s.path} (local {short(s.local)})" for s in plan.forced)
933
+ + " with the server version? Exact local bytes are saved in the Git-private "
934
+ "recovery folder first.",
935
+ )
936
+ try:
937
+ contents = fetch_contents(ctx, view, plan.downloads)
938
+ except RemoteError as exc:
939
+ if exc.code == "revision_changed":
940
+ report.warnings.append("Server changed during " + direction + "; re-planning")
941
+ continue
942
+ raise
943
+ state = _new_state(ctx, view, state)
944
+ for s in plan.adopt:
945
+ state.files[s.path] = FileBase(s.remote or "", True, view.revision)
946
+ _handle_unregistered(state, plan, report)
947
+ result = None
948
+ if plan.uploads:
949
+ req = ctx.rpc.build(
950
+ "push",
951
+ project=_project(ctx),
952
+ expected_server_epoch=view.server_epoch,
953
+ expected_revision=view.revision,
954
+ changes=[
955
+ _content(obs[s.path], s.remote, with_expected=True) for s in plan.uploads
956
+ ],
957
+ )
958
+ record = _pending_record(
959
+ ctx, req, view.server_epoch, view.server_id,
960
+ {s.path: s.local or "" for s in plan.uploads}, [],
961
+ ) # fmt: skip
962
+ ctx.local.save(state)
963
+ try:
964
+ result, state = send_mutation(ctx, state, req, record)
965
+ except RemoteError as exc:
966
+ if exc.code in ("revision_conflict", "path_conflict"):
967
+ report.warnings.append("Server changed during sync; re-planning")
968
+ continue
969
+ raise
970
+ ctx.local.save(state)
971
+ try:
972
+ apply_downloads(
973
+ ctx,
974
+ state,
975
+ plan.downloads,
976
+ contents,
977
+ view.revision,
978
+ keep_paths=forced,
979
+ operation=direction,
980
+ )
981
+ except (PartialError, LocalChangedError, UnsafeLocalFile) as exc:
982
+ if result is not None:
983
+ raise PartialError(
984
+ f"Uploaded to revision {result['revision']}, but local downloads failed: "
985
+ f"{exc.message}",
986
+ code="partial_sync",
987
+ hint=exc.hint or "Run 'offgit status'",
988
+ ) from exc
989
+ raise
990
+ return _finish(_describe_plan(report, plan, view, direction, result=result), ctx)
991
+ raise ConflictError(
992
+ f"Server kept changing during {direction}; nothing was written",
993
+ code="stale_revision",
994
+ hint="Retry",
995
+ )
996
+
997
+
998
+ class _NullLock:
999
+ def __enter__(self) -> None:
1000
+ return None
1001
+
1002
+ def __exit__(self, *exc: object) -> None:
1003
+ return None
1004
+
1005
+
1006
+ def _describe_plan(
1007
+ report: Report,
1008
+ plan: Plan,
1009
+ view: RemoteView,
1010
+ direction: str,
1011
+ *,
1012
+ dry_run: bool = False,
1013
+ result: dict[str, Any] | None = None,
1014
+ ) -> Report:
1015
+ would = "would " if dry_run else ""
1016
+ up_ok = set()
1017
+ if result is not None:
1018
+ up_ok = set(result.get("changed", []))
1019
+ for s in plan.statuses:
1020
+ if s in plan.uploads:
1021
+ verb = "upload" if dry_run else "updated"
1022
+ msg = f"{would}{verb}" + (" (prefer local)" if s in plan.forced else "")
1023
+ if not dry_run and s.path not in up_ok and result is not None:
1024
+ msg = "unchanged"
1025
+ report.add(s.path, msg, "info" if dry_run else "ok", state=s.kind.value)
1026
+ elif s in plan.downloads:
1027
+ verb = "restore" if s.kind is Kind.MISSING else "download"
1028
+ done = "restored" if s.kind is Kind.MISSING else "downloaded"
1029
+ msg = f"{would}{verb}" if dry_run else done
1030
+ if s in plan.forced:
1031
+ msg += " (prefer remote; local copy saved)"
1032
+ report.add(s.path, msg, "info" if dry_run else "ok", state=s.kind.value)
1033
+ elif s in plan.skipped:
1034
+ if s.kind is Kind.MISSING:
1035
+ report.add(
1036
+ s.path,
1037
+ "missing locally (not a deletion; run offgit pull)",
1038
+ "warn",
1039
+ state=s.kind.value,
1040
+ )
1041
+ elif s.kind is Kind.REMOTE_AHEAD:
1042
+ report.add(
1043
+ s.path, "skipped: remote ahead (run offgit pull)", "warn", state=s.kind.value
1044
+ )
1045
+ else:
1046
+ report.add(
1047
+ s.path, "skipped: local ahead (run offgit push)", "warn", state=s.kind.value
1048
+ )
1049
+ elif s.kind is Kind.IN_SYNC:
1050
+ report.add(s.path, "unchanged", "same", state=s.kind.value)
1051
+ elif dry_run and s in plan.unregistered:
1052
+ report.add(s.path, _KIND_TEXT[s.kind][0], "warn", state=s.kind.value)
1053
+ n_up = len(plan.uploads)
1054
+ n_down = len(plan.downloads)
1055
+ incomplete = bool(plan.skipped or plan.unregistered)
1056
+ report.data.update(
1057
+ {
1058
+ "dry_run": dry_run,
1059
+ "revision_before": view.revision,
1060
+ "uploaded": [s.path for s in plan.uploads] if not dry_run else [],
1061
+ "downloaded": [s.path for s in plan.downloads] if not dry_run else [],
1062
+ "planned_uploads": [s.path for s in plan.uploads],
1063
+ "planned_downloads": [s.path for s in plan.downloads],
1064
+ "skipped": [s.path for s in plan.skipped],
1065
+ "unchanged": [s.path for s in plan.statuses if s.kind is Kind.IN_SYNC],
1066
+ "fully_synchronized": not incomplete,
1067
+ }
1068
+ )
1069
+ rev_after = result["revision"] if result else view.revision
1070
+ report.data["revision"] = rev_after
1071
+ parts = []
1072
+ if dry_run:
1073
+ parts.append(f"Dry run: {n_up} to upload, {n_down} to download")
1074
+ report.summary_style = "info"
1075
+ else:
1076
+ if direction in ("push", "sync"):
1077
+ pushed = len(up_ok) if result is not None else 0
1078
+ parts.append(f"Pushed {pushed} file{'s' if pushed != 1 else ''}")
1079
+ if direction in ("pull", "sync"):
1080
+ parts.append(f"Pulled {n_down} file{'s' if n_down != 1 else ''}")
1081
+ if result is not None and result["revision"] != view.revision:
1082
+ parts.append(f"revision {view.revision} → {result['revision']}")
1083
+ else:
1084
+ parts.append(f"revision {rev_after}")
1085
+ if plan.skipped:
1086
+ parts.append(f"{len(plan.skipped)} skipped")
1087
+ report.summary = " · ".join(parts)
1088
+ if not dry_run:
1089
+ if incomplete:
1090
+ report.summary_style = "warn"
1091
+ report.notes.append("Not fully synchronized: see skipped files above")
1092
+ else:
1093
+ report.summary_style = "ok"
1094
+ if not dry_run and direction in ("push", "sync") and result is not None:
1095
+ report.notes.append("Committed on the server; cloud backup runs separately on the server")
1096
+ return report
1097
+
1098
+
1099
+ def cmd_status(ctx: Context) -> Report:
1100
+ report = ctx.report("status")
1101
+ state = ctx.local.load()
1102
+ report.data["local_state"] = state is not None
1103
+ try:
1104
+ view = fetch_view(ctx)
1105
+ except OffgitError as exc:
1106
+ report.data["server"] = {"reachable": False}
1107
+ if state is not None:
1108
+ for p, fb in sorted(state.files.items()):
1109
+ report.add(p, f"unknown (server unreachable; base {short(fb.base_sha256)})", "warn")
1110
+ report.error = exc
1111
+ report.exit_code = exc.exit_code
1112
+ return _finish(report, ctx)
1113
+ server_info = {
1114
+ "reachable": True,
1115
+ "id": view.server_id,
1116
+ "epoch": view.server_epoch,
1117
+ "revision": view.revision,
1118
+ "backup": view.backup,
1119
+ }
1120
+ report.data["server"] = server_info
1121
+ if not view.exists:
1122
+ report.summary = "Project is not registered on the server (offgit init -f FILE...)"
1123
+ report.summary_style = "warn"
1124
+ return _finish(report, ctx)
1125
+ epoch_ok = True
1126
+ try:
1127
+ check_epoch(ctx, state, view)
1128
+ except RecoveryRequired as exc:
1129
+ epoch_ok = False
1130
+ report.warnings.append(exc.message + "; run 'offgit rebaseline'")
1131
+ if ctx.local.load_pending() is not None:
1132
+ report.warnings.append("An interrupted operation is pending; the next push/pull settles it")
1133
+ if ctx.local.open_journals():
1134
+ report.warnings.append("An interrupted pull journal exists; the next push/pull recovers it")
1135
+ statuses, _ = compute_statuses(ctx, state if epoch_ok else None, view)
1136
+ counts: dict[str, int] = {}
1137
+ for s in statuses:
1138
+ text, style = _KIND_TEXT[s.kind]
1139
+ if s.kind is Kind.UNSAFE:
1140
+ text = f"unsafe: {s.detail}"
1141
+ elif s.kind is Kind.IN_SYNC and s.base != s.remote:
1142
+ text = "in sync (base will be recorded on next push/pull)"
1143
+ elif s.kind is Kind.CONFLICT and s.base is None:
1144
+ text = "conflict: differs from server and no common base"
1145
+ report.add(s.path, text, style, **{k: v for k, v in s.to_dict().items() if k != "path"})
1146
+ counts[s.kind.value] = counts.get(s.kind.value, 0) + 1
1147
+ report.data["counts"] = counts
1148
+ report.data["revision"] = view.revision
1149
+ report.data["last_seen_revision"] = state.last_seen_revision if state else None
1150
+ clean = all(s.kind is Kind.IN_SYNC for s in statuses) and epoch_ok
1151
+ report.data["fully_synchronized"] = clean
1152
+ backup = view.backup
1153
+ if backup.get("configured"):
1154
+ age = backup.get("last_success_age_seconds")
1155
+ report.notes.append(
1156
+ "Server backup: "
1157
+ + (
1158
+ f"last success {age // 3600}h{(age % 3600) // 60:02d}m ago"
1159
+ if isinstance(age, int)
1160
+ else "no success yet"
1161
+ )
1162
+ + (f", last attempt {backup.get('last_result')}" if backup.get("last_result") else "")
1163
+ )
1164
+ summary = ", ".join(f"{n} {k.replace('_', ' ')}" for k, n in sorted(counts.items()))
1165
+ report.summary = f"revision {view.revision} · " + (summary or "no registered files")
1166
+ report.summary_style = "ok" if clean else "warn"
1167
+ return _finish(report, ctx)
1168
+
1169
+
1170
+ def cmd_list(ctx: Context) -> Report:
1171
+ report = ctx.report("list")
1172
+ view = fetch_view(ctx)
1173
+ require_project(ctx, view)
1174
+ rows = []
1175
+ for p, e in sorted(view.registered.items()):
1176
+ rows.append([p, str(e.size), short(e.sha256), str(e.changed_revision)])
1177
+ report.data.setdefault("registered", []).append(
1178
+ {"path": p, "size": e.size, "sha256": e.sha256, "changed_revision": e.changed_revision}
1179
+ )
1180
+ report.table = {"columns": ["path", "bytes", "sha256", "changed in"], "rows": rows}
1181
+ report.data["revision"] = view.revision
1182
+ report.summary = (
1183
+ f"{len(rows)} registered file{'s' if len(rows) != 1 else ''} · revision {view.revision}"
1184
+ )
1185
+ report.summary_style = "info"
1186
+ return _finish(report, ctx)
1187
+
1188
+
1189
+ def cmd_add(ctx: Context, files: list[str]) -> Report:
1190
+ report = ctx.report("add")
1191
+ if not files:
1192
+ raise UsageError("add needs at least one file", code="no_files")
1193
+ paths = [normalize_user_path(f) for f in files]
1194
+ check_collisions(paths)
1195
+ with ctx.local.lock():
1196
+ for _attempt in range(MAX_CAS_ATTEMPTS):
1197
+ state, view = _prepare(ctx, mutate=True, report=report)
1198
+ already = [p for p in paths if p in view.registered]
1199
+ if already:
1200
+ raise UsageError(
1201
+ f"Already registered: {', '.join(already)}; add never overwrites registrations",
1202
+ code="already_registered",
1203
+ hint="Use 'offgit push' to upload changes",
1204
+ )
1205
+ check_collisions(list(view.registered) + paths)
1206
+ obs = observe(ctx, paths, max_bytes=view.limits["max_file_bytes"])
1207
+ _require_local_files(obs, paths)
1208
+ state = _new_state(ctx, view, state)
1209
+ req = ctx.rpc.build(
1210
+ "add",
1211
+ project=_project(ctx),
1212
+ expected_server_epoch=view.server_epoch,
1213
+ expected_revision=view.revision,
1214
+ files=[_content(obs[p]) for p in paths],
1215
+ )
1216
+ record = _pending_record(
1217
+ ctx,
1218
+ req,
1219
+ view.server_epoch,
1220
+ view.server_id,
1221
+ {p: obs[p].sha256 or "" for p in paths},
1222
+ [],
1223
+ )
1224
+ try:
1225
+ result, state = send_mutation(ctx, state, req, record)
1226
+ except RemoteError as exc:
1227
+ if exc.code == "revision_conflict":
1228
+ continue
1229
+ raise
1230
+ for p in paths:
1231
+ report.add(p, "registered", "ok", sha256=obs[p].sha256, size=obs[p].size)
1232
+ report.summary = f"Added {len(paths)} file{'s' if len(paths) != 1 else ''} · revision {view.revision} → {result['revision']}"
1233
+ report.data["revision"] = result["revision"]
1234
+ return _finish(report, ctx)
1235
+ raise ConflictError("Server kept changing; nothing was added", code="stale_revision")
1236
+
1237
+
1238
+ def cmd_remove(ctx: Context, files: list[str], *, yes: bool, confirm: Confirm | None) -> Report:
1239
+ report = ctx.report("remove")
1240
+ if not files:
1241
+ raise UsageError("remove needs at least one file", code="no_files")
1242
+ paths = [normalize_user_path(f) for f in files]
1243
+ with ctx.local.lock():
1244
+ for _attempt in range(MAX_CAS_ATTEMPTS):
1245
+ state, view = _prepare(ctx, mutate=True, report=report)
1246
+ ack = [p for p in paths if p not in view.registered and state and p in state.files]
1247
+ unknown = [p for p in paths if p not in view.registered and p not in ack]
1248
+ if unknown:
1249
+ raise UsageError(f"Not registered: {', '.join(unknown)}", code="not_registered")
1250
+ to_remove = [p for p in paths if p in view.registered]
1251
+ _require_confirm(
1252
+ confirm,
1253
+ yes,
1254
+ f"Unregister {', '.join(paths)} on the server for ALL devices? Local files on every "
1255
+ "device are kept and history is retained; other devices will stop syncing them.",
1256
+ )
1257
+ state = _new_state(ctx, view, state)
1258
+ for p in ack:
1259
+ state.files.pop(p, None)
1260
+ report.add(p, "acknowledged server removal (local file kept)", "ok")
1261
+ if not to_remove:
1262
+ ctx.local.save(state)
1263
+ report.summary = "No server change"
1264
+ return _finish(report, ctx)
1265
+ req = ctx.rpc.build(
1266
+ "remove",
1267
+ project=_project(ctx),
1268
+ expected_server_epoch=view.server_epoch,
1269
+ expected_revision=view.revision,
1270
+ paths=to_remove,
1271
+ )
1272
+ record = _pending_record(ctx, req, view.server_epoch, view.server_id, {}, to_remove)
1273
+ ctx.local.save(state)
1274
+ try:
1275
+ result, state = send_mutation(ctx, state, req, record)
1276
+ except RemoteError as exc:
1277
+ if exc.code == "revision_conflict":
1278
+ continue
1279
+ raise
1280
+ for p in to_remove:
1281
+ report.add(p, "unregistered (local file kept, history retained)", "ok")
1282
+ report.summary = f"Removed {len(to_remove)} registration{'s' if len(to_remove) != 1 else ''} · revision {view.revision} → {result['revision']}"
1283
+ report.data["revision"] = result["revision"]
1284
+ return _finish(report, ctx)
1285
+ raise ConflictError("Server kept changing; nothing was removed", code="stale_revision")
1286
+
1287
+
1288
+ def cmd_diff(ctx: Context, files: list[str]) -> Report:
1289
+ report = ctx.report("diff")
1290
+ state = ctx.local.load()
1291
+ view = fetch_view(ctx)
1292
+ require_project(ctx, view)
1293
+ if files:
1294
+ paths = [normalize_user_path(f) for f in files]
1295
+ missing = [p for p in paths if p not in view.registered]
1296
+ if missing:
1297
+ raise UsageError(f"Not registered: {', '.join(missing)}", code="not_registered")
1298
+ else:
1299
+ paths = sorted(view.registered)
1300
+ obs = observe(ctx, paths, max_bytes=view.limits["max_file_bytes"])
1301
+ differing = [
1302
+ p for p in paths
1303
+ if obs[p].unsafe is None and (not obs[p].exists or obs[p].sha256 != view.registered[p].sha256)
1304
+ ] # fmt: skip
1305
+ for p in paths:
1306
+ if obs[p].unsafe:
1307
+ report.add(p, f"unsafe: {obs[p].unsafe}", "error")
1308
+ statuses = [
1309
+ FileStatus(
1310
+ p, Kind.REMOTE_AHEAD, None, obs[p].sha256, view.registered[p].sha256, obs[p].exists
1311
+ )
1312
+ for p in differing
1313
+ ]
1314
+ contents = fetch_contents(ctx, view, statuses)
1315
+ chunks: list[str] = []
1316
+ for p in paths:
1317
+ if p not in differing:
1318
+ if obs[p].unsafe is None:
1319
+ report.add(p, "identical", "same")
1320
+ continue
1321
+ remote_b = contents[p]
1322
+ local_b = obs[p].data if obs[p].exists else None
1323
+ label_r = f"server:{p} (revision {view.revision}, {short(view.registered[p].sha256)})"
1324
+ label_l = f"local:{p}" + ("" if local_b is not None else " (missing)")
1325
+ try:
1326
+ r_text = remote_b.decode("utf-8")
1327
+ l_text = (local_b or b"").decode("utf-8")
1328
+ except UnicodeDecodeError:
1329
+ report.add(
1330
+ p,
1331
+ f"binary or non-UTF-8 content differs (server {len(remote_b)} bytes, "
1332
+ f"local {len(local_b) if local_b is not None else 'missing'})",
1333
+ "warn",
1334
+ )
1335
+ continue
1336
+ diff = difflib.unified_diff(
1337
+ r_text.splitlines(keepends=True),
1338
+ l_text.splitlines(keepends=True),
1339
+ fromfile=label_r,
1340
+ tofile=label_l,
1341
+ )
1342
+ text = "".join(
1343
+ d if d.endswith("\n") else d + "\n\\n" for d in diff
1344
+ )
1345
+ if not text:
1346
+ text = f"--- {label_r}\n+++ {label_l}\n(only line-ending or trailing-newline differences)\n"
1347
+ chunks.append(text)
1348
+ report.add(p, "differs", "warn")
1349
+ report.text = "".join(chunks) if chunks else None
1350
+ report.data["direction"] = "server -> local ('-' lines are on the server, '+' lines are local)"
1351
+ report.data["revision"] = view.revision
1352
+ report.summary = (
1353
+ f"{len(differing)} differing file{'s' if len(differing) != 1 else ''} (server → local)"
1354
+ )
1355
+ report.summary_style = "info"
1356
+ del state
1357
+ return _finish(report, ctx)
1358
+
1359
+
1360
+ def cmd_history(ctx: Context, file: str | None, limit: int) -> Report:
1361
+ report = ctx.report("history")
1362
+ path = normalize_user_path(file) if file else None
1363
+ if not 1 <= limit <= 1000:
1364
+ raise UsageError("--limit must be between 1 and 1000")
1365
+ res = ctx.rpc.call("history", project=_project(ctx), path=path, limit=limit)
1366
+ rows = []
1367
+ for r in res.get("revisions", []):
1368
+ changes = ", ".join(
1369
+ f"{c['path']}{'' if c['registered'] else ' (unregistered)'} {short(c['sha256'], 8)}"
1370
+ for c in r.get("changes", [])
1371
+ )
1372
+ rows.append(
1373
+ [
1374
+ str(r["revision"]),
1375
+ r["timestamp_utc"][:19].replace("T", " "),
1376
+ r.get("device") or "-",
1377
+ r["operation"],
1378
+ changes,
1379
+ ]
1380
+ )
1381
+ report.table = {
1382
+ "columns": ["rev", "time (UTC)", "device", "operation", "changes"],
1383
+ "rows": rows,
1384
+ }
1385
+ report.data["revisions"] = res.get("revisions", [])
1386
+ report.data["revision"] = res.get("revision")
1387
+ report.summary = (
1388
+ f"{len(rows)} revision{'s' if len(rows) != 1 else ''} shown · head {res.get('revision')}"
1389
+ )
1390
+ report.summary_style = "info"
1391
+ return _finish(report, ctx)
1392
+
1393
+
1394
+ def cmd_restore(
1395
+ ctx: Context, file: str, revision: int, *, yes: bool, confirm: Confirm | None
1396
+ ) -> Report:
1397
+ report = ctx.report("restore")
1398
+ path = normalize_user_path(file)
1399
+ with ctx.local.lock():
1400
+ for _attempt in range(MAX_CAS_ATTEMPTS):
1401
+ state, view = _prepare(ctx, mutate=True, report=report)
1402
+ cur = view.registered.get(path)
1403
+ if cur is None:
1404
+ raise UsageError(
1405
+ f"{path} is not currently registered",
1406
+ code="not_registered",
1407
+ hint="Re-register it with 'offgit add' before restoring old content",
1408
+ )
1409
+ old = ctx.rpc.call("get_file", project=_project(ctx), revision=revision, path=path)
1410
+ entry = old.get("entry") or {}
1411
+ if not entry.get("registered"):
1412
+ raise UsageError(
1413
+ f"{path} was not registered at revision {revision}", code="not_found"
1414
+ )
1415
+ if entry.get("sha256") == cur.sha256:
1416
+ report.add(path, f"already identical to revision {revision}", "same")
1417
+ report.summary = "No change"
1418
+ return _finish(report, ctx)
1419
+ _require_confirm(
1420
+ confirm,
1421
+ yes,
1422
+ f"Publish {path} from revision {revision} ({short(entry.get('sha256'))}) as a NEW "
1423
+ f"server revision, replacing current {short(cur.sha256)}? Local files are untouched.",
1424
+ )
1425
+ req = ctx.rpc.build(
1426
+ "restore",
1427
+ project=_project(ctx),
1428
+ expected_server_epoch=view.server_epoch,
1429
+ expected_revision=view.revision,
1430
+ path=path,
1431
+ revision=revision,
1432
+ )
1433
+ record = _pending_record(ctx, req, view.server_epoch, view.server_id, {}, [])
1434
+ try:
1435
+ result, state = send_mutation(ctx, state, req, record)
1436
+ except RemoteError as exc:
1437
+ if exc.code == "revision_conflict":
1438
+ continue
1439
+ raise
1440
+ report.add(path, f"restored from revision {revision}", "ok")
1441
+ report.summary = f"Server revision {view.revision} → {result['revision']}"
1442
+ report.notes.append(
1443
+ "Local files were not changed. Run 'offgit pull' to fetch it (local edits are never "
1444
+ "overwritten; differences show as conflicts)."
1445
+ )
1446
+ report.data["revision"] = result["revision"]
1447
+ return _finish(report, ctx)
1448
+ raise ConflictError("Server kept changing; nothing was restored", code="stale_revision")
1449
+
1450
+
1451
+ def cmd_rebaseline(ctx: Context, *, yes: bool, confirm: Confirm | None) -> Report:
1452
+ report = ctx.report("rebaseline")
1453
+ with ctx.local.lock():
1454
+ state = ctx.local.load()
1455
+ view = fetch_view(ctx)
1456
+ require_project(ctx, view)
1457
+ statuses, obs = compute_statuses(ctx, None, view)
1458
+ _require_confirm(
1459
+ confirm,
1460
+ yes,
1461
+ "Rebuild this worktree's sync bases against the current server state? Local files are "
1462
+ "not modified; files that differ become conflicts. Nothing is pushed.",
1463
+ )
1464
+ new = State(
1465
+ project_id=ctx.identity.project_id,
1466
+ canonical_remote=ctx.identity.canonical,
1467
+ remote_name=ctx.remote_name,
1468
+ server_id=view.server_id,
1469
+ server_epoch=view.server_epoch,
1470
+ last_seen_revision=view.revision,
1471
+ )
1472
+ for s in statuses:
1473
+ if s.kind is Kind.IN_SYNC:
1474
+ new.files[s.path] = FileBase(s.remote or "", True, view.revision)
1475
+ report.add(s.path, "base verified (identical)", "ok")
1476
+ elif s.kind is Kind.MISSING:
1477
+ report.add(s.path, "missing locally; 'offgit pull' will restore it", "warn")
1478
+ elif s.kind is Kind.UNSAFE:
1479
+ report.add(s.path, f"unsafe: {s.detail}", "error")
1480
+ else:
1481
+ report.add(s.path, "differs from server; resolve explicitly (offgit diff)", "warn")
1482
+ pending = ctx.local.load_pending()
1483
+ if pending is not None:
1484
+ ctx.local.clear_pending()
1485
+ report.warnings.append(
1486
+ f"Discarded an unsettled {pending.get('operation')} from the previous server epoch"
1487
+ )
1488
+ for op_dir, journal in ctx.local.open_journals():
1489
+ journal["status"] = "abandoned_after_rebaseline"
1490
+ ctx.local.write_journal(op_dir, journal)
1491
+ report.warnings.append(f"Kept recovery copies from an interrupted pull in {op_dir}")
1492
+ ctx.local.save(new)
1493
+ del state, obs
1494
+ report.summary = (
1495
+ f"Rebaselined against server epoch {view.server_epoch[:8]} · revision {view.revision}"
1496
+ )
1497
+ return _finish(report, ctx)
1498
+
1499
+
1500
+ def cmd_projects(cfg: Config, transport: Transport | None = None) -> Report:
1501
+ rpc, _label = make_rpc(cfg, transport)
1502
+ report = Report(command="projects", server=f"{cfg.require_server().host}")
1503
+ res = rpc.call("projects")
1504
+ rows = [
1505
+ [
1506
+ p["canonical_remote"],
1507
+ str(p["revision"]),
1508
+ str(p["files"]),
1509
+ str(p["bytes"]),
1510
+ p["updated_at"],
1511
+ ]
1512
+ for p in res.get("projects", [])
1513
+ ]
1514
+ report.table = {
1515
+ "columns": ["repository", "revision", "files", "bytes", "updated (UTC)"],
1516
+ "rows": rows,
1517
+ }
1518
+ report.data["projects"] = res.get("projects", [])
1519
+ report.summary = f"{len(rows)} project{'s' if len(rows) != 1 else ''}"
1520
+ report.summary_style = "info"
1521
+ return report
1522
+
1523
+
1524
+ def cmd_doctor(
1525
+ cfg: Config, *, cwd: str | None = None, transport: Transport | None = None
1526
+ ) -> Report:
1527
+ report = Report(command="doctor")
1528
+ checks: list[dict[str, Any]] = []
1529
+
1530
+ def check(name: str, ok: bool, detail: str, level: str | None = None) -> None:
1531
+ checks.append({"check": name, "ok": ok, "detail": detail})
1532
+ report.add(name, detail, level or ("ok" if ok else "error"))
1533
+
1534
+ git = shutil.which("git")
1535
+ check("git", bool(git), git or "not found on PATH")
1536
+ try:
1537
+ from offgit.transport import ssh_executable
1538
+
1539
+ ssh = ssh_executable()
1540
+ check("ssh", True, ssh)
1541
+ except OffgitError as exc:
1542
+ check("ssh", False, exc.message)
1543
+ check(
1544
+ "config",
1545
+ cfg.server is not None,
1546
+ str(cfg.path) if cfg.server else "not configured (offgit configure)",
1547
+ )
1548
+ failure: OffgitError | None = None
1549
+ if cfg.server is not None:
1550
+ try:
1551
+ rpc, _label = make_rpc(cfg, transport)
1552
+ t0 = time.monotonic()
1553
+ hello = rpc.call("hello")
1554
+ latency = (time.monotonic() - t0) * 1000
1555
+ server = rpc.last_server or {}
1556
+ check(
1557
+ "server",
1558
+ True,
1559
+ f"{cfg.server.host}: offgit {hello.get('server_version')} protocol {hello.get('protocol_versions')} ({latency:.0f} ms)",
1560
+ )
1561
+ check(
1562
+ "server identity",
1563
+ True,
1564
+ f"id {server.get('id')} epoch {server.get('epoch')}",
1565
+ "info",
1566
+ )
1567
+ backup = hello.get("backup") or {}
1568
+ if backup.get("configured"):
1569
+ age = backup.get("last_success_age_seconds")
1570
+ ok = backup.get("last_result") == "ok" and isinstance(age, int) and age < 3 * 3600
1571
+ check(
1572
+ "backup",
1573
+ ok,
1574
+ f"last result {backup.get('last_result')}, last success "
1575
+ + (f"{age}s ago" if isinstance(age, int) else "never"),
1576
+ None if ok else "warn",
1577
+ )
1578
+ else:
1579
+ check("backup", False, "no backup health recorded on server", "warn")
1580
+ report.data["limits"] = hello.get("limits")
1581
+ except OffgitError as exc:
1582
+ check("server", False, exc.message)
1583
+ failure = exc
1584
+ try:
1585
+ wt = gitrepo.find_worktree(cwd)
1586
+ local = LocalStore(wt.git_dir)
1587
+ state = local.load()
1588
+ remote_name = (state.remote_name if state else None) or cfg.default_remote
1589
+ try:
1590
+ url = gitrepo.remote_url(wt.root, remote_name)
1591
+ ident = identity_from_url(url, cfg.host_aliases)
1592
+ check(
1593
+ "repository",
1594
+ True,
1595
+ f"{ident.canonical} via {remote_name} ({redact_url(url)})",
1596
+ "info",
1597
+ )
1598
+ except OffgitError as exc:
1599
+ check("repository", False, exc.message, "warn")
1600
+ if local.load_pending():
1601
+ check("pending", False, "interrupted operation pending", "warn")
1602
+ except OffgitError:
1603
+ pass
1604
+ report.data["checks"] = checks
1605
+ if failure is not None:
1606
+ report.exit_code = failure.exit_code if failure.exit_code != 1 else EXIT_CONNECTIVITY
1607
+ report.summary = "Server check failed"
1608
+ report.summary_style = "error"
1609
+ elif cfg.server is None:
1610
+ report.exit_code = EXIT_USAGE
1611
+ report.summary = "offgit is not configured"
1612
+ report.summary_style = "error"
1613
+ else:
1614
+ report.summary = "All essential checks passed"
1615
+ return report
1616
+
1617
+
1618
+ __all__ = [
1619
+ "EXIT_PARTIAL",
1620
+ "Context",
1621
+ "cmd_add",
1622
+ "cmd_diff",
1623
+ "cmd_doctor",
1624
+ "cmd_history",
1625
+ "cmd_init",
1626
+ "cmd_list",
1627
+ "cmd_projects",
1628
+ "cmd_pull",
1629
+ "cmd_push",
1630
+ "cmd_rebaseline",
1631
+ "cmd_remove",
1632
+ "cmd_restore",
1633
+ "cmd_status",
1634
+ "cmd_sync",
1635
+ "open_context",
1636
+ ]