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/options.py ADDED
@@ -0,0 +1,400 @@
1
+ """Configuration knobs and source/dest argument resolution for the irsync CLI."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass, field
6
+ from pathlib import Path
7
+
8
+ from drivecfg import Drive, DriveConfig, UnknownDriveError
9
+
10
+ from irsync.paths import ensure_local_dir, is_rsync_remote
11
+
12
+ ALL_ARG = "ALL"
13
+ """Source argument meaning "every entry in the configured backup order"."""
14
+
15
+
16
+ @dataclass
17
+ class Options:
18
+ """Path knobs and defaults for the backup workflow.
19
+
20
+ The drive list, named endpoints, and backup order all come from a
21
+ :class:`drivecfg.DriveConfig`; nothing about a particular machine is
22
+ hardcoded here. ``base_dir`` keeps a default because it is only used as
23
+ the mount-gate root (see :func:`irsync.preflight.check_mounted`), which
24
+ can refuse a run but can never redirect one.
25
+
26
+ Attributes:
27
+ base_dir: Parent directory of every drive; the mount-gate root.
28
+ drive_config: The loaded layout, or None for a plain-path run.
29
+ exclude_dirs: Directory names rsync is told to skip by default.
30
+ max_errors: How many failures an ``ALL`` run tolerates before stopping.
31
+ """
32
+
33
+ base_dir: Path
34
+ drive_config: DriveConfig | None = None
35
+ exclude_dirs: list[str] = field(
36
+ default_factory=lambda: [".Trash-1000", ".cache", "unfinished_downloads"]
37
+ )
38
+ max_errors: int = 5
39
+
40
+ @property
41
+ def all_backups(self) -> list[str]:
42
+ """The ordered source arguments for a whole-machine (``ALL``) backup.
43
+
44
+ Returns:
45
+ The configured backup order, or an empty list when no config is
46
+ loaded (in which case ``ALL`` never gets this far — the CLI
47
+ refuses first).
48
+ """
49
+ if self.drive_config is None:
50
+ return []
51
+ return list(self.drive_config.backup_order)
52
+
53
+ @classmethod
54
+ def without_drive_config(cls) -> Options:
55
+ """Build options for a plain-path run, which needs no config file.
56
+
57
+ Returns:
58
+ Options whose only path knowledge is the mount-gate root.
59
+ """
60
+ return cls(base_dir=Path("/") / "media" / Path.home().resolve().name)
61
+
62
+ @classmethod
63
+ def from_drive_config(cls, cfg: DriveConfig) -> Options:
64
+ """Build options from a loaded drive configuration.
65
+
66
+ Args:
67
+ cfg: The layout loaded by drivecfg.
68
+
69
+ Returns:
70
+ Options whose drives, endpoints, backup order, and mount-gate
71
+ root all come from ``cfg``.
72
+ """
73
+ return cls(base_dir=cfg.base_dir, drive_config=cfg)
74
+
75
+
76
+ @dataclass(frozen=True)
77
+ class Endpoints:
78
+ """Resolved source/dest pair plus remote flags for a single backup."""
79
+
80
+ source: Path | str
81
+ dest: Path | str
82
+ source_is_remote: bool
83
+ dest_is_remote: bool
84
+
85
+
86
+ def _is_letter_token(token: str) -> bool:
87
+ """Return True for a single-letter drive shorthand such as ``g``."""
88
+ return len(token) == 1 and token.isalpha()
89
+
90
+
91
+ def needs_drive_config(
92
+ source_arg: str,
93
+ destination_arg: str | None,
94
+ *,
95
+ snapshot_only: bool = False,
96
+ ) -> bool:
97
+ """Return True when this invocation cannot be resolved without a config.
98
+
99
+ Decided from the argument text alone, never from what happens to exist in
100
+ the working directory, so the same command always means the same thing.
101
+ The rules, in order:
102
+
103
+ * ``ALL`` and a single-letter drive id always need one — neither has any
104
+ meaning outside a config, whether or not a destination was given.
105
+ * **Any** source paired with a destination needs none. That is the form
106
+ decision 1 protects (``irsync SRC DEST``), and it also covers ``~`` and
107
+ ``~/sub``, which :func:`resolve_endpoints` hands straight to
108
+ ``Path.expanduser``. Loading a config there would refuse a run that
109
+ never consults it.
110
+ * A source with no destination needs one, because it cannot work without
111
+ it: either the config names it (a drive, ``~``, ``mypython``, or an
112
+ endpoint whose own source path was typed out in full) or the
113
+ invocation is an error.
114
+ * ...unless ``--snapshot-only`` is in play, which takes no destination
115
+ and snapshots any directory. :func:`resolve_source` consults the config
116
+ when there is one and falls back to the literal path when there is not,
117
+ so an absent config is not fatal there.
118
+
119
+ Args:
120
+ source_arg: Raw source argument from the user.
121
+ destination_arg: Raw destination argument, or None.
122
+ snapshot_only: True when ``--snapshot-only`` was passed.
123
+
124
+ Returns:
125
+ True if the caller must load a :class:`drivecfg.DriveConfig` first.
126
+ """
127
+ token = source_arg.strip()
128
+ destination = (destination_arg or "").strip()
129
+ if not token:
130
+ return False
131
+ if token.upper() == ALL_ARG or _is_letter_token(token):
132
+ return True
133
+ if destination:
134
+ return False
135
+ return not snapshot_only
136
+
137
+
138
+ def _require_config(options: Options, source_arg: str) -> DriveConfig:
139
+ """Return the loaded config, or explain that this argument needs one.
140
+
141
+ Args:
142
+ options: The options in play.
143
+ source_arg: The argument that triggered the requirement.
144
+
145
+ Returns:
146
+ The loaded :class:`drivecfg.DriveConfig`.
147
+
148
+ Raises:
149
+ ValueError: If no config was loaded. The message names both ways out,
150
+ since a caller who simply forgot the destination folder needs a
151
+ destination, not a config file.
152
+ """
153
+ if options.drive_config is not None:
154
+ return options.drive_config
155
+ raise ValueError(
156
+ f"The source argument {source_arg!r} has no destination folder, so it "
157
+ "must name a configured drive or endpoint — but no drive config was "
158
+ "loaded. Give a destination folder, or pass --config PATH, set "
159
+ "DRIVECFG_CONFIG, or create drives.toml under $XDG_CONFIG_HOME/drivecfg "
160
+ "(usually ~/.config/drivecfg)."
161
+ )
162
+
163
+
164
+ def _lookup_drive(cfg: DriveConfig, token: str) -> Drive:
165
+ """Look up a drive, converting drivecfg's error into a ValueError.
166
+
167
+ Args:
168
+ cfg: The loaded configuration.
169
+ token: The drive id from the command line, in any case.
170
+
171
+ Returns:
172
+ The matching drive.
173
+
174
+ Raises:
175
+ ValueError: If the token is not a configured drive. The message
176
+ names every configured drive id.
177
+ """
178
+ try:
179
+ return cfg.drive(token)
180
+ except UnknownDriveError as exc:
181
+ raise ValueError(str(exc)) from exc
182
+
183
+
184
+ def _find_drive(cfg: DriveConfig, token: str) -> Drive | None:
185
+ """Return the drive ``token`` names, or None if it names no drive."""
186
+ try:
187
+ return cfg.drive(token)
188
+ except UnknownDriveError:
189
+ return None
190
+
191
+
192
+ def _endpoint_name(cfg: DriveConfig, token: str) -> str | None:
193
+ """Return the endpoint ``token`` names, directly or as its own source path.
194
+
195
+ The path form preserves pre-config behaviour: passing the home directory
196
+ itself (rather than ``~``) resolved to the home backup, and the same held
197
+ for the Python tree. Any endpoint whose configured source resolves to the
198
+ same directory is matched the same way.
199
+
200
+ Args:
201
+ cfg: The loaded configuration.
202
+ token: The source argument.
203
+
204
+ Returns:
205
+ The endpoint name, or None if nothing matches.
206
+ """
207
+ if token in cfg.endpoints:
208
+ return token
209
+ candidate = Path(token).expanduser().resolve()
210
+ for name in cfg.endpoints:
211
+ source, _dest = cfg.endpoint(name)
212
+ if source.expanduser().resolve() == candidate:
213
+ return name
214
+ return None
215
+
216
+
217
+ def _find_named(cfg: DriveConfig, token: str) -> tuple[Path, Path] | None:
218
+ """Return the ``(source, dest)`` pair ``token`` names, or None for neither.
219
+
220
+ Args:
221
+ cfg: The loaded configuration.
222
+ token: A drive id, an endpoint name, or an endpoint's own source path.
223
+
224
+ Returns:
225
+ The configured pair, or None when the config knows nothing by that
226
+ name. Callers decide whether "not a configured name" is an error
227
+ (:func:`resolve_endpoints`, which has no other way to find a
228
+ destination) or a cue to treat the token as a literal path
229
+ (:func:`resolve_source`, which needs no destination).
230
+ """
231
+ drive = _find_drive(cfg, token)
232
+ if drive is not None:
233
+ return drive.path, drive.backup_path
234
+ name = _endpoint_name(cfg, token)
235
+ if name is None:
236
+ return None
237
+ return cfg.endpoint(name)
238
+
239
+
240
+ def _resolve_named(cfg: DriveConfig, token: str) -> tuple[Path, Path]:
241
+ """Resolve a destination-less source argument against the config.
242
+
243
+ Args:
244
+ cfg: The loaded configuration.
245
+ token: A drive id or endpoint name.
246
+
247
+ Returns:
248
+ The ``(source, dest)`` pair the config gives for ``token``.
249
+
250
+ Raises:
251
+ ValueError: If ``token`` is neither a configured drive nor a
252
+ configured endpoint. The message names both sets.
253
+ """
254
+ pair = _find_named(cfg, token)
255
+ if pair is None:
256
+ drives = ", ".join(d.id for d in cfg.drives) or "(none)"
257
+ endpoints = ", ".join(cfg.endpoints) or "(none)"
258
+ raise ValueError(
259
+ "Destination folder is required unless the source argument is a "
260
+ f"configured drive or endpoint. The source argument is {token!r}. "
261
+ f"Configured drives: {drives}. Configured endpoints: {endpoints}."
262
+ )
263
+ return pair
264
+
265
+
266
+ def resolve_source(source_arg: str, options: Options) -> Path:
267
+ """Resolve a source-only argument (no destination) to a local directory.
268
+
269
+ Shares the shorthand lookups with :func:`resolve_endpoints` so that
270
+ ``--snapshot-only`` cannot drift into a second, divergent notion of what
271
+ a drive id or endpoint name means. It differs in one deliberate way: with
272
+ no destination to disambiguate against, the question here is only "does
273
+ the config know this name?". A token the config does not know is taken as
274
+ a literal directory, which is what keeps ``cd /mnt && irsync data
275
+ --snapshot-only`` — a bare relative directory name — working, with or
276
+ without a config. A single-letter drive id is the exception: it has no
277
+ meaning outside a config, so it still fails closed.
278
+
279
+ Args:
280
+ source_arg: Raw source argument from the user.
281
+ options: Path knobs and the loaded config, if any.
282
+
283
+ Returns:
284
+ The resolved source directory.
285
+
286
+ Raises:
287
+ ValueError: If the argument is empty, or is a drive id that the
288
+ config does not define (or that has no config to define it).
289
+ FileNotFoundError: If the resolved directory does not exist.
290
+ NotADirectoryError: If the resolved path is not a directory.
291
+ """
292
+ token = source_arg.strip()
293
+ if not token:
294
+ raise ValueError("Source argument is required.")
295
+ if _is_letter_token(token):
296
+ cfg = _require_config(options, token)
297
+ return ensure_local_dir(_lookup_drive(cfg, token).path)
298
+ if options.drive_config is not None:
299
+ named = _find_named(options.drive_config, token)
300
+ if named is not None:
301
+ return ensure_local_dir(named[0])
302
+ return ensure_local_dir(token)
303
+
304
+
305
+ def resolve_endpoints(
306
+ source_arg: str,
307
+ destination_arg: str | None,
308
+ options: Options,
309
+ ) -> Endpoints:
310
+ """Map raw CLI args into resolved endpoints, applying configured shortcuts.
311
+
312
+ A configured drive id expands to that drive's directory and its backup
313
+ directory, both taken from the config; an endpoint name such as ``~`` or
314
+ ``mypython`` expands to the configured source/dest pair. Anything else is
315
+ taken as a literal path or rsync remote (``host:/path``), which needs no
316
+ config.
317
+
318
+ Args:
319
+ source_arg: Raw source argument from the user.
320
+ destination_arg: Raw destination argument, or None.
321
+ options: Path knobs and the loaded config, if any.
322
+
323
+ Returns:
324
+ An :class:`Endpoints` describing the resolved pair.
325
+
326
+ Raises:
327
+ ValueError: If the args are invalid (missing dest, unconfigured
328
+ drive or endpoint, no config loaded, remote-to-remote, recursive
329
+ paths, identical paths).
330
+ FileNotFoundError: If a local source/dest path does not exist.
331
+ NotADirectoryError: If a local source/dest is not a directory.
332
+ """
333
+ source_arg = source_arg.strip()
334
+ if destination_arg is not None:
335
+ destination_arg = destination_arg.strip() or None
336
+
337
+ source: Path | str
338
+ dest: Path | str
339
+
340
+ if not source_arg:
341
+ raise ValueError("Source argument is required.")
342
+
343
+ if _is_letter_token(source_arg) and not destination_arg:
344
+ drive = _lookup_drive(_require_config(options, source_arg), source_arg)
345
+ source = drive.path
346
+ dest = drive.backup_path
347
+ elif destination_arg:
348
+ if _is_letter_token(source_arg):
349
+ source = _lookup_drive(
350
+ _require_config(options, source_arg), source_arg
351
+ ).path
352
+ else:
353
+ source = source_arg
354
+ dest = destination_arg
355
+ else:
356
+ source, dest = _resolve_named(_require_config(options, source_arg), source_arg)
357
+
358
+ source_is_remote = is_rsync_remote(source)
359
+ dest_is_remote = is_rsync_remote(dest)
360
+
361
+ if source_is_remote and dest_is_remote:
362
+ raise ValueError(
363
+ "Remote-to-remote rsync is not supported by this wrapper "
364
+ "(exactly one side must be local)."
365
+ )
366
+
367
+ if not source_is_remote:
368
+ source = ensure_local_dir(source)
369
+ if not dest_is_remote:
370
+ # Allow the destination to not yet exist on first backup if the parent does.
371
+ try:
372
+ dest = ensure_local_dir(dest)
373
+ except FileNotFoundError:
374
+ dest_path = Path(dest).expanduser().resolve()
375
+ if not dest_path.parent.exists():
376
+ raise
377
+ dest = dest_path
378
+
379
+ if not source_is_remote and not dest_is_remote:
380
+ src_p = source if isinstance(source, Path) else Path(source)
381
+ dst_p = dest if isinstance(dest, Path) else Path(dest)
382
+ if src_p == dst_p:
383
+ raise ValueError(
384
+ "Source and destination are the same path. Refusing to run."
385
+ )
386
+ if dst_p.exists() and src_p.is_relative_to(dst_p):
387
+ raise ValueError(
388
+ "Source is inside destination. Refusing to run to avoid recursion/deletion."
389
+ )
390
+ if dst_p.exists() and dst_p.is_relative_to(src_p):
391
+ raise ValueError(
392
+ "Destination is inside source. Refusing to run to avoid recursion/deletion."
393
+ )
394
+
395
+ return Endpoints(
396
+ source=source,
397
+ dest=dest,
398
+ source_is_remote=source_is_remote,
399
+ dest_is_remote=dest_is_remote,
400
+ )
irsync/paths.py ADDED
@@ -0,0 +1,61 @@
1
+ """Path utilities shared across irsync: rsync remote detection and local dir validation."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ import re
7
+ from pathlib import Path
8
+
9
+ REMOTE_RSYNC_RE: re.Pattern[str] = re.compile(r"^(?:[^@\s:/]+@)?[^:\s/]+:.+")
10
+
11
+
12
+ def is_rsync_remote(spec: str | Path) -> bool:
13
+ """Return True for rsync SSH-style endpoints like ``host:/path`` or ``user@host:/path``.
14
+
15
+ Args:
16
+ spec: A path or rsync endpoint string.
17
+
18
+ Returns:
19
+ True if ``spec`` matches rsync's remote endpoint syntax, False otherwise.
20
+ """
21
+ return bool(REMOTE_RSYNC_RE.match(os.fspath(spec)))
22
+
23
+
24
+ def ensure_local_dir(pathlike: str | Path) -> Path:
25
+ """Validate that a local path exists and is a directory; return its resolved form.
26
+
27
+ Args:
28
+ pathlike: A filesystem path (``~`` is expanded).
29
+
30
+ Returns:
31
+ The resolved absolute :class:`pathlib.Path` to the directory.
32
+
33
+ Raises:
34
+ FileNotFoundError: If the path does not exist.
35
+ NotADirectoryError: If the path exists but is not a directory.
36
+ """
37
+ p = Path(pathlike).expanduser().resolve()
38
+ if not p.exists():
39
+ raise FileNotFoundError(f"Path '{p}' does not exist.")
40
+ if not p.is_dir():
41
+ raise NotADirectoryError(f"Path '{p}' is not a directory.")
42
+ return p
43
+
44
+
45
+ def with_trailing_slash(spec: str | Path, *, remote: bool) -> str:
46
+ """Append a trailing slash to ``spec`` while preserving rsync remote syntax.
47
+
48
+ Args:
49
+ spec: Either a local path or a remote rsync endpoint.
50
+ remote: True if ``spec`` is a remote endpoint (``host:/path``).
51
+
52
+ Returns:
53
+ The endpoint string guaranteed to end with ``/``.
54
+ """
55
+ s = os.fspath(spec)
56
+ if remote:
57
+ userhost, path = s.split(":", 1)
58
+ if not path.endswith("/"):
59
+ path += "/"
60
+ return f"{userhost}:{path}"
61
+ return s if s.endswith(os.sep) else (s + os.sep)