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 ADDED
@@ -0,0 +1,4 @@
1
+ """offgit: versioned synchronization for files Git ignores."""
2
+
3
+ __version__ = "0.1.0"
4
+ PROTOCOL_VERSION = 1
offgit/cli.py ADDED
@@ -0,0 +1,498 @@
1
+ """``offgit`` command-line interface."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ import sys
7
+ from collections.abc import Callable
8
+ from dataclasses import dataclass
9
+ from typing import Annotated
10
+
11
+ import typer
12
+
13
+ from offgit import __version__
14
+ from offgit.client import (
15
+ Confirm,
16
+ cmd_add,
17
+ cmd_diff,
18
+ cmd_doctor,
19
+ cmd_history,
20
+ cmd_init,
21
+ cmd_list,
22
+ cmd_projects,
23
+ cmd_pull,
24
+ cmd_push,
25
+ cmd_rebaseline,
26
+ cmd_remove,
27
+ cmd_restore,
28
+ cmd_status,
29
+ cmd_sync,
30
+ open_context,
31
+ )
32
+ from offgit.config import (
33
+ DEFAULT_CONNECT_TIMEOUT,
34
+ DEFAULT_OPERATION_TIMEOUT,
35
+ DEFAULT_SERVER_BINARY,
36
+ Config,
37
+ ServerConfig,
38
+ load_config,
39
+ save_config,
40
+ validate_host,
41
+ validate_remote_name,
42
+ )
43
+ from offgit.errors import EXIT_INTERNAL, ConfigError, OffgitError
44
+ from offgit.output import Output, Report
45
+ from offgit.transport import RpcClient, SSHTransport, Transport
46
+
47
+ # Tests may install an in-process transport here; never set in production.
48
+ TRANSPORT_OVERRIDE: Transport | None = None
49
+
50
+ app = typer.Typer(
51
+ add_completion=False,
52
+ no_args_is_help=True,
53
+ rich_markup_mode=None,
54
+ pretty_exceptions_enable=False,
55
+ context_settings={"help_option_names": ["-h", "--help"]},
56
+ help="offgit: versioned synchronization for files Git ignores.\n\n"
57
+ "Run project commands from the top-level directory of a Git working tree.",
58
+ )
59
+
60
+
61
+ @dataclass
62
+ class Globals:
63
+ json: bool = False
64
+ no_color: bool = False
65
+ verbose: bool = False
66
+ quiet: bool = False
67
+ remote: str | None = None
68
+
69
+
70
+ JsonOpt = Annotated[bool, typer.Option("--json", help="Print one machine-readable JSON document.")]
71
+ NoColorOpt = Annotated[bool, typer.Option("--no-color", help="Disable colors (also NO_COLOR).")]
72
+ VerboseOpt = Annotated[bool, typer.Option("--verbose", "-v", help="More diagnostics on stderr.")]
73
+ QuietOpt = Annotated[bool, typer.Option("--quiet", "-q", help="Only problems and the summary.")]
74
+ RemoteOpt = Annotated[
75
+ str | None,
76
+ typer.Option("--remote", help="Git remote that identifies the project (default: origin)."),
77
+ ]
78
+ DryRunOpt = Annotated[bool, typer.Option("--dry-run", help="Plan only; change nothing.")]
79
+ YesOpt = Annotated[bool, typer.Option("--yes", "-y", help="Confirm without prompting.")]
80
+
81
+
82
+ def _version_cb(value: bool) -> None:
83
+ if value:
84
+ typer.echo(f"offgit {__version__}")
85
+ raise typer.Exit(0)
86
+
87
+
88
+ @app.callback()
89
+ def _main(
90
+ ctx: typer.Context,
91
+ version: Annotated[
92
+ bool,
93
+ typer.Option(
94
+ "--version", callback=_version_cb, is_eager=True, help="Show version and exit."
95
+ ),
96
+ ] = False,
97
+ json_: JsonOpt = False,
98
+ no_color: NoColorOpt = False,
99
+ verbose: VerboseOpt = False,
100
+ quiet: QuietOpt = False,
101
+ remote: RemoteOpt = None,
102
+ ) -> None:
103
+ ctx.obj = Globals(json=json_, no_color=no_color, verbose=verbose, quiet=quiet, remote=remote)
104
+
105
+
106
+ def _g(
107
+ ctx: typer.Context,
108
+ json_: bool = False,
109
+ no_color: bool = False,
110
+ verbose: bool = False,
111
+ quiet: bool = False,
112
+ remote: str | None = None,
113
+ ) -> Globals:
114
+ base: Globals = ctx.obj or Globals()
115
+ return Globals(
116
+ json=base.json or json_,
117
+ no_color=base.no_color or no_color,
118
+ verbose=base.verbose or verbose,
119
+ quiet=base.quiet or quiet,
120
+ remote=remote or base.remote,
121
+ )
122
+
123
+
124
+ def _confirm(g: Globals) -> Confirm | None:
125
+ if g.json or not sys.stdin.isatty():
126
+ return None
127
+
128
+ def ask(prompt: str) -> bool:
129
+ return typer.confirm(prompt, default=False, err=True)
130
+
131
+ return ask
132
+
133
+
134
+ def _run(g: Globals, command: str, fn: Callable[[Output], Report]) -> None:
135
+ out = Output(json_mode=g.json, no_color=g.no_color, quiet=g.quiet, verbose=g.verbose)
136
+ try:
137
+ report = fn(out)
138
+ except OffgitError as exc:
139
+ out.emit_error(command, exc)
140
+ raise typer.Exit(exc.exit_code) from None
141
+ except KeyboardInterrupt:
142
+ out.emit_error(command, OffgitError("Interrupted", code="interrupted"))
143
+ raise typer.Exit(130) from None
144
+ except Exception as exc:
145
+ if os.environ.get("OFFGIT_DEBUG"):
146
+ raise
147
+ err = OffgitError(f"Unexpected error: {type(exc).__name__}: {exc}", code="internal_error")
148
+ out.emit_error(command, err)
149
+ raise typer.Exit(EXIT_INTERNAL) from None
150
+ out.emit(report)
151
+ raise typer.Exit(report.exit_code)
152
+
153
+
154
+ def _context(g: Globals): # type: ignore[no-untyped-def]
155
+ cfg = load_config()
156
+ return open_context(cfg, remote=g.remote, transport=TRANSPORT_OVERRIDE)
157
+
158
+
159
+ # ---------------------------------------------------------------------------
160
+
161
+
162
+ @app.command()
163
+ def configure(
164
+ ctx: typer.Context,
165
+ host: Annotated[str, typer.Option("--host", help="Server host, Tailscale name or SSH alias.")],
166
+ user: Annotated[
167
+ str | None, typer.Option("--user", help="SSH user on the server (e.g. offgit).")
168
+ ] = None,
169
+ port: Annotated[int | None, typer.Option("--port", help="SSH port.")] = None,
170
+ identity: Annotated[
171
+ str | None, typer.Option("--identity", help="Path to a dedicated SSH private key.")
172
+ ] = None,
173
+ server_binary: Annotated[
174
+ str, typer.Option("--server-binary", help="Absolute path of offgit-server on the server.")
175
+ ] = DEFAULT_SERVER_BINARY,
176
+ connect_timeout: Annotated[int, typer.Option("--connect-timeout")] = DEFAULT_CONNECT_TIMEOUT,
177
+ operation_timeout: Annotated[
178
+ int, typer.Option("--operation-timeout")
179
+ ] = DEFAULT_OPERATION_TIMEOUT,
180
+ device_name: Annotated[
181
+ str | None, typer.Option("--device-name", help="Advisory device label.")
182
+ ] = None,
183
+ default_remote: Annotated[str | None, typer.Option("--default-remote")] = None,
184
+ alias: Annotated[
185
+ list[str] | None,
186
+ typer.Option(
187
+ "--host-alias", help="Trusted Git host alias mapping ALIAS=HOST (repeatable)."
188
+ ),
189
+ ] = None,
190
+ no_check: Annotated[
191
+ bool, typer.Option("--no-check", help="Do not test the connection.")
192
+ ] = False,
193
+ json_: JsonOpt = False,
194
+ no_color: NoColorOpt = False,
195
+ ) -> None:
196
+ """Write the global client configuration (tests the connection first)."""
197
+ g = _g(ctx, json_, no_color)
198
+
199
+ def run(out: Output) -> Report:
200
+ try:
201
+ current = load_config()
202
+ except ConfigError:
203
+ current = Config()
204
+ server = ServerConfig(
205
+ host=host,
206
+ user=user,
207
+ port=port,
208
+ identity_file=identity,
209
+ connect_timeout=connect_timeout,
210
+ operation_timeout=operation_timeout,
211
+ server_binary=server_binary,
212
+ )
213
+ server.validate()
214
+ cfg = Config(
215
+ server=server,
216
+ default_remote=default_remote or current.default_remote,
217
+ device_name=device_name or current.device_name,
218
+ host_aliases=dict(current.host_aliases),
219
+ path=current.path,
220
+ )
221
+ for a in alias or []:
222
+ src, sep, dst = a.partition("=")
223
+ if not sep:
224
+ raise ConfigError(f"Invalid --host-alias {a!r}; expected ALIAS=HOST")
225
+ cfg.host_aliases[validate_host(src.strip()).lower()] = validate_host(
226
+ dst.strip()
227
+ ).lower()
228
+ validate_remote_name(cfg.default_remote)
229
+ cfg.validate()
230
+ report = Report(command="configure", server=host)
231
+ if not no_check:
232
+ transport = TRANSPORT_OVERRIDE or SSHTransport(server)
233
+ rpc = RpcClient(transport, device=cfg.device_name, timeout=float(operation_timeout))
234
+ hello = rpc.call("hello")
235
+ report.add("connection", f"ok: offgit-server {hello.get('server_version')}", "ok")
236
+ path = save_config(cfg)
237
+ report.data["config"] = cfg.sanitized()
238
+ report.summary = f"Configuration written to {path}" + (
239
+ " (connection not tested)" if no_check else ""
240
+ )
241
+ return report
242
+
243
+ _run(g, "configure", run)
244
+
245
+
246
+ @app.command()
247
+ def init(
248
+ ctx: typer.Context,
249
+ file: Annotated[
250
+ list[str] | None,
251
+ typer.Option(
252
+ "-f",
253
+ "--file",
254
+ help="File to register (ignored, untracked). Accepts several after one -f.",
255
+ ),
256
+ ] = None,
257
+ more: Annotated[
258
+ list[str] | None, typer.Argument(help="More files (after -f).", show_default=False)
259
+ ] = None,
260
+ json_: JsonOpt = False,
261
+ no_color: NoColorOpt = False,
262
+ verbose: VerboseOpt = False,
263
+ quiet: QuietOpt = False,
264
+ remote: RemoteOpt = None,
265
+ ) -> None:
266
+ """Register the project and upload the selected ignored files atomically."""
267
+ g = _g(ctx, json_, no_color, verbose, quiet, remote)
268
+ files = list(file or []) + list(more or [])
269
+ if more and not file:
270
+ out = Output(json_mode=g.json, no_color=g.no_color, quiet=g.quiet, verbose=g.verbose)
271
+ out.emit_error(
272
+ "init", ConfigError("Use: offgit init -f FILE [FILE...]", code="usage_error")
273
+ )
274
+ raise typer.Exit(2)
275
+ _run(g, "init", lambda out: cmd_init(_context(g), files))
276
+
277
+
278
+ @app.command()
279
+ def push(
280
+ ctx: typer.Context,
281
+ dry_run: DryRunOpt = False,
282
+ prefer_local: Annotated[
283
+ list[str] | None,
284
+ typer.Option(
285
+ "--prefer-local",
286
+ help="Resolve this conflicted file by uploading the local copy (repeatable).",
287
+ ),
288
+ ] = None,
289
+ yes: YesOpt = False,
290
+ json_: JsonOpt = False,
291
+ no_color: NoColorOpt = False,
292
+ verbose: VerboseOpt = False,
293
+ quiet: QuietOpt = False,
294
+ remote: RemoteOpt = None,
295
+ ) -> None:
296
+ """Upload locally changed registered files (never downloads, never deletes)."""
297
+ g = _g(ctx, json_, no_color, verbose, quiet, remote)
298
+ _run(
299
+ g,
300
+ "push",
301
+ lambda out: cmd_push(
302
+ _context(g), dry_run=dry_run, prefer_local=prefer_local, yes=yes, confirm=_confirm(g)
303
+ ),
304
+ )
305
+
306
+
307
+ @app.command()
308
+ def pull(
309
+ ctx: typer.Context,
310
+ dry_run: DryRunOpt = False,
311
+ prefer_remote: Annotated[
312
+ list[str] | None,
313
+ typer.Option(
314
+ "--prefer-remote",
315
+ help="Resolve this conflicted file by taking the server copy (repeatable).",
316
+ ),
317
+ ] = None,
318
+ yes: YesOpt = False,
319
+ json_: JsonOpt = False,
320
+ no_color: NoColorOpt = False,
321
+ verbose: VerboseOpt = False,
322
+ quiet: QuietOpt = False,
323
+ remote: RemoteOpt = None,
324
+ ) -> None:
325
+ """Download server changes and missing files (never overwrites local-only work)."""
326
+ g = _g(ctx, json_, no_color, verbose, quiet, remote)
327
+ _run(
328
+ g,
329
+ "pull",
330
+ lambda out: cmd_pull(
331
+ _context(g), dry_run=dry_run, prefer_remote=prefer_remote, yes=yes, confirm=_confirm(g)
332
+ ),
333
+ )
334
+
335
+
336
+ @app.command()
337
+ def sync(
338
+ ctx: typer.Context,
339
+ dry_run: DryRunOpt = False,
340
+ json_: JsonOpt = False,
341
+ no_color: NoColorOpt = False,
342
+ verbose: VerboseOpt = False,
343
+ quiet: QuietOpt = False,
344
+ remote: RemoteOpt = None,
345
+ ) -> None:
346
+ """Safe bidirectional sync using the same three-way planner."""
347
+ g = _g(ctx, json_, no_color, verbose, quiet, remote)
348
+ _run(g, "sync", lambda out: cmd_sync(_context(g), dry_run=dry_run))
349
+
350
+
351
+ @app.command()
352
+ def status(
353
+ ctx: typer.Context,
354
+ json_: JsonOpt = False,
355
+ no_color: NoColorOpt = False,
356
+ verbose: VerboseOpt = False,
357
+ quiet: QuietOpt = False,
358
+ remote: RemoteOpt = None,
359
+ ) -> None:
360
+ """Show per-file synchronization state (read-only)."""
361
+ g = _g(ctx, json_, no_color, verbose, quiet, remote)
362
+ _run(g, "status", lambda out: cmd_status(_context(g)))
363
+
364
+
365
+ @app.command("list")
366
+ def list_(
367
+ ctx: typer.Context,
368
+ json_: JsonOpt = False,
369
+ no_color: NoColorOpt = False,
370
+ remote: RemoteOpt = None,
371
+ ) -> None:
372
+ """List registered paths with sizes and hashes."""
373
+ g = _g(ctx, json_, no_color, remote=remote)
374
+ _run(g, "list", lambda out: cmd_list(_context(g)))
375
+
376
+
377
+ @app.command()
378
+ def projects(ctx: typer.Context, json_: JsonOpt = False, no_color: NoColorOpt = False) -> None:
379
+ """List all projects known to the server (no file contents)."""
380
+ g = _g(ctx, json_, no_color)
381
+ _run(g, "projects", lambda out: cmd_projects(load_config(), TRANSPORT_OVERRIDE))
382
+
383
+
384
+ @app.command()
385
+ def add(
386
+ ctx: typer.Context,
387
+ files: Annotated[list[str], typer.Argument(help="Existing ignored files to register.")],
388
+ json_: JsonOpt = False,
389
+ no_color: NoColorOpt = False,
390
+ quiet: QuietOpt = False,
391
+ remote: RemoteOpt = None,
392
+ ) -> None:
393
+ """Register more files (never overwrites an existing registration)."""
394
+ g = _g(ctx, json_, no_color, quiet=quiet, remote=remote)
395
+ _run(g, "add", lambda out: cmd_add(_context(g), files))
396
+
397
+
398
+ @app.command()
399
+ def remove(
400
+ ctx: typer.Context,
401
+ files: Annotated[list[str], typer.Argument(help="Registered files to unregister.")],
402
+ yes: YesOpt = False,
403
+ json_: JsonOpt = False,
404
+ no_color: NoColorOpt = False,
405
+ remote: RemoteOpt = None,
406
+ ) -> None:
407
+ """Unregister files on the server for all devices (local files and history are kept)."""
408
+ g = _g(ctx, json_, no_color, remote=remote)
409
+ _run(g, "remove", lambda out: cmd_remove(_context(g), files, yes=yes, confirm=_confirm(g)))
410
+
411
+
412
+ @app.command()
413
+ def diff(
414
+ ctx: typer.Context,
415
+ files: Annotated[
416
+ list[str] | None, typer.Argument(help="Registered files (default: all differing).")
417
+ ] = None,
418
+ json_: JsonOpt = False,
419
+ no_color: NoColorOpt = False,
420
+ remote: RemoteOpt = None,
421
+ ) -> None:
422
+ """Unified diff server -> local (read-only)."""
423
+ g = _g(ctx, json_, no_color, remote=remote)
424
+ _run(g, "diff", lambda out: cmd_diff(_context(g), list(files or [])))
425
+
426
+
427
+ @app.command()
428
+ def history(
429
+ ctx: typer.Context,
430
+ file: Annotated[
431
+ str | None, typer.Argument(help="Only revisions that changed this file.")
432
+ ] = None,
433
+ limit: Annotated[int, typer.Option("--limit", "-n", help="Maximum revisions to show.")] = 20,
434
+ json_: JsonOpt = False,
435
+ no_color: NoColorOpt = False,
436
+ remote: RemoteOpt = None,
437
+ ) -> None:
438
+ """Show recent server revisions."""
439
+ g = _g(ctx, json_, no_color, remote=remote)
440
+ _run(g, "history", lambda out: cmd_history(_context(g), file, limit))
441
+
442
+
443
+ @app.command()
444
+ def restore(
445
+ ctx: typer.Context,
446
+ file: Annotated[str, typer.Argument(help="Registered file.")],
447
+ revision: Annotated[
448
+ int, typer.Option("--revision", "-r", help="Historical revision to publish.")
449
+ ],
450
+ yes: YesOpt = False,
451
+ json_: JsonOpt = False,
452
+ no_color: NoColorOpt = False,
453
+ remote: RemoteOpt = None,
454
+ ) -> None:
455
+ """Publish a historical version as a NEW server revision (local files untouched)."""
456
+ g = _g(ctx, json_, no_color, remote=remote)
457
+ _run(
458
+ g,
459
+ "restore",
460
+ lambda out: cmd_restore(_context(g), file, revision, yes=yes, confirm=_confirm(g)),
461
+ )
462
+
463
+
464
+ @app.command()
465
+ def rebaseline(
466
+ ctx: typer.Context,
467
+ yes: YesOpt = False,
468
+ json_: JsonOpt = False,
469
+ no_color: NoColorOpt = False,
470
+ remote: RemoteOpt = None,
471
+ ) -> None:
472
+ """Re-verify bases after a server restore/epoch change (never pushes, never edits files)."""
473
+ g = _g(ctx, json_, no_color, remote=remote)
474
+ _run(g, "rebaseline", lambda out: cmd_rebaseline(_context(g), yes=yes, confirm=_confirm(g)))
475
+
476
+
477
+ @app.command()
478
+ def doctor(ctx: typer.Context, json_: JsonOpt = False, no_color: NoColorOpt = False) -> None:
479
+ """Check Git, SSH, configuration, server protocol, identity and backup health."""
480
+ g = _g(ctx, json_, no_color)
481
+
482
+ def run(out: Output) -> Report:
483
+ try:
484
+ cfg = load_config()
485
+ except ConfigError as exc:
486
+ rep = Report(command="doctor", exit_code=exc.exit_code, error=exc)
487
+ return rep
488
+ return cmd_doctor(cfg, transport=TRANSPORT_OVERRIDE)
489
+
490
+ _run(g, "doctor", run)
491
+
492
+
493
+ def main() -> None:
494
+ app(prog_name="offgit")
495
+
496
+
497
+ if __name__ == "__main__": # pragma: no cover
498
+ main()