irsync 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.
irsync/cli.py ADDED
@@ -0,0 +1,275 @@
1
+ """Command-line interface for irsync."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import logging
7
+ import os
8
+ import sys
9
+ from pathlib import Path
10
+
11
+ from irsync import __version__
12
+
13
+
14
+ def _build_parser() -> argparse.ArgumentParser:
15
+ parser = argparse.ArgumentParser(
16
+ prog="irsync",
17
+ description=(
18
+ f'"Intelligent rsync" version {__version__}. A rename-aware Python wrapper around '
19
+ "rsync. Before each backup, irsync compares an inode snapshot of the source tree "
20
+ "against the previous snapshot to detect moves/renames; those moves are replayed "
21
+ "atomically on the backup tree before rsync runs, so renamed multi-GB files are "
22
+ "not retransferred. If nothing changed since the last backup, the backup drive is "
23
+ "never accessed."
24
+ ),
25
+ )
26
+ parser.add_argument(
27
+ "source_arg",
28
+ nargs="?",
29
+ type=str,
30
+ help=(
31
+ "Source: a full path, a configured drive id (usually a drive "
32
+ "letter), a configured endpoint name such as '~' for the home "
33
+ "directory or 'mypython' for the Python directory, 'ALL' to back "
34
+ "up every entry in the configured backup order, or an rsync "
35
+ "remote like host:/path. Every shorthand needs a drive config, "
36
+ "and so does a bare path given without a DESTINATION (it must "
37
+ "be checked against the config before it can be treated as a "
38
+ "plain path); a path given together with a DESTINATION does not."
39
+ ),
40
+ )
41
+ parser.add_argument(
42
+ "destination_arg",
43
+ nargs="?",
44
+ type=str,
45
+ help=(
46
+ "Destination. Optional when SOURCE is a configured drive id or "
47
+ "endpoint name; in those cases it comes from the drive config."
48
+ ),
49
+ )
50
+ parser.add_argument(
51
+ "--ssh-port", type=int, metavar="PORT", help="SSH port for remote endpoints."
52
+ )
53
+ parser.add_argument(
54
+ "--ssh-key",
55
+ type=str,
56
+ metavar="PATH",
57
+ help="SSH identity file for remote endpoints.",
58
+ )
59
+ parser.add_argument(
60
+ "--config",
61
+ metavar="PATH",
62
+ help=(
63
+ "Drive config file to use instead of the discovered one "
64
+ "($DRIVECFG_CONFIG, then $XDG_CONFIG_HOME/drivecfg/drives.toml)."
65
+ ),
66
+ )
67
+ parser.add_argument(
68
+ "--no-exclude",
69
+ action="store_true",
70
+ help="Do not apply the default exclude list.",
71
+ )
72
+ parser.add_argument(
73
+ "--allow-unmounted",
74
+ action="store_true",
75
+ help=(
76
+ "Proceed even when a drive under the media base directory is not "
77
+ "mounted. Without this, irsync refuses, because an unmounted drive "
78
+ "looks like an empty tree and would wipe its own backup."
79
+ ),
80
+ )
81
+ parser.add_argument(
82
+ "--require-mount",
83
+ action="store_true",
84
+ help=(
85
+ "Apply the mountpoint check to endpoints outside the media base "
86
+ "directory too."
87
+ ),
88
+ )
89
+ parser.add_argument(
90
+ "--allow-nonempty-dest",
91
+ action="store_true",
92
+ help=(
93
+ "Allow a first backup (no prior snapshot) into a destination that "
94
+ "already contains files. Without this, irsync refuses, because "
95
+ "rsync --delete-before would remove them."
96
+ ),
97
+ )
98
+ parser.add_argument(
99
+ "--allow-empty-source",
100
+ action="store_true",
101
+ help=(
102
+ "Allow a backup with no prior snapshot to proceed even though the "
103
+ "source is empty. Without this, irsync refuses, because an empty "
104
+ "source with no baseline is the signature of an unmounted or "
105
+ "mistyped source, and rsync --delete-before would erase the "
106
+ "destination."
107
+ ),
108
+ )
109
+ parser.add_argument(
110
+ "-y", "--yes", action="store_true", help="Skip the confirmation prompt."
111
+ )
112
+ parser.add_argument(
113
+ "--force",
114
+ action="store_true",
115
+ help="Run rsync even when the source snapshot shows no changes.",
116
+ )
117
+ parser.add_argument(
118
+ "--allow-massive-delete",
119
+ action="store_true",
120
+ help=(
121
+ "Bypass the refusal when the diff would delete more than half of "
122
+ "the previously-recorded entries."
123
+ ),
124
+ )
125
+ parser.add_argument(
126
+ "--no-snapshot",
127
+ action="store_true",
128
+ help="Skip the snapshot/diff/replay layer and run rsync directly against the source and destination.",
129
+ )
130
+ parser.add_argument(
131
+ "--snapshot-only",
132
+ action="store_true",
133
+ help="Take a snapshot of SOURCE, write it next to the source, and exit. No backup.",
134
+ )
135
+ parser.add_argument(
136
+ "--dry-run",
137
+ action="store_true",
138
+ help="Show what would be moved and rsync's --dry-run output, but apply nothing.",
139
+ )
140
+ parser.add_argument(
141
+ "-d", "--debug", action="store_true", help="Enable debug logging."
142
+ )
143
+ parser.add_argument(
144
+ "-v", "--version", action="version", version=f"%(prog)s {__version__}"
145
+ )
146
+ return parser
147
+
148
+
149
+ def main(argv: list[str] | None = None) -> int:
150
+ """CLI entry point. Returns the process exit code."""
151
+ from irsync.backup import EXIT_REFUSED, run_all_backups, run_backup
152
+ from irsync.options import Options, needs_drive_config
153
+
154
+ parser = _build_parser()
155
+
156
+ if argv is None:
157
+ argv = sys.argv[1:]
158
+
159
+ if not argv:
160
+ parser.print_help()
161
+ return 0
162
+
163
+ args = parser.parse_args(argv)
164
+
165
+ if args.ssh_port is not None and not (1 <= args.ssh_port <= 65535):
166
+ parser.error("--ssh-port must be in 1..65535")
167
+ if args.ssh_key is not None and not Path(args.ssh_key).expanduser().is_file():
168
+ parser.error(f"--ssh-key file does not exist: {args.ssh_key}")
169
+ # NEW-M2 (5th-pass). --force only takes effect inside the snapshot diff
170
+ # branch (the no-changes short-circuit). Combined with --no-snapshot it
171
+ # does nothing; reject upfront so the user notices rather than running
172
+ # with one of their flags silently ignored. --allow-massive-delete has
173
+ # its own, identical conflict check just below.
174
+ if args.force and args.no_snapshot:
175
+ parser.error(
176
+ "--force has no effect with --no-snapshot (the snapshot diff is "
177
+ "what --force overrides). Drop one of --force or --no-snapshot."
178
+ )
179
+ if args.allow_massive_delete and args.no_snapshot:
180
+ parser.error(
181
+ "--allow-massive-delete has no effect with --no-snapshot (the "
182
+ "snapshot diff is what it overrides). Drop one of them."
183
+ )
184
+
185
+ logging.basicConfig(
186
+ level=logging.DEBUG if args.debug else logging.INFO,
187
+ format="%(asctime)s - %(levelname)s - %(message)s",
188
+ datefmt="%Y-%m-%d %H:%M:%S",
189
+ )
190
+
191
+ if not args.source_arg:
192
+ parser.print_help()
193
+ return 0
194
+
195
+ from irsync.preflight import (
196
+ EndpointNotMounted,
197
+ RsyncUnavailable,
198
+ UnsafeDestination,
199
+ )
200
+
201
+ # The config is loaded lazily, and only when the arguments actually need
202
+ # it: `irsync SRC DEST` on plain paths must keep working on a machine that
203
+ # has no drives.toml, so it must not even attempt discovery. Everything
204
+ # that cannot be resolved without a config fails closed instead.
205
+ #
206
+ # --snapshot-only sits between the two. It takes no destination, so its
207
+ # source could equally be a configured name or an ordinary directory, and
208
+ # only the config can say which. So consult the config when there is one
209
+ # (resolve_source prefers a configured name), but treat a config that is
210
+ # simply absent as "there is no configured name", not as a refusal — any
211
+ # OTHER config error (unreadable, malformed, invalid) still refuses, since
212
+ # silently ignoring a broken config is how a run ends up somewhere the
213
+ # user did not intend.
214
+ required = needs_drive_config(
215
+ args.source_arg, args.destination_arg, snapshot_only=args.snapshot_only
216
+ )
217
+ optional = (
218
+ not required
219
+ and args.snapshot_only
220
+ and not args.destination_arg
221
+ and bool(args.source_arg.strip())
222
+ )
223
+ if args.config or required or optional:
224
+ from drivecfg import ConfigError, ConfigNotFoundError, load_config
225
+
226
+ # ENV_VAR is not re-exported from the package root, so take it from
227
+ # the module that owns it rather than hardcoding the variable name.
228
+ from drivecfg.discovery import ENV_VAR
229
+
230
+ # "Not found" is only tolerable when it was *discovery* that came up
231
+ # empty. A config named explicitly (--config, or $DRIVECFG_CONFIG)
232
+ # that isn't there is a typo, and quietly carrying on would run
233
+ # against a different layout than the one the user named.
234
+ #
235
+ # Presence, not truthiness: drivecfg treats a set-but-EMPTY
236
+ # DRIVECFG_CONFIG as a broken explicit path (it is what a shell
237
+ # template interpolating an unset variable produces) and refuses it.
238
+ # Stripping the value before asking would make irsync disagree,
239
+ # swallow that refusal, and fall back to a literal path.
240
+ explicit = args.config is not None or ENV_VAR in os.environ
241
+ try:
242
+ options = Options.from_drive_config(load_config(args.config))
243
+ except ConfigNotFoundError as exc:
244
+ if explicit or required:
245
+ logging.error("%s", exc)
246
+ return EXIT_REFUSED
247
+ options = Options.without_drive_config()
248
+ except ConfigError as exc:
249
+ logging.error("%s", exc)
250
+ return EXIT_REFUSED
251
+ else:
252
+ options = Options.without_drive_config()
253
+
254
+ try:
255
+ if args.source_arg.strip().upper() == "ALL":
256
+ if args.destination_arg:
257
+ parser.error("Destination is not allowed when SOURCE is 'ALL'.")
258
+ return run_all_backups(options=options, args=args)
259
+ return run_backup(
260
+ source_arg=args.source_arg,
261
+ destination_arg=args.destination_arg,
262
+ options=options,
263
+ args=args,
264
+ )
265
+ except (
266
+ EndpointNotMounted,
267
+ UnsafeDestination,
268
+ RsyncUnavailable,
269
+ FileNotFoundError,
270
+ NotADirectoryError,
271
+ PermissionError,
272
+ ValueError,
273
+ ) as e:
274
+ logging.error("%s", e)
275
+ return EXIT_REFUSED