hlsync 1.19.1__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.

Potentially problematic release.


This version of hlsync might be problematic. Click here for more details.

hlsync/cli.py ADDED
@@ -0,0 +1,3038 @@
1
+ from __future__ import annotations
2
+
3
+ import argparse
4
+ import os
5
+ import shlex
6
+ import shutil
7
+ import sys
8
+ import time
9
+ from collections.abc import Callable, Sequence
10
+ from contextlib import ExitStack
11
+ from dataclasses import dataclass, replace
12
+ from pathlib import Path, PurePosixPath
13
+ from typing import TextIO, TypeVar
14
+
15
+ from hlsync import __version__
16
+ from hlsync.comparison import (
17
+ ComparisonEntry,
18
+ ComparisonPlan,
19
+ build_comparison,
20
+ mark_untraversed_directories,
21
+ )
22
+ from hlsync.config import (
23
+ DEFAULT_PASSWORD_ENV,
24
+ DEFAULT_USERNAME_ENV,
25
+ ApplicationConfiguration,
26
+ CommonRuleStore,
27
+ ConfigurationError,
28
+ ConfigurationStore,
29
+ ProfileConfiguration,
30
+ RuleUpdate,
31
+ canonical_local_root,
32
+ validate_profile_name,
33
+ )
34
+ from hlsync.gitignore import GitIgnores
35
+ from hlsync.pattern_operands import (
36
+ PatternOperandError,
37
+ add_pattern_operands,
38
+ normalize_pattern_operands,
39
+ )
40
+ from hlsync.progress import DirectoryReadProgress
41
+ from hlsync.rules import (
42
+ RuleError,
43
+ RuleSet,
44
+ SyncRule,
45
+ patterns_from_common_operands,
46
+ patterns_from_operands,
47
+ patterns_from_remote_operands,
48
+ )
49
+ from hlsync.selection import (
50
+ DirectoryContentsSelection,
51
+ FileSelection,
52
+ FileSelector,
53
+ FileSelectorSet,
54
+ SelectionError,
55
+ )
56
+ from hlsync.snapshot import (
57
+ SnapshotError,
58
+ TreeEntry,
59
+ TreeSnapshot,
60
+ list_local_directory,
61
+ snapshot_local,
62
+ )
63
+ from hlsync.transfer import (
64
+ TransferError,
65
+ TransferIssue,
66
+ TransferOperation,
67
+ TransferResult,
68
+ execute_transfer,
69
+ )
70
+ from hlsync.transport import ExplicitFTPSTransport, PathOperationError, TransportError
71
+
72
+ _EntryT = TypeVar("_EntryT")
73
+
74
+ _RESET = "\033[0m"
75
+ _DIRECTORY_COLOR = "\033[38;5;75m"
76
+ _EXCLUDED_DIRECTORY_COLOR = "\033[38;5;24m"
77
+ _COLLAPSED_DIRECTORY_COLOR = "\033[3;38;5;24m"
78
+ _DIFF_MARKER_COLORS = {
79
+ "+": "\033[38;5;82m",
80
+ "~": "\033[33m",
81
+ "-": "\033[31m",
82
+ "?": "\033[35m",
83
+ "x": "\033[90m",
84
+ "#": "\033[90m",
85
+ "r": "\033[38;5;30m",
86
+ "l": "\033[38;5;51m",
87
+ }
88
+ _TRANSFER_MARKERS = {
89
+ "add": "+",
90
+ "update": "~",
91
+ "delete": "-",
92
+ "create": "+",
93
+ }
94
+
95
+
96
+ @dataclass(frozen=True)
97
+ class _DiffTraversalRoot:
98
+ path: PurePosixPath
99
+ include_container: bool = False
100
+
101
+
102
+ @dataclass(frozen=True)
103
+ class _PendingDiffDirectory:
104
+ path: PurePosixPath
105
+ has_local: bool
106
+ has_remote: bool
107
+ include_container: bool
108
+ is_root: bool
109
+ display_root: PurePosixPath | None
110
+ display_anchor: bool
111
+
112
+
113
+ @dataclass(frozen=True)
114
+ class _PendingDiffOutput:
115
+ entry: ComparisonEntry
116
+ collapsed_paths: frozenset[str]
117
+ display_root: PurePosixPath | None
118
+
119
+
120
+ CANONICAL_COMMANDS = (
121
+ "create",
122
+ "connect",
123
+ "map",
124
+ "remove",
125
+ "root",
126
+ "profile",
127
+ "profiles",
128
+ "list",
129
+ "diff",
130
+ "push",
131
+ "pull",
132
+ "rules",
133
+ "exclude",
134
+ "include",
135
+ "help",
136
+ "version",
137
+ )
138
+ COMMAND_ALIASES = {"ls": "list", "lsr": "list"}
139
+ PROFILE_AWARE_COMMANDS = frozenset(
140
+ {
141
+ "connect",
142
+ "map",
143
+ "remove",
144
+ "root",
145
+ "profile",
146
+ "list",
147
+ "diff",
148
+ "push",
149
+ "pull",
150
+ "rules",
151
+ "exclude",
152
+ "include",
153
+ }
154
+ )
155
+
156
+
157
+ def _add_included_only_argument(parser: argparse.ArgumentParser) -> None:
158
+ parser.add_argument(
159
+ "-i",
160
+ "--inc",
161
+ "--included-only",
162
+ dest="included_only",
163
+ action="store_true",
164
+ help="show only included paths",
165
+ )
166
+
167
+
168
+ def _active_options(arguments: argparse.Namespace) -> str | None:
169
+ options: list[str] = []
170
+ if getattr(arguments, "remote", False):
171
+ options.append("remote (--remote)")
172
+ if getattr(arguments, "pull", False):
173
+ options.append("pull perspective (--pull)")
174
+ if getattr(arguments, "recursive", False):
175
+ options.append("recursive (-r)")
176
+ if getattr(arguments, "shallow", False):
177
+ options.append("shallow (-s)")
178
+ if getattr(arguments, "show_all", False):
179
+ options.append("all entries (-a)")
180
+ if getattr(arguments, "included_only", False):
181
+ options.append("included paths only (-i)")
182
+ if getattr(arguments, "show_excluded", False):
183
+ options.append("excluded paths (-x)")
184
+ if getattr(arguments, "include_excluded", False):
185
+ options.append("include excluded paths (-I)")
186
+ if getattr(arguments, "prune", False):
187
+ options.append("prune remote-only paths (-p)")
188
+ if getattr(arguments, "force", False):
189
+ options.append("overwrite newer destinations (--force)")
190
+ if getattr(arguments, "dry", False):
191
+ options.append("dry run (--dry)")
192
+ if getattr(arguments, "paged", False):
193
+ options.append("paged output (--paged)")
194
+ if getattr(arguments, "resume", None) is not None:
195
+ options.append(f"resume at {arguments.resume!r} (--resume)")
196
+ if not options:
197
+ return None
198
+ return f"Options: {'; '.join(options)}."
199
+
200
+
201
+ def _add_recursive_depth_arguments(parser: argparse.ArgumentParser) -> None:
202
+ depth = parser.add_mutually_exclusive_group()
203
+ depth.add_argument(
204
+ "-r", "--recursive", action="store_true",
205
+ help="recurse into selected directories (default)",
206
+ )
207
+ depth.add_argument(
208
+ "-s", "--shallow", action="store_true",
209
+ help="process immediate contents without entering child directories",
210
+ )
211
+
212
+
213
+ DEFAULT_UPLOAD_JOBS = 4
214
+ MAX_UPLOAD_JOBS = 10
215
+
216
+
217
+ def _upload_job_count(value: str) -> int:
218
+ if not value.isdigit() or not 1 <= int(value) <= MAX_UPLOAD_JOBS:
219
+ raise argparse.ArgumentTypeError(
220
+ f"must be a whole number from 1 to {MAX_UPLOAD_JOBS}"
221
+ )
222
+ return int(value)
223
+
224
+
225
+ def _open_upload_sessions(
226
+ profile: ProfileConfiguration,
227
+ jobs: int,
228
+ files: int,
229
+ sessions: ExitStack,
230
+ progress: TextIO,
231
+ ) -> tuple[ExplicitFTPSTransport, ...]:
232
+ wanted = min(jobs, files)
233
+ opened: list[ExplicitFTPSTransport] = []
234
+ refusal: TransportError | None = None
235
+ for _ in range(wanted - 1):
236
+ try:
237
+ opened.append(sessions.enter_context(ExplicitFTPSTransport(profile)))
238
+ except TransportError as error:
239
+ refusal = error
240
+ break
241
+ connections = len(opened) + 1
242
+ noun = "connection" if connections == 1 else "connections"
243
+ if refusal is not None:
244
+ message = (
245
+ f"Using {connections} of {wanted} connections; "
246
+ f"the server refused more: {refusal}"
247
+ )
248
+ elif wanted < jobs:
249
+ message = f"Using {connections} {noun}, one per file."
250
+ else:
251
+ message = f"Using {connections} {noun}."
252
+ print(message, file=progress, flush=True)
253
+ return tuple(opened)
254
+
255
+
256
+ def _add_include_excluded_argument(parser: argparse.ArgumentParser) -> None:
257
+ parser.add_argument(
258
+ "-I", "--include-excluded", action="store_true",
259
+ help="treat locally excluded paths as included for this command",
260
+ )
261
+
262
+
263
+ def _resolve_command_name(
264
+ value: str,
265
+ *,
266
+ stdin: TextIO | None = None,
267
+ stdout: TextIO | None = None,
268
+ ) -> str:
269
+ if value in CANONICAL_COMMANDS:
270
+ return value
271
+ if value in COMMAND_ALIASES:
272
+ return COMMAND_ALIASES[value]
273
+ matches = tuple(
274
+ command for command in CANONICAL_COMMANDS if command.startswith(value)
275
+ )
276
+ if not matches:
277
+ raise ConfigurationError(f"unknown command '{value}'")
278
+ if len(matches) > 1:
279
+ is_terminal = getattr(stdin, "isatty", None)
280
+ if stdin is not None and stdout is not None and is_terminal and is_terminal():
281
+ print(f"'{value}' matches multiple commands:\n", file=stdout)
282
+ for index, command in enumerate(matches, start=1):
283
+ print(f" {index}. {command}", file=stdout)
284
+ while True:
285
+ print(
286
+ f"\nChoose a command [1-{len(matches)}]: ",
287
+ end="",
288
+ file=stdout,
289
+ flush=True,
290
+ )
291
+ answer = stdin.readline()
292
+ if answer == "":
293
+ raise ConfigurationError("command selection cancelled")
294
+ try:
295
+ selection = int(answer.strip())
296
+ except ValueError:
297
+ selection = 0
298
+ if 1 <= selection <= len(matches):
299
+ return matches[selection - 1]
300
+ print("Enter one of the listed numbers.", file=stdout)
301
+ raise ConfigurationError(
302
+ f"ambiguous command '{value}': {', '.join(matches)}"
303
+ )
304
+ return matches[0]
305
+
306
+
307
+ def _could_be_command(value: str) -> bool:
308
+ return value in COMMAND_ALIASES or any(
309
+ command.startswith(value) for command in CANONICAL_COMMANDS
310
+ )
311
+
312
+
313
+ def _resolve_invocation(
314
+ raw_arguments: list[str],
315
+ *,
316
+ stdin: TextIO,
317
+ stdout: TextIO,
318
+ ) -> tuple[list[str], str | None]:
319
+ if not raw_arguments or raw_arguments[0].startswith("-"):
320
+ return raw_arguments, None
321
+ first = raw_arguments[0]
322
+ if (
323
+ first not in CANONICAL_COMMANDS
324
+ and first not in COMMAND_ALIASES
325
+ and len(raw_arguments) > 1
326
+ and not raw_arguments[1].startswith("-")
327
+ and _could_be_command(raw_arguments[1])
328
+ ):
329
+ profile_name = validate_profile_name(first)
330
+ raw_arguments = raw_arguments[1:]
331
+ remote_list_alias = raw_arguments[0] == "lsr"
332
+ raw_arguments[0] = _resolve_command_name(
333
+ raw_arguments[0], stdin=stdin, stdout=stdout
334
+ )
335
+ if remote_list_alias:
336
+ raw_arguments.insert(1, "--remote")
337
+ return raw_arguments, profile_name
338
+ remote_list_alias = first == "lsr"
339
+ raw_arguments[0] = _resolve_command_name(first, stdin=stdin, stdout=stdout)
340
+ if remote_list_alias:
341
+ raw_arguments.insert(1, "--remote")
342
+ return raw_arguments, None
343
+
344
+
345
+ def _validate_profile_prefix(arguments: argparse.Namespace) -> None:
346
+ profile_name = getattr(arguments, "profile_prefix", None)
347
+ if profile_name is not None and getattr(arguments, "common_rules", False):
348
+ raise ConfigurationError("a profile prefix cannot be combined with --common")
349
+ if profile_name is not None and arguments.command not in PROFILE_AWARE_COMMANDS:
350
+ raise ConfigurationError(
351
+ f"profile prefix '{profile_name}' cannot be used with "
352
+ f"'{arguments.command}'"
353
+ )
354
+
355
+
356
+ def build_parser() -> argparse.ArgumentParser:
357
+ parser = argparse.ArgumentParser(
358
+ prog="hlsync",
359
+ description=(
360
+ "Transfer mapped files over explicit FTP over TLS. Run commands "
361
+ "inside a mapped profile; prefix a command with a profile only for "
362
+ "a one-command override. Commands may be shortened to any unique "
363
+ "prefix."
364
+ ),
365
+ )
366
+ parser.add_argument("-v", "--version", action="version", version=__version__)
367
+ parser.add_argument(
368
+ "--legend",
369
+ action="store_true",
370
+ help="show diff symbols and exit",
371
+ )
372
+ subparsers = parser.add_subparsers(dest="command")
373
+
374
+ create_parser = subparsers.add_parser(
375
+ "create",
376
+ help="create an FTPS profile with a mapped local root",
377
+ description=(
378
+ "Create an FTPS profile using environment-variable credentials. "
379
+ "Without --local-root, choose the current or another directory."
380
+ ),
381
+ )
382
+ create_parser.add_argument("profile_name", help="new profile name")
383
+ create_parser.add_argument("--host", required=True, help="FTPS server host")
384
+ create_parser.add_argument(
385
+ "--remote-root", required=True, help="absolute server directory"
386
+ )
387
+ create_parser.add_argument(
388
+ "--protocol",
389
+ choices=("ftps",),
390
+ default="ftps",
391
+ help="transfer protocol (default: ftps)",
392
+ )
393
+ create_parser.add_argument(
394
+ "--port", type=int, default=21, help="server port (default: 21)"
395
+ )
396
+ create_parser.add_argument(
397
+ "--username-env",
398
+ help=f"username environment variable (default: {DEFAULT_USERNAME_ENV})",
399
+ )
400
+ create_parser.add_argument(
401
+ "--password-env",
402
+ help=f"password environment variable (default: {DEFAULT_PASSWORD_ENV})",
403
+ )
404
+ create_parser.add_argument(
405
+ "--local-root",
406
+ metavar="PATH",
407
+ help=(
408
+ "local profile directory; when omitted, offer the current "
409
+ "directory and prompt for another if declined"
410
+ ),
411
+ )
412
+
413
+ connect_parser = subparsers.add_parser(
414
+ "connect",
415
+ help="verify a profile's FTPS connection",
416
+ usage="hlsync connect [PROFILE]\n hlsync PROFILE connect",
417
+ description=(
418
+ "Check secure FTPS connectivity, then disconnect. Infer the profile "
419
+ "from the current directory unless named."
420
+ ),
421
+ )
422
+ connect_parser.add_argument(
423
+ "profile_name", nargs="?", help="profile; inferred when omitted"
424
+ )
425
+
426
+ map_parser = subparsers.add_parser(
427
+ "map",
428
+ help="change a profile's local or remote root",
429
+ usage=(
430
+ "hlsync map [PROFILE] [--local-root PATH] [--remote-root PATH]\n"
431
+ " hlsync PROFILE map [--local-root PATH] [--remote-root PATH]"
432
+ ),
433
+ description=(
434
+ "Change mapped roots after a [y/N] confirmation. Omitted roots stay "
435
+ "unchanged; with neither option, use the current local directory."
436
+ ),
437
+ )
438
+ map_parser.add_argument(
439
+ "profile_name", nargs="?", help="profile; inferred when omitted"
440
+ )
441
+ map_parser.add_argument(
442
+ "--local-root",
443
+ metavar="PATH",
444
+ help="new local root; defaults to the current directory",
445
+ )
446
+ map_parser.add_argument(
447
+ "--remote-root",
448
+ metavar="PATH",
449
+ help="new absolute remote root; omitted leaves it unchanged",
450
+ )
451
+
452
+ rule_change_help = {
453
+ "exclude": "exclude paths from synchronization",
454
+ "include": "include paths, overriding broader exclusions",
455
+ }
456
+ for command in ("exclude", "include"):
457
+ rule_parser = subparsers.add_parser(
458
+ command,
459
+ help=rule_change_help[command],
460
+ usage=(
461
+ f"hlsync [PROFILE] {command} [--remote] "
462
+ "[--anywhere | --shallow] [--ext EXT] [-m] PATH\n"
463
+ f" hlsync {command} -c [--remote] "
464
+ "[--anywhere | --shallow] [--ext EXT] [-m] PATH"
465
+ ),
466
+ description=(
467
+ f"Record {command} rules for the current profile, or for every "
468
+ "profile with -c. List rules with 'hlsync rules'."
469
+ ),
470
+ )
471
+ add_pattern_operands(
472
+ rule_parser,
473
+ required=False,
474
+ metavar="PATH",
475
+ help_text=(
476
+ "a path, a quoted wildcard, or comma-separated paths; "
477
+ "wildcards also match in subfolders"
478
+ ),
479
+ )
480
+ rule_parser.add_argument(
481
+ "--remote",
482
+ action="store_true",
483
+ help="apply to protected remote paths",
484
+ )
485
+ rule_matching = rule_parser.add_mutually_exclusive_group()
486
+ rule_matching.add_argument(
487
+ "-s",
488
+ "--shallow",
489
+ action="store_true",
490
+ help="match wildcards in the named folder only, not its subfolders",
491
+ )
492
+ rule_matching.add_argument(
493
+ "--anywhere",
494
+ action="store_true",
495
+ help=(
496
+ "match names at any depth below the current directory; "
497
+ "-c: every profile"
498
+ ),
499
+ )
500
+ rule_parser.add_argument(
501
+ "-c",
502
+ "--common",
503
+ dest="common_rules",
504
+ action="store_true",
505
+ help="record a rule shared by every profile",
506
+ )
507
+ rule_parser.add_argument(
508
+ "--ext",
509
+ metavar="EXT",
510
+ help="match these comma-separated file extensions inside PATH",
511
+ )
512
+ rule_parser.add_argument(
513
+ "-m",
514
+ "--multiple",
515
+ action="store_true",
516
+ help="accept several space-separated paths",
517
+ )
518
+
519
+ rules_parser = subparsers.add_parser(
520
+ "rules",
521
+ help="list or remove synchronization rules",
522
+ usage=(
523
+ "hlsync [PROFILE] rules\n"
524
+ " hlsync [PROFILE] rules rm RULE_ID ...\n"
525
+ " hlsync rules -c [rm COMMON_RULE_ID ...]"
526
+ ),
527
+ description=(
528
+ "List rules, or remove them by their displayed IDs with rm. Use -c for "
529
+ "common rules. Add rules with 'hlsync exclude' and 'hlsync include'."
530
+ ),
531
+ )
532
+ rules_parser.add_argument(
533
+ "operation",
534
+ nargs="?",
535
+ choices=("rm",),
536
+ metavar="rm",
537
+ help="remove the rules with the displayed RULE_IDs",
538
+ )
539
+ rules_parser.add_argument("rule_ids", nargs="*", metavar="RULE_ID")
540
+ rules_parser.add_argument(
541
+ "-c",
542
+ "--common",
543
+ dest="common_rules",
544
+ action="store_true",
545
+ help="manage rules shared by every profile",
546
+ )
547
+ remove_parser = subparsers.add_parser(
548
+ "remove",
549
+ help="remove a profile",
550
+ usage="hlsync remove [PROFILE]\n hlsync PROFILE remove",
551
+ description=(
552
+ "Remove local profile configuration only; remote files stay "
553
+ "unchanged. Infer the profile when omitted."
554
+ ),
555
+ )
556
+ remove_parser.add_argument(
557
+ "profile_name", nargs="?", help="profile; inferred when omitted"
558
+ )
559
+
560
+ root_parser = subparsers.add_parser(
561
+ "root",
562
+ help="print a profile's mapped local root",
563
+ usage="hlsync root [PROFILE]\n hlsync PROFILE root",
564
+ description=(
565
+ "Print only the canonical local root, suitable for "
566
+ "cd \"$(hlsync root PROFILE)\"."
567
+ ),
568
+ )
569
+ root_parser.add_argument(
570
+ "profile_name",
571
+ nargs="?",
572
+ metavar="PROFILE",
573
+ help="profile name; inferred from the current directory when omitted",
574
+ )
575
+
576
+ profile_parser = subparsers.add_parser(
577
+ "profile",
578
+ help="show the current profile or detailed profile information",
579
+ usage=(
580
+ "hlsync profile [PROFILE] [--details]\n"
581
+ " hlsync PROFILE profile [--details]"
582
+ ),
583
+ description=(
584
+ "Print the inferred or named profile. --details adds its "
585
+ "connection, mapping, credentials, and rules."
586
+ ),
587
+ )
588
+ profile_parser.add_argument(
589
+ "profile_name",
590
+ nargs="?",
591
+ metavar="PROFILE",
592
+ help="profile name; inferred from the current directory when omitted",
593
+ )
594
+ profile_parser.add_argument(
595
+ "--details",
596
+ dest="profile_details",
597
+ action="store_true",
598
+ help="show endpoint, mapping, credentials, and rule count",
599
+ )
600
+
601
+ subparsers.add_parser(
602
+ "profiles",
603
+ help="list configured profiles",
604
+ description="List profiles; * marks the one containing this directory.",
605
+ )
606
+
607
+ list_parser = subparsers.add_parser(
608
+ "list",
609
+ aliases=("lsr",),
610
+ help="list the current local or remote directory",
611
+ usage=(
612
+ "hlsync [PROFILE] list [--remote] [-r] [-i] [PATH ...]\n"
613
+ " hlsync [PROFILE] lsr [-r] [-i] [PATH ...]"
614
+ ),
615
+ description=(
616
+ "With no PATH, list the current directory one level. A directory "
617
+ "PATH is also shallow unless -r. Use --remote/lsr for remote and "
618
+ "-i to hide exclusions."
619
+ ),
620
+ )
621
+ add_pattern_operands(
622
+ list_parser,
623
+ required=False,
624
+ metavar="PATH",
625
+ help_text=(
626
+ "relative paths or wildcards; default: current directory"
627
+ ),
628
+ )
629
+ list_parser.add_argument(
630
+ "--remote",
631
+ action="store_true",
632
+ help="list the mapped remote directory over FTPS",
633
+ )
634
+ list_parser.add_argument(
635
+ "-r",
636
+ "--recursive",
637
+ action="store_true",
638
+ help="include descendants of the selected directories",
639
+ )
640
+ _add_included_only_argument(list_parser)
641
+
642
+ diff_parser = subparsers.add_parser(
643
+ "diff",
644
+ help="preview file changes without modifying anything",
645
+ usage=(
646
+ "hlsync [PROFILE] diff [PATH ...]\n"
647
+ " [--pull | --prune] [-r | -s] [-a] [-x] [-I] [--paged]\n"
648
+ " [--resume DIRECTORY]"
649
+ ),
650
+ description=(
651
+ "With no PATH, preview the current subtree recursively. Directory "
652
+ "PATHs are also recursive; use -s for immediate contents only. "
653
+ "Use --pull to reverse direction, "
654
+ "-x to show exclusions, -I to treat them as included, and -a to "
655
+ "show everything."
656
+ ),
657
+ )
658
+ add_pattern_operands(
659
+ diff_parser,
660
+ required=False,
661
+ metavar="PATH",
662
+ help_text=(
663
+ "relative paths or wildcards; default: current directory"
664
+ ),
665
+ )
666
+ diff_direction = diff_parser.add_mutually_exclusive_group()
667
+ diff_direction.add_argument(
668
+ "--pull",
669
+ action="store_true",
670
+ help="show changes from the remote perspective without remote deletion",
671
+ )
672
+ _add_recursive_depth_arguments(diff_parser)
673
+ _add_include_excluded_argument(diff_parser)
674
+ diff_parser.add_argument(
675
+ "-x",
676
+ "--excluded",
677
+ dest="show_excluded",
678
+ action="store_true",
679
+ help="also show excluded paths",
680
+ )
681
+ diff_parser.add_argument(
682
+ "-a",
683
+ "--all",
684
+ dest="show_all",
685
+ action="store_true",
686
+ help="show every compared path, including unchanged and kept ones",
687
+ )
688
+ diff_parser.add_argument(
689
+ "--paged",
690
+ action="store_true",
691
+ help="show one directory, then exit with a resume command",
692
+ )
693
+ diff_parser.add_argument(
694
+ "--resume",
695
+ metavar="DIRECTORY",
696
+ help="resume a paged diff at a profile-relative directory",
697
+ )
698
+ diff_direction.add_argument(
699
+ "-p",
700
+ "--prune",
701
+ action="store_true",
702
+ help="show remote-only paths as deleted, as push --prune would",
703
+ )
704
+ transfer_help = {
705
+ "push": "upload local changes to the remote profile",
706
+ "pull": "replace changed local files from the remote profile",
707
+ }
708
+ transfer_description = {
709
+ "push": (
710
+ "Push local changes. With no PATH, push the current subtree "
711
+ "recursively. Directory PATHs are also recursive; use -s for "
712
+ "immediate contents only. Remote-only paths are kept unless "
713
+ "-p is given, and a remote file is replaced only when the local "
714
+ "copy is newer unless --force is given. Use --dry to "
715
+ "preview the exact push without changing either side."
716
+ ),
717
+ "pull": (
718
+ "Pull requires a PATH. A directory PATH is shallow unless -r; "
719
+ "missing local paths stay missing. A local file is replaced only "
720
+ "when the remote copy is newer unless --force is given."
721
+ ),
722
+ }
723
+ for command in ("push", "pull"):
724
+ transfer_parser = subparsers.add_parser(
725
+ command,
726
+ help=transfer_help[command],
727
+ description=transfer_description[command],
728
+ usage=(
729
+ (
730
+ "hlsync [PROFILE] pull PATH [PATH ...] [-r] [-I] [--force]"
731
+ if command == "pull"
732
+ else "hlsync [PROFILE] push [PATH ...] [-r | -s] [-I]"
733
+ )
734
+ + (" [-p] [--force] [--dry] [-j N]" if command == "push" else "")
735
+ ),
736
+ )
737
+ _add_include_excluded_argument(transfer_parser)
738
+ add_pattern_operands(
739
+ transfer_parser,
740
+ required=command == "pull",
741
+ metavar="PATH",
742
+ help_text=(
743
+ "relative paths or wildcards; default: current subtree"
744
+ if command == "push"
745
+ else "relative paths or wildcards"
746
+ ),
747
+ )
748
+ if command == "push":
749
+ _add_recursive_depth_arguments(transfer_parser)
750
+ transfer_parser.add_argument(
751
+ "-p",
752
+ "--prune",
753
+ action="store_true",
754
+ help="delete selected remote-only paths",
755
+ )
756
+ transfer_parser.add_argument(
757
+ "--dry",
758
+ action="store_true",
759
+ help="show the exact push without changing either side",
760
+ )
761
+ transfer_parser.add_argument(
762
+ "-j",
763
+ "--jobs",
764
+ type=_upload_job_count,
765
+ default=DEFAULT_UPLOAD_JOBS,
766
+ metavar="N",
767
+ help=(
768
+ "upload N files at once over separate connections "
769
+ f"(1-{MAX_UPLOAD_JOBS}, default {DEFAULT_UPLOAD_JOBS})"
770
+ ),
771
+ )
772
+ else:
773
+ transfer_parser.add_argument(
774
+ "-r", "--recursive", action="store_true",
775
+ help="recurse into selected directories",
776
+ )
777
+ transfer_parser.add_argument(
778
+ "--force",
779
+ action="store_true",
780
+ help="overwrite destination files that are not older than the source",
781
+ )
782
+
783
+ help_parser = subparsers.add_parser("help", help="show command help")
784
+ help_parser.add_argument("topic", nargs="?")
785
+
786
+ subparsers.add_parser("version", help="show the installed version")
787
+ return parser
788
+
789
+
790
+ def _confirm(
791
+ prompt: str,
792
+ stdin: TextIO,
793
+ stdout: TextIO,
794
+ *,
795
+ default: bool,
796
+ ) -> bool:
797
+ while True:
798
+ print(prompt, end="", file=stdout, flush=True)
799
+ answer = stdin.readline()
800
+ if answer == "":
801
+ raise ConfigurationError("confirmation requires yes or no")
802
+ normalized = answer.strip().lower()
803
+ if normalized in {"y", "yes"}:
804
+ return True
805
+ if normalized in {"n", "no"}:
806
+ return False
807
+ if normalized == "":
808
+ return default
809
+ print("Please answer yes or no.", file=stdout)
810
+
811
+
812
+ def _create_profile(
813
+ arguments: argparse.Namespace,
814
+ store: ConfigurationStore,
815
+ stdin: TextIO,
816
+ stdout: TextIO,
817
+ ) -> str:
818
+ name = validate_profile_name(arguments.profile_name)
819
+ configuration = store.load()
820
+ if name in configuration.profiles:
821
+ raise ConfigurationError(f"profile '{name}' already exists")
822
+ profile = ProfileConfiguration(
823
+ type=arguments.protocol,
824
+ host=arguments.host,
825
+ remote_root=arguments.remote_root,
826
+ port=arguments.port,
827
+ username_env=(
828
+ arguments.username_env
829
+ if arguments.username_env is not None
830
+ else DEFAULT_USERNAME_ENV
831
+ ),
832
+ password_env=(
833
+ arguments.password_env
834
+ if arguments.password_env is not None
835
+ else DEFAULT_PASSWORD_ENV
836
+ ),
837
+ )
838
+ configuration.profiles[name] = profile
839
+ if arguments.local_root is not None:
840
+ local_root = canonical_local_root(arguments.local_root)
841
+ else:
842
+ current_root = canonical_local_root(Path.cwd())
843
+ prompt = (
844
+ f"Map current directory '{current_root}' to "
845
+ f"'{name}:{profile.remote_root}'? [Y/n] "
846
+ )
847
+ if _confirm(prompt, stdin, stdout, default=True):
848
+ local_root = current_root
849
+ else:
850
+ print(
851
+ "What local folder should be mapped instead? ",
852
+ end="",
853
+ file=stdout,
854
+ flush=True,
855
+ )
856
+ supplied_root = stdin.readline()
857
+ if supplied_root == "" or not supplied_root.strip():
858
+ raise ConfigurationError("a local folder is required")
859
+ local_root = canonical_local_root(supplied_root.strip())
860
+ configuration.set_profile_roots(
861
+ name,
862
+ local_root=local_root,
863
+ remote_root=profile.remote_root,
864
+ )
865
+ message = (
866
+ f"Created FTPS profile '{name}'.\n"
867
+ f"Mapped '{local_root}' to '{name}:{profile.remote_root}'."
868
+ )
869
+ _common_rule_store(store).load()
870
+ store.save(configuration)
871
+ return message
872
+
873
+
874
+ def _common_rule_store(store: ConfigurationStore) -> CommonRuleStore:
875
+ return CommonRuleStore(store.path.with_name("rules.json"))
876
+
877
+
878
+ def _effective_rules(
879
+ store: ConfigurationStore,
880
+ profile: ProfileConfiguration,
881
+ ) -> RuleSet:
882
+ common_rules = _common_rule_store(store).load().rules
883
+ return RuleSet.layered(
884
+ common_rules,
885
+ profile.rules,
886
+ gitignores=GitIgnores(Path(profile.local_root)) if profile.local_root else None,
887
+ )
888
+
889
+
890
+ def _command_rules(
891
+ arguments: argparse.Namespace,
892
+ store: ConfigurationStore,
893
+ profile: ProfileConfiguration,
894
+ ) -> RuleSet:
895
+ rules = _effective_rules(store, profile)
896
+ if not arguments.include_excluded:
897
+ return rules
898
+ return replace(
899
+ rules,
900
+ rules=tuple(rule for rule in rules.rules if rule.target == "remote"),
901
+ gitignores=None,
902
+ )
903
+
904
+
905
+ def _resolve_profile(
906
+ arguments: argparse.Namespace, store: ConfigurationStore
907
+ ) -> tuple[ApplicationConfiguration, str, ProfileConfiguration]:
908
+ configuration = store.load()
909
+ prefix_name = getattr(arguments, "profile_prefix", None)
910
+ positional_name = getattr(arguments, "profile_name", None)
911
+ if prefix_name is not None and positional_name is not None:
912
+ raise ConfigurationError(
913
+ "profile was specified both before the command and as an argument"
914
+ )
915
+ supplied_name = prefix_name or positional_name
916
+ if supplied_name is None:
917
+ active = configuration.profile_for_path(Path.cwd().resolve(strict=True))
918
+ if active is None:
919
+ raise ConfigurationError(
920
+ "current directory is not inside a mapped profile; prefix the "
921
+ "command with a profile (hlsync PROFILE COMMAND)"
922
+ )
923
+ name, profile = active
924
+ return configuration, name, profile
925
+ name = validate_profile_name(supplied_name)
926
+ if name not in configuration.profiles:
927
+ raise ConfigurationError(f"profile '{name}' does not exist")
928
+ return configuration, name, configuration.profiles[name]
929
+
930
+
931
+ def _effective_current_directory(
932
+ arguments: argparse.Namespace,
933
+ profile_root: Path,
934
+ ) -> Path:
935
+ if getattr(arguments, "profile_prefix", None) is not None:
936
+ return profile_root.resolve(strict=True)
937
+ return Path.cwd().resolve(strict=True)
938
+
939
+
940
+ def _connect(arguments: argparse.Namespace, store: ConfigurationStore) -> str:
941
+ _, name, profile = _resolve_profile(arguments, store)
942
+ with ExplicitFTPSTransport(profile):
943
+ pass
944
+ return f"Verified secure connectivity to profile '{name}'."
945
+
946
+
947
+ def _map(
948
+ arguments: argparse.Namespace,
949
+ store: ConfigurationStore,
950
+ stdin: TextIO,
951
+ stdout: TextIO,
952
+ ) -> str:
953
+ configuration, name, profile = _resolve_profile(arguments, store)
954
+ if arguments.local_root is not None:
955
+ local_root = canonical_local_root(arguments.local_root)
956
+ elif arguments.remote_root is None or profile.local_root is None:
957
+ local_root = canonical_local_root(Path.cwd())
958
+ else:
959
+ local_root = profile.local_root
960
+ remote_root = (
961
+ arguments.remote_root
962
+ if arguments.remote_root is not None
963
+ else profile.remote_root
964
+ )
965
+ candidate = profile.with_roots(
966
+ local_root=local_root,
967
+ remote_root=remote_root,
968
+ )
969
+ changes = []
970
+ if profile.local_root != candidate.local_root:
971
+ changes.append(
972
+ f" Local root: {profile.local_root or 'not mapped'} "
973
+ f"→ {candidate.local_root}"
974
+ )
975
+ if profile.remote_root != candidate.remote_root:
976
+ changes.append(
977
+ f" Remote root: {profile.remote_root} → {candidate.remote_root}"
978
+ )
979
+ if not changes:
980
+ return f"Profile '{name}' mapping is unchanged."
981
+
982
+ configuration.set_profile_roots(
983
+ name,
984
+ local_root=candidate.local_root,
985
+ remote_root=candidate.remote_root,
986
+ )
987
+ prompt = "\n".join(
988
+ (f"Change mapping for profile '{name}'?", *changes, "Continue? [y/N] ")
989
+ )
990
+ if not _confirm(prompt, stdin, stdout, default=False):
991
+ return f"Kept profile '{name}' mapping unchanged."
992
+ store.save(configuration)
993
+ return "\n".join((f"Updated profile '{name}' mapping:", *changes))
994
+
995
+
996
+ def _format_rules(
997
+ name: str,
998
+ rules: tuple[SyncRule, ...],
999
+ *,
1000
+ heading: str,
1001
+ common_scope: bool = False,
1002
+ ) -> str:
1003
+ scope_heading = (
1004
+ f"Common {heading.lower()}"
1005
+ if common_scope
1006
+ else f"{heading} for profile '{name}'"
1007
+ )
1008
+ if not rules:
1009
+ return f"No {scope_heading.lower()}."
1010
+ identifiers = {
1011
+ rule.id: _format_rule_id(rule, common_scope=common_scope) for rule in rules
1012
+ }
1013
+ width = max(len(identifier) for identifier in identifiers.values())
1014
+ return "\n".join(
1015
+ (
1016
+ f"{scope_heading}:",
1017
+ *(
1018
+ f" {identifiers[rule.id]:>{width}} {rule.action:<7} "
1019
+ f"{_format_rule_expression(rule)}"
1020
+ for rule in rules
1021
+ ),
1022
+ )
1023
+ )
1024
+
1025
+
1026
+ COMMON_RULES_HEADING = "Common rules (all profiles):"
1027
+
1028
+
1029
+ def _format_rule_sections(
1030
+ sections: tuple[tuple[str, tuple[SyncRule, ...], bool], ...],
1031
+ ) -> str:
1032
+ width = max(
1033
+ (
1034
+ len(_format_rule_id(rule, common_scope=common_scope))
1035
+ for _, rules, common_scope in sections
1036
+ for rule in rules
1037
+ ),
1038
+ default=0,
1039
+ )
1040
+ return "\n\n".join(
1041
+ _format_rule_section(heading, rules, common_scope=common_scope, width=width)
1042
+ for heading, rules, common_scope in sections
1043
+ )
1044
+
1045
+
1046
+ def _format_rule_section(
1047
+ heading: str,
1048
+ rules: tuple[SyncRule, ...],
1049
+ *,
1050
+ common_scope: bool,
1051
+ width: int,
1052
+ ) -> str:
1053
+ if not rules:
1054
+ return f"{heading}\n (none)"
1055
+ populated_targets = tuple(
1056
+ (label, tuple(rule for rule in rules if rule.target == target))
1057
+ for label, target in (("Local paths", "local"), ("Remote paths", "remote"))
1058
+ if any(rule.target == target for rule in rules)
1059
+ )
1060
+ show_target_headings = len(populated_targets) > 1 or (
1061
+ populated_targets[0][0] == "Remote paths"
1062
+ )
1063
+ lines = [heading]
1064
+ for target_heading, target_rules in populated_targets:
1065
+ group_indent = " "
1066
+ if show_target_headings:
1067
+ lines.append(f" {target_heading}:")
1068
+ group_indent = " "
1069
+ groups: dict[str, list[tuple[SyncRule, str]]] = {}
1070
+ for rule in target_rules:
1071
+ group, expression = _rule_display_location(rule)
1072
+ groups.setdefault(group, []).append((rule, expression))
1073
+ for group in sorted(groups, key=_rule_group_key):
1074
+ lines.append(f"{group_indent}{group}")
1075
+ for rule, expression in sorted(
1076
+ groups[group],
1077
+ key=lambda item: (item[1].casefold(), item[1], item[0].id),
1078
+ ):
1079
+ identifier = _format_rule_id(rule, common_scope=common_scope)
1080
+ lines.append(
1081
+ f"{group_indent} {identifier:>{width}} "
1082
+ f"{rule.action:<7} {expression}"
1083
+ )
1084
+ return "\n".join(lines)
1085
+
1086
+
1087
+ def _rule_display_location(rule: SyncRule) -> tuple[str, str]:
1088
+ parts = PurePosixPath(rule.pattern).parts
1089
+ wildcard_index = next(
1090
+ (index for index, part in enumerate(parts) if "*" in part),
1091
+ None,
1092
+ )
1093
+ if wildcard_index is None:
1094
+ return _rule_group_label(parts[:-1]), parts[-1]
1095
+ if parts[0] == "**":
1096
+ return "Everywhere", _describe_wildcards(parts, everywhere=True)
1097
+ return _rule_group_label(parts[:wildcard_index]), _describe_wildcards(
1098
+ parts[wildcard_index:], everywhere=False
1099
+ )
1100
+
1101
+
1102
+ def _describe_wildcards(parts: tuple[str, ...], *, everywhere: bool) -> str:
1103
+ if parts == ("**",):
1104
+ return "all contents"
1105
+ deep = parts[0] == "**"
1106
+ body = parts[1:] if deep else parts
1107
+ tree = len(body) > 1 and body[-1] == "**"
1108
+ if tree:
1109
+ body = body[:-1]
1110
+ text = "/".join(body) + ("/" if tree else "")
1111
+ if everywhere or "**" in body:
1112
+ return text
1113
+ return f"{text} (all subfolders)" if deep else f"{text} (this folder only)"
1114
+
1115
+
1116
+ def _rule_group_label(parts: tuple[str, ...]) -> str:
1117
+ return "./" if not parts else f"{PurePosixPath(*parts).as_posix()}/"
1118
+
1119
+
1120
+ def _rule_group_key(group: str) -> tuple[int, str, str]:
1121
+ if group == "./":
1122
+ return (0, "", "")
1123
+ if group == "Everywhere":
1124
+ return (2, "", "")
1125
+ return (1, group.casefold(), group)
1126
+
1127
+
1128
+ def _rules_need_precedence_note(rules: tuple[SyncRule, ...]) -> bool:
1129
+ return any(
1130
+ len({rule.action for rule in rules if rule.target == target}) > 1
1131
+ for target in ("local", "remote")
1132
+ )
1133
+
1134
+
1135
+ def _format_rule_expression(rule: SyncRule) -> str:
1136
+ if "*" not in rule.pattern:
1137
+ return f"./{rule.pattern}"
1138
+ group, expression = _rule_display_location(rule)
1139
+ if group == "Everywhere":
1140
+ return f"{expression} (everywhere)"
1141
+ if expression == "all contents":
1142
+ return f"{group} (all contents)"
1143
+ return f"{group}{expression}"
1144
+
1145
+
1146
+ def _format_rule_id(rule: SyncRule, *, common_scope: bool) -> str:
1147
+ return f"c{rule.id}" if common_scope else str(rule.id)
1148
+
1149
+
1150
+ def _parse_rule_id(value: str, *, common_scope: bool) -> int:
1151
+ identifier = value[1:] if common_scope and value.startswith("c") else value
1152
+ valid_prefix = not common_scope or value.startswith("c")
1153
+ if not valid_prefix or not identifier.isdigit() or int(identifier) < 1:
1154
+ expected = "c-prefixed (for example c3)" if common_scope else "numeric"
1155
+ raise ConfigurationError(f"rule id must be {expected} in this scope")
1156
+ return int(identifier)
1157
+
1158
+
1159
+ def _change_rules(
1160
+ arguments: argparse.Namespace,
1161
+ store: ConfigurationStore,
1162
+ *,
1163
+ include: bool,
1164
+ ) -> str:
1165
+ if len(arguments.pattern_operands) > 1 and not arguments.multiple:
1166
+ raise ConfigurationError("got multiple paths; quote wildcards or add -m")
1167
+ patterns = normalize_pattern_operands(arguments)
1168
+ if arguments.ext is not None:
1169
+ patterns = _extension_patterns(patterns or (".",), arguments.ext)
1170
+ target = "remote" if arguments.remote else "local"
1171
+ if not patterns:
1172
+ raise ConfigurationError(f"{arguments.command} requires at least one path")
1173
+ if not arguments.anywhere and not arguments.shallow:
1174
+ patterns = tuple(_reach_subfolders(pattern) for pattern in patterns)
1175
+ if arguments.anywhere:
1176
+ for pattern in patterns:
1177
+ path = PurePosixPath(pattern)
1178
+ if path.is_absolute() or ".." in path.parts or not path.parts:
1179
+ raise ConfigurationError(
1180
+ "--anywhere requires relative names or patterns"
1181
+ )
1182
+ patterns = tuple(f"**/{pattern}" for pattern in patterns)
1183
+ if arguments.common_rules:
1184
+ common_store = _common_rule_store(store)
1185
+ configuration = common_store.load()
1186
+ normalized = patterns_from_common_operands(
1187
+ patterns,
1188
+ trailing_slash_tree=not arguments.remote,
1189
+ )
1190
+ configuration, update = configuration.with_appended_rules(
1191
+ "include" if include else "exclude",
1192
+ normalized,
1193
+ target=target,
1194
+ )
1195
+ common_store.save(configuration)
1196
+ return _format_rule_update(
1197
+ "",
1198
+ update,
1199
+ include=include,
1200
+ common_scope=True,
1201
+ target=target,
1202
+ )
1203
+ configuration, name, profile = _resolve_profile(arguments, store)
1204
+ root = _require_local_root(name, profile)
1205
+ current_directory = _effective_current_directory(arguments, root)
1206
+ normalizer = (
1207
+ patterns_from_remote_operands
1208
+ if arguments.remote
1209
+ else patterns_from_operands
1210
+ )
1211
+ normalized = normalizer(
1212
+ patterns, profile_root=root, current_directory=current_directory
1213
+ )
1214
+ update = configuration.append_rules(
1215
+ name,
1216
+ "include" if include else "exclude",
1217
+ normalized,
1218
+ target=target,
1219
+ base_rules=_common_rule_store(store).load().rules,
1220
+ )
1221
+ store.save(configuration)
1222
+ return _format_rule_update(name, update, include=include, target=target)
1223
+
1224
+
1225
+ def _extension_patterns(
1226
+ folders: tuple[str, ...], extensions: str
1227
+ ) -> tuple[str, ...]:
1228
+ names = tuple(extension.strip().lstrip(".") for extension in extensions.split(","))
1229
+ if any(not name or "/" in name or "*" in name for name in names):
1230
+ raise ConfigurationError("--ext takes extensions such as jpg,png,webp")
1231
+ if any("*" in folder for folder in folders):
1232
+ raise ConfigurationError("--ext takes a folder, not a wildcard")
1233
+ return tuple(
1234
+ f"{folder.rstrip('/') or '.'}/*.{name}" for folder in folders for name in names
1235
+ )
1236
+
1237
+
1238
+ def _reach_subfolders(pattern: str) -> str:
1239
+ path = PurePosixPath(pattern)
1240
+ if "*" not in pattern or "**" in path.parts or not path.parts:
1241
+ return pattern
1242
+ tree = "/" if pattern.endswith("/") else ""
1243
+ return PurePosixPath(*path.parts[:-1], "**", path.parts[-1]).as_posix() + tree
1244
+
1245
+
1246
+ def _format_rule_update(
1247
+ name: str,
1248
+ update: RuleUpdate,
1249
+ *,
1250
+ include: bool,
1251
+ common_scope: bool = False,
1252
+ target: str = "local",
1253
+ ) -> str:
1254
+ scope = "common synchronization policy" if common_scope else f"profile '{name}'"
1255
+ if update.added and update.removed:
1256
+ lines = [f"Updated synchronization rules for {scope}:"]
1257
+ lines.extend(
1258
+ f" added {_format_rule_id(rule, common_scope=common_scope)} "
1259
+ f"{rule.action:<7} {_format_rule_expression(rule)}"
1260
+ for rule in update.added
1261
+ )
1262
+ lines.extend(
1263
+ f" removed {_format_rule_id(rule, common_scope=common_scope)} "
1264
+ f"{rule.action:<7} {_format_rule_expression(rule)}"
1265
+ for rule in update.removed
1266
+ )
1267
+ return "\n".join(lines)
1268
+ if update.added:
1269
+ action = "Inclusion" if include else "Exclusion"
1270
+ if target == "remote":
1271
+ action = f"Remote {action.lower()}"
1272
+ if common_scope:
1273
+ identifiers = tuple(
1274
+ _format_rule_id(rule, common_scope=True) for rule in update.added
1275
+ )
1276
+ width = max(len(identifier) for identifier in identifiers)
1277
+ return "\n".join(
1278
+ (
1279
+ f"Recorded common {action.lower()} rules:",
1280
+ *(
1281
+ f" {identifier:>{width}} {rule.action:<7} "
1282
+ f"{_format_rule_expression(rule)}"
1283
+ for rule, identifier in zip(
1284
+ update.added, identifiers, strict=True
1285
+ )
1286
+ ),
1287
+ )
1288
+ )
1289
+ return _format_rules(
1290
+ name,
1291
+ update.added,
1292
+ heading=f"Recorded {action.lower()} rules",
1293
+ )
1294
+ if update.removed:
1295
+ result = "included" if include else "excluded"
1296
+ if target == "remote":
1297
+ result = f"remotely {result}"
1298
+ remaining_scope = (
1299
+ "common synchronization policy"
1300
+ if common_scope
1301
+ else f"policy for profile '{name}'"
1302
+ )
1303
+ lines = [
1304
+ f"Paths are {result} by the remaining {remaining_scope};",
1305
+ "removed the unnecessary rules:",
1306
+ ]
1307
+ identifiers = tuple(
1308
+ _format_rule_id(rule, common_scope=common_scope)
1309
+ for rule in update.removed
1310
+ )
1311
+ width = max(len(identifier) for identifier in identifiers)
1312
+ lines.extend(
1313
+ f" {identifier:>{width}} {rule.action:<7} "
1314
+ f"{_format_rule_expression(rule)}"
1315
+ for rule, identifier in zip(update.removed, identifiers, strict=True)
1316
+ )
1317
+ return "\n".join(lines)
1318
+ return f"Synchronization rules for {scope} are unchanged."
1319
+
1320
+
1321
+ def _manage_rules(
1322
+ arguments: argparse.Namespace,
1323
+ store: ConfigurationStore,
1324
+ ) -> str:
1325
+ identifiers = tuple(
1326
+ dict.fromkeys(
1327
+ value.strip()
1328
+ for operand in arguments.rule_ids
1329
+ for value in operand.split(",")
1330
+ )
1331
+ )
1332
+ if arguments.operation == "rm" and not identifiers:
1333
+ raise ConfigurationError("rules rm requires a RULE_ID")
1334
+ if "" in identifiers:
1335
+ raise ConfigurationError("rule ids cannot be empty")
1336
+ if not identifiers:
1337
+ return _list_rules(arguments, store)
1338
+ common_ids = tuple(
1339
+ _parse_rule_id(value, common_scope=True)
1340
+ for value in identifiers
1341
+ if arguments.common_rules or value.startswith("c")
1342
+ )
1343
+ profile_ids = tuple(
1344
+ _parse_rule_id(value, common_scope=False)
1345
+ for value in identifiers
1346
+ if not (arguments.common_rules or value.startswith("c"))
1347
+ )
1348
+ reports = []
1349
+ common_store = _common_rule_store(store)
1350
+ common_configuration = common_store.load()
1351
+ if common_ids:
1352
+ common_configuration, removed = common_configuration.without_rules(common_ids)
1353
+ reports.append(
1354
+ _format_rules("", removed, heading="Rules removed", common_scope=True)
1355
+ )
1356
+ if profile_ids:
1357
+ configuration, name, _ = _resolve_profile(arguments, store)
1358
+ removed = configuration.remove_rules(name, profile_ids)
1359
+ reports.append(_format_rules(name, removed, heading="Rules removed"))
1360
+ store.save(configuration)
1361
+ if common_ids:
1362
+ common_store.save(common_configuration)
1363
+ return "\n".join(reports)
1364
+
1365
+
1366
+ def _list_rules(arguments: argparse.Namespace, store: ConfigurationStore) -> str:
1367
+ common_rules = _common_rule_store(store).load().rules
1368
+ if arguments.common_rules:
1369
+ formatted = _format_rule_sections(((COMMON_RULES_HEADING, common_rules, True),))
1370
+ if _rules_need_precedence_note(common_rules):
1371
+ return f"{formatted}\nLater rules win."
1372
+ return formatted
1373
+ _, name, profile = _resolve_profile(arguments, store)
1374
+ overview = _format_rule_sections(
1375
+ (
1376
+ (COMMON_RULES_HEADING, common_rules, True),
1377
+ (f"Profile rules ('{name}' only):", profile.rules, False),
1378
+ )
1379
+ )
1380
+ return (
1381
+ f"{overview}\n\n"
1382
+ "Profile rules override common rules; later matching rules win."
1383
+ )
1384
+
1385
+
1386
+ def _remove(arguments: argparse.Namespace, store: ConfigurationStore) -> str:
1387
+ configuration, name, _ = _resolve_profile(arguments, store)
1388
+ del configuration.profiles[name]
1389
+ store.save(configuration)
1390
+ return f"Removed profile '{name}'."
1391
+
1392
+
1393
+ def _list_profiles(store: ConfigurationStore) -> str:
1394
+ configuration = store.load()
1395
+ if not configuration.profiles:
1396
+ return "No profiles configured."
1397
+
1398
+ active = configuration.profile_for_path(Path.cwd().resolve(strict=True))
1399
+ active_name = active[0] if active is not None else None
1400
+ return "\n".join(
1401
+ f"{'*' if name == active_name else ' '} {name}"
1402
+ for name in sorted(configuration.profiles)
1403
+ )
1404
+
1405
+
1406
+ def _show_profile(
1407
+ arguments: argparse.Namespace,
1408
+ store: ConfigurationStore,
1409
+ ) -> str:
1410
+ implicit = (
1411
+ getattr(arguments, "profile_prefix", None) is None
1412
+ and arguments.profile_name is None
1413
+ )
1414
+ if implicit:
1415
+ configuration = store.load()
1416
+ active = configuration.profile_for_path(Path.cwd().resolve(strict=True))
1417
+ if active is None:
1418
+ return "No active profile. Use hlsync PROFILE COMMAND."
1419
+ name, profile = active
1420
+ else:
1421
+ _, name, profile = _resolve_profile(arguments, store)
1422
+ if not arguments.profile_details:
1423
+ return name
1424
+ return "\n".join(
1425
+ (
1426
+ f"Profile '{name}':",
1427
+ f" Protocol: {profile.type.upper()}",
1428
+ f" Host: {profile.host}:{profile.port}",
1429
+ f" Remote root: {profile.remote_root}",
1430
+ f" Local root: {profile.local_root or 'not mapped'}",
1431
+ f" Username env: {profile.username_env}",
1432
+ f" Password env: {profile.password_env}",
1433
+ f" Rules: {len(profile.rules)}",
1434
+ )
1435
+ )
1436
+
1437
+
1438
+ def _show_root(
1439
+ arguments: argparse.Namespace,
1440
+ store: ConfigurationStore,
1441
+ ) -> str:
1442
+ _, name, profile = _resolve_profile(arguments, store)
1443
+ return os.fspath(_require_local_root(name, profile))
1444
+
1445
+
1446
+ def _require_local_root(name: str, profile: ProfileConfiguration) -> Path:
1447
+ if profile.local_root is None:
1448
+ raise ConfigurationError(f"profile '{name}' has not been mapped")
1449
+ return Path(profile.local_root)
1450
+
1451
+
1452
+ def _format_tree_listing(
1453
+ arguments: argparse.Namespace,
1454
+ snapshot: TreeSnapshot,
1455
+ *,
1456
+ heading: str,
1457
+ empty_message: str,
1458
+ display_base: PurePosixPath,
1459
+ output: TextIO,
1460
+ status_for: Callable[
1461
+ [TreeEntry], tuple[str, str | None, bool, str | None]
1462
+ ],
1463
+ ) -> str:
1464
+ if not snapshot.entries:
1465
+ return empty_message
1466
+ lines = [heading]
1467
+ options = _active_options(arguments)
1468
+ if options is not None:
1469
+ lines.append(options)
1470
+ color = _use_color(output)
1471
+ emitted_directories: set[str] = set()
1472
+ for entry in _file_browser_order(
1473
+ snapshot.entries,
1474
+ path_of=lambda item: item.path,
1475
+ directory_of=lambda item: item.kind == "directory",
1476
+ ):
1477
+ profile_path = PurePosixPath(entry.path)
1478
+ try:
1479
+ relative = profile_path.relative_to(display_base)
1480
+ except ValueError as error:
1481
+ raise SelectionError(
1482
+ f"selected path '{entry.path}' is outside the display scope"
1483
+ ) from error
1484
+ for index, part in enumerate(relative.parts[:-1]):
1485
+ ancestor = display_base / PurePosixPath(*relative.parts[: index + 1])
1486
+ ancestor_path = ancestor.as_posix()
1487
+ if ancestor_path in emitted_directories:
1488
+ continue
1489
+ lines.append(
1490
+ _format_path_line(
1491
+ " ",
1492
+ directory=True,
1493
+ path=part,
1494
+ depth=index,
1495
+ color=color,
1496
+ marker_color=None,
1497
+ excluded=False,
1498
+ )
1499
+ )
1500
+ emitted_directories.add(ancestor_path)
1501
+ marker, marker_color, excluded, path_color = status_for(entry)
1502
+ lines.append(
1503
+ _format_path_line(
1504
+ marker,
1505
+ directory=entry.kind == "directory",
1506
+ path=relative.name,
1507
+ depth=max(len(relative.parts) - 1, 0),
1508
+ color=color,
1509
+ marker_color=marker_color,
1510
+ excluded=excluded,
1511
+ path_color=path_color,
1512
+ )
1513
+ )
1514
+ if entry.kind == "directory":
1515
+ emitted_directories.add(entry.path)
1516
+ return "\n".join(lines)
1517
+
1518
+
1519
+ def _list_local(
1520
+ arguments: argparse.Namespace,
1521
+ store: ConfigurationStore,
1522
+ output: TextIO,
1523
+ ) -> str:
1524
+ _, name, profile = _resolve_profile(arguments, store)
1525
+ root = _require_local_root(name, profile)
1526
+ selector = _list_selection(arguments, root)
1527
+ raw_snapshot = snapshot_local(
1528
+ root,
1529
+ _effective_rules(store, profile),
1530
+ selector,
1531
+ include_excluded=True,
1532
+ traverse_excluded=True,
1533
+ )
1534
+ if not raw_snapshot.entries:
1535
+ raise SelectionError(f"file selector '{selector.pattern}' matched no paths")
1536
+ snapshot = TreeSnapshot(
1537
+ tuple(
1538
+ entry
1539
+ for entry in raw_snapshot.entries
1540
+ if selector.includes_result(
1541
+ entry.path,
1542
+ directory=entry.kind == "directory",
1543
+ )
1544
+ and (not arguments.included_only or not entry.excluded)
1545
+ )
1546
+ )
1547
+ display_base = _profile_relative_current_directory(arguments, root)
1548
+ return _format_tree_listing(
1549
+ arguments,
1550
+ snapshot,
1551
+ heading=f"Local tree for profile '{name}':",
1552
+ empty_message=f"Local tree for profile '{name}' is empty.",
1553
+ display_base=display_base,
1554
+ output=output,
1555
+ status_for=lambda entry: (
1556
+ "x" if entry.excluded else " ",
1557
+ "\033[90m" if entry.excluded else None,
1558
+ entry.excluded,
1559
+ None,
1560
+ ),
1561
+ )
1562
+
1563
+
1564
+ def _list_remote(
1565
+ arguments: argparse.Namespace,
1566
+ store: ConfigurationStore,
1567
+ progress: TextIO,
1568
+ output: TextIO,
1569
+ ) -> str:
1570
+ _, name, profile = _resolve_profile(arguments, store)
1571
+ root = _require_local_root(name, profile)
1572
+ selector = _list_selection(arguments, root)
1573
+ rules = _effective_rules(store, profile)
1574
+ print(f"Listing remote files for profile '{name}'...", file=progress, flush=True)
1575
+ print("Connecting securely over FTPS...", file=progress, flush=True)
1576
+ with ExplicitFTPSTransport(profile) as transport:
1577
+ raw_snapshot = transport.snapshot(
1578
+ rules,
1579
+ selector,
1580
+ include_excluded=True,
1581
+ traverse_excluded=True,
1582
+ )
1583
+ if not raw_snapshot.entries:
1584
+ raise SelectionError(f"file selector '{selector.pattern}' matched no paths")
1585
+ snapshot = TreeSnapshot(
1586
+ tuple(
1587
+ entry
1588
+ for entry in raw_snapshot.entries
1589
+ if selector.includes_result(
1590
+ entry.path,
1591
+ directory=entry.kind == "directory",
1592
+ )
1593
+ and (
1594
+ not arguments.included_only
1595
+ or (not entry.excluded and not entry.remote_excluded)
1596
+ )
1597
+ )
1598
+ )
1599
+ display_base = _profile_relative_current_directory(arguments, root)
1600
+
1601
+ def remote_status(
1602
+ entry: TreeEntry,
1603
+ ) -> tuple[str, str | None, bool, str | None]:
1604
+ if entry.remote_excluded or entry.excluded:
1605
+ marker = "#" if entry.remote_excluded else "x"
1606
+ return marker, _DIFF_MARKER_COLORS[marker], True, None
1607
+ return " ", None, False, None
1608
+
1609
+ return _format_tree_listing(
1610
+ arguments,
1611
+ snapshot,
1612
+ heading=f"Remote tree for profile '{name}':",
1613
+ empty_message=f"Remote tree for profile '{name}' is empty.",
1614
+ display_base=display_base,
1615
+ output=output,
1616
+ status_for=remote_status,
1617
+ )
1618
+
1619
+
1620
+ def _comparison_kind(entry: ComparisonEntry) -> str:
1621
+ if (
1622
+ entry.local_kind is not None
1623
+ and entry.remote_kind is not None
1624
+ and entry.local_kind != entry.remote_kind
1625
+ ):
1626
+ return f"{entry.local_kind}->{entry.remote_kind}"
1627
+ return entry.local_kind or entry.remote_kind or "unknown"
1628
+
1629
+
1630
+ def _comparison_marker(entry: ComparisonEntry) -> str:
1631
+ side = (
1632
+ "r" if entry.local_kind is None
1633
+ else "l" if entry.remote_kind is None
1634
+ else " "
1635
+ )
1636
+ exclusion = (
1637
+ "#" if entry.state == "remote-excluded"
1638
+ else "x" if entry.state == "excluded"
1639
+ else " "
1640
+ )
1641
+ action = {
1642
+ "excluded": " ",
1643
+ "conflict": "?",
1644
+ "unchanged": "=",
1645
+ "untraversed": " ",
1646
+ "skip": " ",
1647
+ "create-remote": "+",
1648
+ "upload": "+",
1649
+ "replace-remote": "~",
1650
+ "replace-local": "~",
1651
+ "delete-remote": "-",
1652
+ }[entry.action]
1653
+ return f"{action}{exclusion} {side}"
1654
+
1655
+
1656
+ def _comparison_marker_color(marker: str) -> str | None:
1657
+ action, exclusion, side = marker[0], marker[1], marker[3]
1658
+ return (
1659
+ _DIFF_MARKER_COLORS.get(action)
1660
+ or _DIFF_MARKER_COLORS.get(exclusion)
1661
+ or _DIFF_MARKER_COLORS.get(side)
1662
+ )
1663
+
1664
+
1665
+ def _comparison_entry_kind(entry: ComparisonEntry, direction: str) -> str:
1666
+ selected = entry.local_kind if direction == "push" else entry.remote_kind
1667
+ return selected or entry.remote_kind or entry.local_kind or "unknown"
1668
+
1669
+
1670
+ def _use_color(output: TextIO) -> bool:
1671
+ if "NO_COLOR" in os.environ:
1672
+ return False
1673
+ is_terminal = getattr(output, "isatty", None)
1674
+ return bool(is_terminal and is_terminal())
1675
+
1676
+
1677
+ def _format_legend(output: TextIO) -> str:
1678
+ color = _use_color(output)
1679
+ entries = (
1680
+ ("+ l", "local-only; upload", _DIFF_MARKER_COLORS["+"]),
1681
+ ("~ ", "present on both sides; update", _DIFF_MARKER_COLORS["~"]),
1682
+ (" r", "remote-only; retain", _DIFF_MARKER_COLORS["r"]),
1683
+ ("- r", "remote-only; delete with --prune", _DIFF_MARKER_COLORS["-"]),
1684
+ ("-x ", "locally excluded; delete with --prune", _DIFF_MARKER_COLORS["-"]),
1685
+ ("l", "local only", _DIFF_MARKER_COLORS["l"]),
1686
+ ("r", "remote only", _DIFF_MARKER_COLORS["r"]),
1687
+ (" ", "blank side column: present on both sides", None),
1688
+ (
1689
+ "?",
1690
+ "conflict; destination not older, or type mismatch",
1691
+ _DIFF_MARKER_COLORS["?"],
1692
+ ),
1693
+ ("=", "unchanged file", None),
1694
+ ("x", "locally excluded", _DIFF_MARKER_COLORS["x"]),
1695
+ ("#", "remotely excluded; leave untouched", _DIFF_MARKER_COLORS["#"]),
1696
+ ("/", "directory", _DIRECTORY_COLOR),
1697
+ ("▸", "contents not inspected", _COLLAPSED_DIRECTORY_COLOR),
1698
+ )
1699
+ lines = ["Diff legend:"]
1700
+ for marker, meaning, style in entries:
1701
+ rendered = f"{style}{marker}{_RESET}" if color and style else marker
1702
+ lines.append(f" {rendered} {meaning}")
1703
+ return "\n".join(lines)
1704
+
1705
+
1706
+ def _format_path_line(
1707
+ marker: str,
1708
+ *,
1709
+ directory: bool,
1710
+ path: str,
1711
+ depth: int = 0,
1712
+ color: bool,
1713
+ marker_color: str | None,
1714
+ excluded: bool,
1715
+ collapsed: bool = False,
1716
+ path_color: str | None = None,
1717
+ ) -> str:
1718
+ indent = " " * depth
1719
+ label = f"{path}/" if directory else path
1720
+ traversal = " ▸" if collapsed else ""
1721
+ body = f"{marker} {indent}{label}{traversal}"
1722
+ if not color:
1723
+ return body
1724
+ if len(marker) == 4:
1725
+ action, exclusion, side = marker[0], marker[1], marker[3]
1726
+ side_color = _DIFF_MARKER_COLORS.get(side)
1727
+ exclusion_color = _DIFF_MARKER_COLORS.get(exclusion)
1728
+ rendered_side = (
1729
+ f"{side_color}{side}{_RESET}" if side_color and side != " " else side
1730
+ )
1731
+ rendered_exclusion = (
1732
+ f"{exclusion_color}{exclusion}{_RESET}"
1733
+ if exclusion_color and exclusion != " "
1734
+ else exclusion
1735
+ )
1736
+ rendered_action = (
1737
+ f"{marker_color}{action}{_RESET}"
1738
+ if marker_color and action != " "
1739
+ else action
1740
+ )
1741
+ rendered_status = f"{rendered_action}{rendered_exclusion} {rendered_side}"
1742
+ if directory:
1743
+ directory_color = (
1744
+ _COLLAPSED_DIRECTORY_COLOR
1745
+ if collapsed and not marker.strip()
1746
+ else path_color
1747
+ or (_EXCLUDED_DIRECTORY_COLOR if excluded else _DIRECTORY_COLOR)
1748
+ )
1749
+ suffix = " ▸" if collapsed else ""
1750
+ return (
1751
+ f"{rendered_status} {indent}"
1752
+ f"{directory_color}{path}/{suffix}{_RESET}"
1753
+ )
1754
+ path_style = marker_color or side_color
1755
+ rendered_path = (
1756
+ f"{path_style}{label}{traversal}{_RESET}"
1757
+ if path_style
1758
+ else f"{label}{traversal}"
1759
+ )
1760
+ return f"{rendered_status} {indent}{rendered_path}"
1761
+ if directory:
1762
+ if collapsed:
1763
+ colored_marker = (
1764
+ f"{marker_color}{marker}{_RESET}" if marker_color else marker
1765
+ )
1766
+ return (
1767
+ f"{colored_marker} {indent}"
1768
+ f"{_COLLAPSED_DIRECTORY_COLOR}{path}/ ▸{_RESET}"
1769
+ )
1770
+ directory_color = path_color or (
1771
+ _EXCLUDED_DIRECTORY_COLOR if excluded else _DIRECTORY_COLOR
1772
+ )
1773
+ colored_marker = (
1774
+ f"{marker_color}{marker}{_RESET}" if marker_color else marker
1775
+ )
1776
+ return f"{colored_marker} {indent}{directory_color}{path}/{_RESET}"
1777
+ if marker_color:
1778
+ return f"{marker_color}{body}{_RESET}"
1779
+ return body
1780
+
1781
+
1782
+ def _file_browser_order(
1783
+ entries: Sequence[_EntryT],
1784
+ *,
1785
+ path_of: Callable[[_EntryT], str],
1786
+ directory_of: Callable[[_EntryT], bool],
1787
+ ) -> tuple[_EntryT, ...]:
1788
+ directory_paths = {
1789
+ path_of(entry) for entry in entries if directory_of(entry)
1790
+ }
1791
+ for entry in entries:
1792
+ parts = PurePosixPath(path_of(entry)).parts
1793
+ directory_paths.update(
1794
+ PurePosixPath(*parts[:index]).as_posix()
1795
+ for index in range(1, len(parts))
1796
+ )
1797
+
1798
+ def order_key(entry: _EntryT) -> tuple[tuple[int, str, str], ...]:
1799
+ parts = PurePosixPath(path_of(entry)).parts
1800
+ return tuple(
1801
+ (
1802
+ 0
1803
+ if PurePosixPath(*parts[: index + 1]).as_posix()
1804
+ in directory_paths
1805
+ else 1,
1806
+ part.casefold(),
1807
+ part,
1808
+ )
1809
+ for index, part in enumerate(parts)
1810
+ )
1811
+
1812
+ return tuple(sorted(entries, key=order_key))
1813
+
1814
+
1815
+ def _format_comparison_entries(
1816
+ entries: Sequence[ComparisonEntry],
1817
+ direction: str,
1818
+ *,
1819
+ color: bool,
1820
+ collapsed_paths: frozenset[str] = frozenset(),
1821
+ display_path: Callable[[str], tuple[int, str]] | None = None,
1822
+ ) -> tuple[str, ...]:
1823
+ lines: list[str] = []
1824
+ for entry in _file_browser_order(
1825
+ entries,
1826
+ path_of=lambda item: item.path,
1827
+ directory_of=lambda item: _comparison_entry_kind(item, direction)
1828
+ == "directory",
1829
+ ):
1830
+ collapsed = entry.path in collapsed_paths
1831
+ directory = _comparison_entry_kind(entry, direction) == "directory"
1832
+ marker = (
1833
+ " "
1834
+ if directory and entry.action == "unchanged"
1835
+ else _comparison_marker(entry)
1836
+ )
1837
+ depth, path = display_path(entry.path) if display_path else (0, entry.path)
1838
+ lines.append(
1839
+ _format_path_line(
1840
+ marker,
1841
+ directory=directory,
1842
+ path=path,
1843
+ depth=depth,
1844
+ color=color,
1845
+ marker_color=_comparison_marker_color(marker),
1846
+ excluded=entry.action == "excluded",
1847
+ collapsed=collapsed,
1848
+ )
1849
+ )
1850
+ return tuple(lines)
1851
+
1852
+
1853
+ def _scoped_display_path(
1854
+ path: str,
1855
+ *,
1856
+ display_root: PurePosixPath | None,
1857
+ ) -> tuple[int, str]:
1858
+ profile_path = PurePosixPath(path)
1859
+ if display_root is None:
1860
+ return 0, profile_path.as_posix()
1861
+ if profile_path == display_root and display_root.parts:
1862
+ return 0, display_root.as_posix()
1863
+ relative = (
1864
+ profile_path.relative_to(display_root)
1865
+ if display_root.parts
1866
+ else profile_path
1867
+ )
1868
+ depth = len(relative.parts) if display_root.parts else max(
1869
+ len(relative.parts) - 1,
1870
+ 0,
1871
+ )
1872
+ return depth, relative.name
1873
+
1874
+
1875
+ def _comparison_ancestors(
1876
+ path: str,
1877
+ *,
1878
+ display_root: PurePosixPath | None,
1879
+ ) -> tuple[PurePosixPath, ...]:
1880
+ profile_path = PurePosixPath(path)
1881
+ start = len(display_root.parts) if display_root is not None else 1
1882
+ start = max(start, 1)
1883
+ return tuple(
1884
+ PurePosixPath(*profile_path.parts[:length])
1885
+ for length in range(start, len(profile_path.parts))
1886
+ if display_root is None
1887
+ or profile_path.parts[: len(display_root.parts)] == display_root.parts
1888
+ )
1889
+
1890
+
1891
+ def _format_compact_comparison_entry(
1892
+ entry: ComparisonEntry,
1893
+ direction: str,
1894
+ *,
1895
+ color: bool,
1896
+ collapsed: bool,
1897
+ display_root: PurePosixPath | None,
1898
+ emitted_directories: set[str],
1899
+ ) -> tuple[str, ...]:
1900
+ lines: list[str] = []
1901
+ for ancestor in _comparison_ancestors(
1902
+ entry.path,
1903
+ display_root=display_root,
1904
+ ):
1905
+ ancestor_path = ancestor.as_posix()
1906
+ if ancestor_path in emitted_directories:
1907
+ continue
1908
+ depth, label = _scoped_display_path(
1909
+ ancestor_path,
1910
+ display_root=display_root,
1911
+ )
1912
+ lines.append(
1913
+ _format_path_line(
1914
+ " ",
1915
+ directory=True,
1916
+ path=label,
1917
+ depth=depth,
1918
+ color=color,
1919
+ marker_color=None,
1920
+ excluded=False,
1921
+ )
1922
+ )
1923
+ emitted_directories.add(ancestor_path)
1924
+ lines.extend(
1925
+ _format_comparison_entries(
1926
+ (entry,),
1927
+ direction,
1928
+ color=color,
1929
+ collapsed_paths=frozenset((entry.path,)) if collapsed else frozenset(),
1930
+ display_path=lambda path: _scoped_display_path(
1931
+ path,
1932
+ display_root=display_root,
1933
+ ),
1934
+ )
1935
+ )
1936
+ if _comparison_entry_kind(entry, direction) == "directory":
1937
+ emitted_directories.add(entry.path)
1938
+ return tuple(lines)
1939
+
1940
+
1941
+ def _scope_header_lines(
1942
+ display_root: PurePosixPath | None,
1943
+ *,
1944
+ anchored: bool,
1945
+ color: bool,
1946
+ ) -> tuple[str, ...]:
1947
+ if display_root is None:
1948
+ return ()
1949
+ if anchored or not display_root.parts:
1950
+ return ()
1951
+ return (
1952
+ _format_path_line(
1953
+ " ",
1954
+ directory=True,
1955
+ path=display_root.as_posix(),
1956
+ color=color,
1957
+ marker_color=None,
1958
+ excluded=False,
1959
+ ),
1960
+ )
1961
+
1962
+
1963
+ def _file_selection(arguments: argparse.Namespace, root: Path) -> FileSelection:
1964
+ operands = list(normalize_pattern_operands(arguments))
1965
+ current_directory = _effective_current_directory(arguments, root)
1966
+ recursive = arguments.recursive or (
1967
+ arguments.command in {"diff", "push"} and not arguments.shallow
1968
+ )
1969
+ if not operands:
1970
+ return _current_directory_selection(
1971
+ root,
1972
+ current_directory=current_directory,
1973
+ recursive=recursive,
1974
+ )
1975
+ return _directory_contents_selection(
1976
+ operands,
1977
+ root,
1978
+ current_directory=current_directory,
1979
+ recursive=recursive,
1980
+ )
1981
+
1982
+
1983
+
1984
+ def _push_comparison_selection(
1985
+ arguments: argparse.Namespace,
1986
+ root: Path,
1987
+ local: TreeSnapshot,
1988
+ selection: DirectoryContentsSelection,
1989
+ ) -> FileSelection:
1990
+ """Keep explicitly selected remote-only directories as deletion targets."""
1991
+ local_entries = {entry.path: entry for entry in local.entries}
1992
+ for operand in normalize_pattern_operands(arguments):
1993
+ if operand == "." or any(character in operand for character in "*?["):
1994
+ continue
1995
+ path = FileSelector.from_argument(
1996
+ operand.rstrip("/"), profile_root=root,
1997
+ current_directory=_effective_current_directory(arguments, root),
1998
+ ).pattern
1999
+ entry = local_entries.get(path)
2000
+ if entry is None or (entry.excluded and entry.kind == "directory"):
2001
+ return selection.traversal
2002
+ return selection
2003
+
2004
+
2005
+ def _selection_from_values(
2006
+ values: Sequence[str],
2007
+ root: Path,
2008
+ current_directory: Path,
2009
+ ) -> FileSelection:
2010
+ selectors = tuple(
2011
+ FileSelector.from_argument(
2012
+ value,
2013
+ profile_root=root,
2014
+ current_directory=current_directory,
2015
+ )
2016
+ for value in values
2017
+ )
2018
+ if len(selectors) == 1:
2019
+ return selectors[0]
2020
+ return FileSelectorSet(selectors)
2021
+
2022
+
2023
+ def _list_selection(
2024
+ arguments: argparse.Namespace,
2025
+ root: Path,
2026
+ ) -> DirectoryContentsSelection:
2027
+ operands = list(normalize_pattern_operands(arguments))
2028
+ current_directory = _effective_current_directory(arguments, root)
2029
+ if not operands:
2030
+ return _current_directory_selection(
2031
+ root,
2032
+ current_directory=current_directory,
2033
+ recursive=arguments.recursive,
2034
+ )
2035
+ return _directory_contents_selection(
2036
+ operands,
2037
+ root,
2038
+ current_directory=current_directory,
2039
+ recursive=arguments.recursive,
2040
+ )
2041
+
2042
+
2043
+ def _current_directory_selection(
2044
+ root: Path,
2045
+ *,
2046
+ current_directory: Path,
2047
+ recursive: bool,
2048
+ ) -> DirectoryContentsSelection:
2049
+ pattern = "**" if recursive else "*"
2050
+ return DirectoryContentsSelection(
2051
+ _selection_from_values(
2052
+ (pattern,),
2053
+ root,
2054
+ current_directory,
2055
+ )
2056
+ )
2057
+
2058
+
2059
+ def _directory_contents_selection(
2060
+ operands: Sequence[str],
2061
+ root: Path,
2062
+ *,
2063
+ current_directory: Path,
2064
+ recursive: bool,
2065
+ ) -> DirectoryContentsSelection:
2066
+ traversal_patterns: list[str] = []
2067
+ container_patterns: list[str] = []
2068
+ for operand in operands:
2069
+ if operand == ".":
2070
+ traversal_patterns.append("**" if recursive else "*")
2071
+ continue
2072
+ normalized = operand.rstrip("/")
2073
+ container_patterns.append(normalized)
2074
+ traversal_patterns.extend(
2075
+ (
2076
+ normalized,
2077
+ f"{normalized}/{'**' if recursive else '*'}",
2078
+ )
2079
+ )
2080
+ traversal = _selection_from_values(
2081
+ traversal_patterns,
2082
+ root,
2083
+ current_directory,
2084
+ )
2085
+ containers = (
2086
+ _selection_from_values(container_patterns, root, current_directory)
2087
+ if container_patterns
2088
+ else None
2089
+ )
2090
+ return DirectoryContentsSelection(traversal, containers)
2091
+
2092
+
2093
+ def _filtered_listing(
2094
+ listing: TreeSnapshot,
2095
+ selector: FileSelection | None,
2096
+ ) -> TreeSnapshot:
2097
+ return TreeSnapshot(
2098
+ tuple(
2099
+ entry
2100
+ for entry in listing.entries
2101
+ if selector is None or selector.matches(entry.path)
2102
+ )
2103
+ )
2104
+
2105
+
2106
+ def _descendant_directories(
2107
+ local: TreeSnapshot,
2108
+ remote: TreeSnapshot,
2109
+ rules: RuleSet,
2110
+ selector: FileSelection | None,
2111
+ *,
2112
+ descend_remote_only: bool,
2113
+ ) -> tuple[tuple[PurePosixPath, bool, bool], ...]:
2114
+ local_directories = {
2115
+ entry.path: entry for entry in local.entries if entry.kind == "directory"
2116
+ }
2117
+ remote_directories = {
2118
+ entry.path: entry for entry in remote.entries if entry.kind == "directory"
2119
+ }
2120
+ paths = sorted(local_directories.keys() | remote_directories.keys())
2121
+ descendants: list[tuple[PurePosixPath, bool, bool]] = []
2122
+ for path in paths:
2123
+ local_entry = local_directories.get(path)
2124
+ remote_entry = remote_directories.get(path)
2125
+ if local_entry is None and not descend_remote_only:
2126
+ continue
2127
+ if selector is not None and not selector.may_match_descendant(path):
2128
+ continue
2129
+ if (
2130
+ any(
2131
+ entry is not None and entry.excluded
2132
+ for entry in (local_entry, remote_entry)
2133
+ )
2134
+ and not rules.may_include_descendant(path, target="local")
2135
+ ):
2136
+ continue
2137
+ if any(
2138
+ entry is not None and entry.remote_excluded
2139
+ for entry in (local_entry, remote_entry)
2140
+ ):
2141
+ continue
2142
+ descendants.append(
2143
+ (PurePosixPath(path), local_entry is not None, remote_entry is not None)
2144
+ )
2145
+ return tuple(descendants)
2146
+
2147
+
2148
+ def _profile_relative_current_directory(
2149
+ arguments: argparse.Namespace,
2150
+ root: Path,
2151
+ ) -> PurePosixPath:
2152
+ current = _effective_current_directory(arguments, root)
2153
+ try:
2154
+ relative = current.relative_to(root)
2155
+ except ValueError:
2156
+ return PurePosixPath()
2157
+ return PurePosixPath(*relative.parts)
2158
+
2159
+
2160
+ def _diff_traversal_roots(
2161
+ arguments: argparse.Namespace,
2162
+ root: Path,
2163
+ ) -> tuple[_DiffTraversalRoot, ...]:
2164
+ """Find the narrowest deterministic directories needed by the selection."""
2165
+ base = _profile_relative_current_directory(arguments, root)
2166
+ operands = normalize_pattern_operands(arguments)
2167
+ if not operands:
2168
+ return (_DiffTraversalRoot(base),)
2169
+
2170
+ candidates: list[_DiffTraversalRoot] = []
2171
+ for operand in operands:
2172
+ profile_path = base / PurePosixPath(operand)
2173
+ if operand == ".":
2174
+ candidates.append(_DiffTraversalRoot(base))
2175
+ continue
2176
+
2177
+ wildcard_index = next(
2178
+ (
2179
+ index
2180
+ for index, part in enumerate(profile_path.parts)
2181
+ if "*" in part
2182
+ ),
2183
+ None,
2184
+ )
2185
+ if wildcard_index is not None:
2186
+ fixed_parts = profile_path.parts[:wildcard_index]
2187
+ fixed = PurePosixPath(*fixed_parts) if fixed_parts else PurePosixPath()
2188
+ candidates.append(_DiffTraversalRoot(fixed))
2189
+ continue
2190
+
2191
+ local_path = root.joinpath(*profile_path.parts)
2192
+ if local_path.is_dir() and not local_path.is_symlink():
2193
+ candidates.append(_DiffTraversalRoot(profile_path, include_container=True))
2194
+ else:
2195
+ candidates.append(_DiffTraversalRoot(profile_path.parent))
2196
+
2197
+ ordered = sorted(
2198
+ candidates,
2199
+ key=lambda item: (item.path.parts, item.include_container),
2200
+ )
2201
+ roots: list[_DiffTraversalRoot] = []
2202
+ for candidate in ordered:
2203
+ covering = next(
2204
+ (
2205
+ existing
2206
+ for existing in roots
2207
+ if candidate.path.parts[: len(existing.path.parts)]
2208
+ == existing.path.parts
2209
+ ),
2210
+ None,
2211
+ )
2212
+ if covering is None:
2213
+ roots.append(candidate)
2214
+ elif covering.path == candidate.path and candidate.include_container:
2215
+ roots[roots.index(covering)] = candidate
2216
+ return tuple(roots)
2217
+
2218
+
2219
+ def _resume_directory(value: str | None) -> PurePosixPath | None:
2220
+ if value is None:
2221
+ return None
2222
+ path = PurePosixPath(value)
2223
+ if path.is_absolute() or not path.parts or ".." in path.parts:
2224
+ raise SelectionError(
2225
+ "resume directory must be a profile-relative directory"
2226
+ )
2227
+ if any(character in value for character in "*?["):
2228
+ raise SelectionError("resume directory cannot contain wildcards")
2229
+ return path
2230
+
2231
+
2232
+ def _resume_command(arguments: argparse.Namespace, directory: PurePosixPath) -> str:
2233
+ command = ["hlsync"]
2234
+ if arguments.profile_prefix is not None:
2235
+ command.append(arguments.profile_prefix)
2236
+ command.extend(("diff", *arguments.pattern_operands))
2237
+ if arguments.pull:
2238
+ command.append("--pull")
2239
+ if arguments.prune:
2240
+ command.append("--prune")
2241
+ if arguments.recursive:
2242
+ command.append("--recursive")
2243
+ if arguments.shallow:
2244
+ command.append("--shallow")
2245
+ if arguments.show_excluded:
2246
+ command.append("--excluded")
2247
+ if arguments.include_excluded:
2248
+ command.append("--include-excluded")
2249
+ if arguments.show_all:
2250
+ command.append("--all")
2251
+ command.extend(("--paged", "--resume", directory.as_posix()))
2252
+ return shlex.join(command)
2253
+
2254
+
2255
+ def _build_plan(
2256
+ arguments: argparse.Namespace,
2257
+ root: Path,
2258
+ transport: ExplicitFTPSTransport,
2259
+ rules: RuleSet,
2260
+ *,
2261
+ direction: str,
2262
+ progress: TextIO,
2263
+ include_excluded: bool = False,
2264
+ recover_artifacts: bool = True,
2265
+ ) -> tuple[TreeSnapshot, TreeSnapshot, ComparisonPlan]:
2266
+ selector = _file_selection(arguments, root)
2267
+ prune_remote = direction == "push" and getattr(arguments, "prune", False)
2268
+ print("Scanning local files...", file=progress, flush=True)
2269
+
2270
+ def report_local_directory(directory: PurePosixPath) -> None:
2271
+ print(f" Scanning {directory.as_posix()}", file=progress, flush=True)
2272
+
2273
+ local = snapshot_local(
2274
+ root,
2275
+ rules,
2276
+ selector,
2277
+ include_excluded=include_excluded,
2278
+ traverse_excluded=False,
2279
+ respect_remote_boundaries=True,
2280
+ directory_progress=report_local_directory,
2281
+ )
2282
+ print("Reading remote files over FTPS...", file=progress, flush=True)
2283
+
2284
+ with DirectoryReadProgress(progress) as reading:
2285
+ artifact_options: dict[str, Callable[[str], None]] = {}
2286
+ if direction == "push":
2287
+ option = "artifact_recovery" if recover_artifacts else "artifact_preview"
2288
+ artifact_options[option] = reading.message
2289
+ remote = transport.snapshot(
2290
+ rules,
2291
+ selector,
2292
+ include_excluded=include_excluded,
2293
+ traverse_excluded=False,
2294
+ directory_progress=reading.reading,
2295
+ directory_counts=reading.counts,
2296
+ **artifact_options,
2297
+ )
2298
+ print("Comparing local and remote files...", file=progress, flush=True)
2299
+ comparison_selection = (
2300
+ _push_comparison_selection(arguments, root, local, selector)
2301
+ if direction == "push" and prune_remote
2302
+ else selector
2303
+ )
2304
+ plan = build_comparison(
2305
+ local,
2306
+ remote,
2307
+ direction=direction,
2308
+ prune_remote=prune_remote,
2309
+ force=getattr(arguments, "force", False),
2310
+ selector=comparison_selection if arguments.pattern_operands else None,
2311
+ )
2312
+ untraversed_directories = frozenset(
2313
+ entry.path
2314
+ for entry in plan.entries
2315
+ if _comparison_entry_kind(entry, direction) == "directory"
2316
+ and not selector.may_match_descendant(entry.path)
2317
+ and entry.action != "excluded"
2318
+ )
2319
+ plan = mark_untraversed_directories(plan, untraversed_directories)
2320
+ return local, remote, plan
2321
+
2322
+
2323
+ def _diff(
2324
+ arguments: argparse.Namespace,
2325
+ store: ConfigurationStore,
2326
+ progress: TextIO,
2327
+ output: TextIO,
2328
+ ) -> None:
2329
+ _, name, profile = _resolve_profile(arguments, store)
2330
+ root = _require_local_root(name, profile)
2331
+ if arguments.resume is not None and not arguments.paged:
2332
+ raise ConfigurationError("--resume requires --paged")
2333
+ resume = _resume_directory(arguments.resume)
2334
+ selector = _file_selection(arguments, root)
2335
+ rules = _command_rules(arguments, store, profile)
2336
+ direction = "pull" if arguments.pull else "push"
2337
+ prune_remote = direction == "push" and arguments.prune
2338
+ color = _use_color(output)
2339
+ print(f"Checking differences for profile '{name}'...", file=progress, flush=True)
2340
+ options = _active_options(arguments)
2341
+ if options is not None:
2342
+ print(options, file=progress, flush=True)
2343
+ print("Connecting securely over FTPS...", file=progress, flush=True)
2344
+ traversal_roots = _diff_traversal_roots(arguments, root)
2345
+ if resume is not None:
2346
+ root_index = next(
2347
+ (
2348
+ index
2349
+ for index, traversal_root in enumerate(traversal_roots)
2350
+ if resume.parts[: len(traversal_root.path.parts)]
2351
+ == traversal_root.path.parts
2352
+ ),
2353
+ None,
2354
+ )
2355
+ if root_index is None:
2356
+ raise SelectionError(f"resume directory '{resume}' is not reachable")
2357
+ traversal_roots = traversal_roots[root_index:]
2358
+ pending: list[_PendingDiffDirectory | _PendingDiffOutput] = [
2359
+ _PendingDiffDirectory(
2360
+ path=traversal_root.path,
2361
+ has_local=root.joinpath(*traversal_root.path.parts).is_dir(),
2362
+ has_remote=True,
2363
+ include_container=traversal_root.include_container,
2364
+ is_root=True,
2365
+ display_root=(
2366
+ traversal_root.path if len(traversal_roots) == 1 else None
2367
+ ),
2368
+ display_anchor=traversal_root.include_container,
2369
+ )
2370
+ for traversal_root in reversed(traversal_roots)
2371
+ ]
2372
+ seeking = resume is not None
2373
+ selected_count = 0
2374
+ displayed_count = 0
2375
+ hidden: dict[str, int] = {}
2376
+ emitted_directories: set[str] = set()
2377
+
2378
+ def format_entries(
2379
+ entries: Sequence[ComparisonEntry],
2380
+ collapsed_paths: frozenset[str],
2381
+ display_root: PurePosixPath | None,
2382
+ ) -> tuple[str, ...]:
2383
+ if not arguments.show_all:
2384
+ return tuple(
2385
+ line
2386
+ for entry in entries
2387
+ for line in _format_compact_comparison_entry(
2388
+ entry,
2389
+ direction,
2390
+ color=color,
2391
+ collapsed=entry.path in collapsed_paths,
2392
+ display_root=display_root,
2393
+ emitted_directories=emitted_directories,
2394
+ )
2395
+ )
2396
+ return _format_comparison_entries(
2397
+ entries,
2398
+ direction,
2399
+ color=color,
2400
+ collapsed_paths=collapsed_paths,
2401
+ display_path=lambda path: _scoped_display_path(
2402
+ path, display_root=display_root,
2403
+ ),
2404
+ )
2405
+
2406
+ with ExplicitFTPSTransport(profile) as transport:
2407
+ if pending and arguments.show_all:
2408
+ for line in _scope_header_lines(
2409
+ pending[-1].display_root,
2410
+ anchored=pending[-1].display_anchor,
2411
+ color=color,
2412
+ ):
2413
+ print(line, file=output, flush=True)
2414
+ displayed_count += 1
2415
+ while pending:
2416
+ current = pending.pop()
2417
+ if isinstance(current, _PendingDiffOutput):
2418
+ lines = format_entries(
2419
+ (current.entry,), current.collapsed_paths, current.display_root,
2420
+ )
2421
+ for line in lines:
2422
+ print(line, file=output, flush=True)
2423
+ displayed_count += len(lines)
2424
+ continue
2425
+ directory = current.path
2426
+ display_directory = directory.as_posix()
2427
+ local_listing = (
2428
+ list_local_directory(root, directory, rules)
2429
+ if current.has_local
2430
+ else TreeSnapshot()
2431
+ )
2432
+ remote_directory_exists = current.has_remote
2433
+ try:
2434
+ remote_listing = (
2435
+ transport.list_directory(directory, rules)
2436
+ if current.has_remote
2437
+ else TreeSnapshot()
2438
+ )
2439
+ except PathOperationError:
2440
+ if not current.is_root or not directory.parts:
2441
+ raise
2442
+ remote_directory_exists = False
2443
+ remote_listing = TreeSnapshot()
2444
+ descendants = _descendant_directories(
2445
+ local_listing,
2446
+ remote_listing,
2447
+ rules,
2448
+ selector,
2449
+ descend_remote_only=prune_remote,
2450
+ )
2451
+ pending_descendants = tuple(
2452
+ _PendingDiffDirectory(
2453
+ path=path,
2454
+ has_local=local_exists,
2455
+ has_remote=remote_exists,
2456
+ include_container=False,
2457
+ is_root=False,
2458
+ display_root=current.display_root,
2459
+ display_anchor=current.display_anchor,
2460
+ )
2461
+ for path, local_exists, remote_exists in descendants
2462
+ )
2463
+
2464
+ if seeking and directory != resume:
2465
+ assert resume is not None
2466
+ current_parts = directory.parts
2467
+ if resume.parts[: len(current_parts)] != current_parts:
2468
+ raise SelectionError(
2469
+ f"resume directory '{resume}' is not reachable"
2470
+ )
2471
+ branch_length = len(current_parts) + 1
2472
+ branch = PurePosixPath(*resume.parts[:branch_length])
2473
+ matching_branch = next(
2474
+ (
2475
+ candidate
2476
+ for candidate in pending_descendants
2477
+ if candidate.path == branch
2478
+ ),
2479
+ None,
2480
+ )
2481
+ if matching_branch is None:
2482
+ raise SelectionError(
2483
+ f"resume directory '{resume}' is not reachable"
2484
+ )
2485
+ later = tuple(
2486
+ candidate
2487
+ for candidate in pending_descendants
2488
+ if candidate.path > branch
2489
+ )
2490
+ pending.extend(reversed(later))
2491
+ pending.append(matching_branch)
2492
+ continue
2493
+
2494
+ seeking = False
2495
+ local = _filtered_listing(
2496
+ local_listing,
2497
+ selector,
2498
+ )
2499
+ remote = _filtered_listing(
2500
+ remote_listing,
2501
+ selector,
2502
+ )
2503
+ if current.include_container and directory.parts:
2504
+ container_path = directory.as_posix()
2505
+ excluded = rules.excludes(
2506
+ container_path, target="local", is_directory=True
2507
+ )
2508
+ remote_excluded = rules.excludes(
2509
+ container_path, target="remote", is_directory=True
2510
+ )
2511
+ if current.has_local:
2512
+ local = TreeSnapshot(
2513
+ local.entries
2514
+ + (
2515
+ TreeEntry(
2516
+ container_path,
2517
+ "directory",
2518
+ excluded=excluded,
2519
+ remote_excluded=remote_excluded,
2520
+ ),
2521
+ )
2522
+ )
2523
+ if remote_directory_exists:
2524
+ remote = TreeSnapshot(
2525
+ remote.entries
2526
+ + (
2527
+ TreeEntry(
2528
+ container_path,
2529
+ "directory",
2530
+ excluded=excluded,
2531
+ remote_excluded=remote_excluded,
2532
+ ),
2533
+ )
2534
+ )
2535
+ selected_count += len(local.entries) + len(remote.entries)
2536
+ plan = build_comparison(
2537
+ local,
2538
+ remote,
2539
+ direction=direction,
2540
+ prune_remote=prune_remote,
2541
+ )
2542
+ descended_paths = frozenset(
2543
+ path.as_posix() for path, _, _ in descendants
2544
+ )
2545
+ collapsed_paths = frozenset(
2546
+ entry.path
2547
+ for entry in plan.entries
2548
+ if _comparison_entry_kind(entry, direction) == "directory"
2549
+ and entry.path not in descended_paths
2550
+ and entry.path != directory.as_posix()
2551
+ )
2552
+ plan = mark_untraversed_directories(plan, collapsed_paths)
2553
+ shown = tuple(
2554
+ entry
2555
+ for entry in plan.entries
2556
+ if _diff_entry_visible(entry, direction, arguments)
2557
+ )
2558
+ for entry in plan.entries:
2559
+ if entry not in shown and entry.path != directory.as_posix():
2560
+ category = _hidden_diff_category(entry)
2561
+ if category is not None:
2562
+ hidden[category] = hidden.get(category, 0) + 1
2563
+
2564
+ if arguments.paged:
2565
+ pending.extend(reversed(pending_descendants))
2566
+ lines = format_entries(shown, collapsed_paths, current.display_root)
2567
+ for line in lines:
2568
+ print(line, file=output, flush=True)
2569
+ displayed_count += len(lines)
2570
+ if not lines:
2571
+ print(
2572
+ f" nothing to {direction} in {display_directory}",
2573
+ file=output,
2574
+ flush=True,
2575
+ )
2576
+ _print_hidden_summary(hidden, output)
2577
+ if pending:
2578
+ print(
2579
+ f"Resume: {_resume_command(arguments, pending[-1].path)}",
2580
+ file=output,
2581
+ flush=True,
2582
+ )
2583
+ return
2584
+
2585
+ descendants_by_path = {
2586
+ descendant.path.as_posix(): descendant
2587
+ for descendant in pending_descendants
2588
+ }
2589
+ events: list[_PendingDiffDirectory | _PendingDiffOutput] = []
2590
+ ordered_entries = _file_browser_order(
2591
+ plan.entries,
2592
+ path_of=lambda item: item.path,
2593
+ directory_of=lambda item: (
2594
+ _comparison_entry_kind(item, direction) == "directory"
2595
+ ),
2596
+ )
2597
+ directory_entries = tuple(
2598
+ entry
2599
+ for entry in ordered_entries
2600
+ if _comparison_entry_kind(entry, direction) == "directory"
2601
+ )
2602
+ file_entries = tuple(
2603
+ entry
2604
+ for entry in ordered_entries
2605
+ if _comparison_entry_kind(entry, direction) != "directory"
2606
+ and entry in shown
2607
+ )
2608
+ for entry in directory_entries:
2609
+ if entry in shown:
2610
+ events.append(_PendingDiffOutput(
2611
+ entry, collapsed_paths, current.display_root,
2612
+ ))
2613
+ descendant = descendants_by_path.get(entry.path)
2614
+ if descendant is not None:
2615
+ events.append(descendant)
2616
+ events.extend(
2617
+ _PendingDiffOutput(entry, collapsed_paths, current.display_root)
2618
+ for entry in file_entries
2619
+ )
2620
+ scheduled_paths = {
2621
+ event.path.as_posix()
2622
+ for event in events
2623
+ if isinstance(event, _PendingDiffDirectory)
2624
+ }
2625
+ events.extend(
2626
+ descendant
2627
+ for descendant in pending_descendants
2628
+ if descendant.path.as_posix() not in scheduled_paths
2629
+ )
2630
+ pending.extend(reversed(events))
2631
+
2632
+ if seeking:
2633
+ assert resume is not None
2634
+ raise SelectionError(f"resume directory '{resume}' is not reachable")
2635
+ if arguments.pattern_operands and selected_count == 0:
2636
+ raise SelectionError(f"file selector '{selector.pattern}' matched no paths")
2637
+ if displayed_count == 0:
2638
+ print(f" nothing to {direction}", file=output, flush=True)
2639
+ _print_hidden_summary(hidden, output)
2640
+
2641
+
2642
+ _HIDDEN_DIFF_HINTS = {
2643
+ "excluded": "-x or -I",
2644
+ "remote-excluded": "-x",
2645
+ "remote-only": "-a",
2646
+ "local-only": "-a",
2647
+ }
2648
+
2649
+
2650
+ def _diff_entry_visible(
2651
+ entry: ComparisonEntry,
2652
+ direction: str,
2653
+ arguments: argparse.Namespace,
2654
+ ) -> bool:
2655
+ """Show what the transfer would do; -x adds exclusions, -a everything."""
2656
+ if arguments.show_all:
2657
+ return True
2658
+ if entry.action == "excluded":
2659
+ return arguments.show_excluded
2660
+ if entry.action == "untraversed":
2661
+ # An unentered folder matters only if it could still hold changes.
2662
+ if direction == "push":
2663
+ return entry.local_kind is not None
2664
+ return entry.local_kind is not None and entry.remote_kind is not None
2665
+ return entry.action not in {"unchanged", "skip"}
2666
+
2667
+
2668
+ def _hidden_diff_category(entry: ComparisonEntry) -> str | None:
2669
+ if entry.action == "excluded":
2670
+ return entry.state
2671
+ if entry.action in {"skip", "untraversed"}:
2672
+ if entry.local_kind is None:
2673
+ return "remote-only"
2674
+ if entry.remote_kind is None:
2675
+ return "local-only"
2676
+ return None
2677
+
2678
+
2679
+ def _print_hidden_summary(hidden: dict[str, int], output: TextIO) -> None:
2680
+ if not hidden:
2681
+ return
2682
+ parts = ", ".join(
2683
+ f"{hidden[category]} {category} (try using {_HIDDEN_DIFF_HINTS[category]})"
2684
+ for category in _HIDDEN_DIFF_HINTS
2685
+ if category in hidden
2686
+ )
2687
+ print(f"Not shown: {parts}", file=output, flush=True)
2688
+
2689
+
2690
+ def _format_transfer(
2691
+ name: str,
2692
+ result: TransferResult,
2693
+ *,
2694
+ dry_run: bool = False,
2695
+ connections: int = 0,
2696
+ ) -> str:
2697
+ direction = result.plan.direction.capitalize()
2698
+ if not result.succeeded:
2699
+ return (
2700
+ f"{direction} stopped after a failure for profile '{name}': "
2701
+ f"{result.changed_count} completed, {result.failed_count} failed, "
2702
+ f"{result.not_started_count} not started."
2703
+ )
2704
+ count = result.changed_count
2705
+ if count == 0:
2706
+ nothing = f" Nothing to {result.plan.direction}"
2707
+ if result.plan.direction == "push" and result.unchanged_file_count:
2708
+ files = result.unchanged_file_count
2709
+ noun = "file is" if files == 1 else "files are"
2710
+ nothing += f"; {files} {noun} up to date in this scope"
2711
+ lines = [f"{nothing}."]
2712
+ else:
2713
+ changes = f"{count} change{'s' if count != 1 else ''}"
2714
+ over = (
2715
+ f" over {connections} connection{'s' if connections != 1 else ''}"
2716
+ if connections
2717
+ else ""
2718
+ )
2719
+ lines = (
2720
+ [f"Dry push: {count} planned change{'s' if count != 1 else ''}."]
2721
+ if dry_run
2722
+ else [f"{direction} complete: {changes}{over}."]
2723
+ )
2724
+ if result.plan.direction == "pull":
2725
+ skipped = [entry for entry in result.plan.entries if entry.action == "skip"]
2726
+ if skipped:
2727
+ lines.append("Remote-only paths not restored:")
2728
+ lines.extend(f" {entry.path}" for entry in skipped)
2729
+ return "\n".join(lines)
2730
+
2731
+
2732
+ def _report_transfer_operation(
2733
+ operation: TransferOperation | TransferIssue,
2734
+ progress: TextIO,
2735
+ ) -> None:
2736
+ if isinstance(operation, TransferIssue):
2737
+ line = f"failed {operation.path}: {operation.reason}"
2738
+ if _use_color(progress):
2739
+ line = f"\033[31m{line}{_RESET}"
2740
+ print(f" {line}", file=progress, flush=True)
2741
+ return
2742
+ marker = _TRANSFER_MARKERS[operation.action]
2743
+ print(
2744
+ " " + _format_path_line(
2745
+ marker,
2746
+ directory=operation.kind == "directory",
2747
+ path=operation.path,
2748
+ color=_use_color(progress),
2749
+ marker_color=_DIFF_MARKER_COLORS[marker],
2750
+ excluded=False,
2751
+ ),
2752
+ file=progress,
2753
+ flush=True,
2754
+ )
2755
+
2756
+
2757
+ def _byte_label(size: int) -> str:
2758
+ value = float(size)
2759
+ for unit in ("B", "KiB", "MiB", "GiB", "TiB"):
2760
+ if value < 1024 or unit == "TiB":
2761
+ return f"{value:.1f} {unit}" if unit != "B" else f"{size} B"
2762
+ value /= 1024
2763
+ raise AssertionError("unreachable byte unit")
2764
+
2765
+
2766
+ class _UploadProgress:
2767
+ def __init__(
2768
+ self, output: TextIO, uploads: dict[str, int], *, dry_run: bool,
2769
+ ) -> None:
2770
+ self.output = output
2771
+ self.uploads = uploads
2772
+ self.total_bytes = sum(uploads.values())
2773
+ self.sent = 0
2774
+ self.completed = 0
2775
+ self.issues = 0
2776
+ self.last_draw = 0.0
2777
+ self.visible = False
2778
+ self.terminal = bool(
2779
+ uploads and not dry_run and output.isatty()
2780
+ and os.environ.get("TERM") != "dumb"
2781
+ )
2782
+ if uploads:
2783
+ label = "Planned uploads" if dry_run else "Uploading"
2784
+ print(
2785
+ f"{label}: {len(uploads)} files · {_byte_label(self.total_bytes)}.",
2786
+ file=output, flush=True,
2787
+ )
2788
+
2789
+ def clear(self) -> None:
2790
+ if self.visible:
2791
+ print("\r\033[2K", end="", file=self.output, flush=True)
2792
+ self.visible = False
2793
+
2794
+ def draw(self, *, force: bool = False) -> None:
2795
+ if not self.terminal:
2796
+ return
2797
+ now = time.monotonic()
2798
+ if not force and now - self.last_draw < 0.1:
2799
+ return
2800
+ self.last_draw = now
2801
+ fraction = (
2802
+ self.sent / self.total_bytes if self.total_bytes
2803
+ else self.completed / len(self.uploads)
2804
+ )
2805
+ filled = min(16, int(fraction * 16))
2806
+ bar = "#" * filled + "-" * (16 - filled)
2807
+ line = (
2808
+ f" [{bar}] {self.completed}/{len(self.uploads)} installed · "
2809
+ f"{_byte_label(self.sent)}/{_byte_label(self.total_bytes)} sent"
2810
+ )
2811
+ if self.issues:
2812
+ line += f" · {self.issues} failed"
2813
+ width = max(1, shutil.get_terminal_size().columns - 1)
2814
+ print(f"\r\033[2K{line[:width]}", end="", file=self.output, flush=True)
2815
+ self.visible = True
2816
+
2817
+ def advance(self, count: int) -> None:
2818
+ self.sent += count
2819
+ self.draw()
2820
+
2821
+ def report(self, event: TransferOperation | TransferIssue) -> None:
2822
+ self.clear()
2823
+ if event.path in self.uploads:
2824
+ if isinstance(event, TransferIssue):
2825
+ self.issues += 1
2826
+ else:
2827
+ self.completed += 1
2828
+ _report_transfer_operation(event, self.output)
2829
+ self.draw(force=True)
2830
+
2831
+ def finish(self) -> None:
2832
+ if self.terminal:
2833
+ self.draw(force=True)
2834
+ print(file=self.output, flush=True)
2835
+ self.visible = False
2836
+
2837
+
2838
+ def _transfer(
2839
+ arguments: argparse.Namespace,
2840
+ store: ConfigurationStore,
2841
+ progress: TextIO,
2842
+ ) -> tuple[str, bool]:
2843
+ _, name, profile = _resolve_profile(arguments, store)
2844
+ root = _require_local_root(name, profile)
2845
+ print(
2846
+ f"Preparing {arguments.command} for profile '{name}'...",
2847
+ file=progress,
2848
+ flush=True,
2849
+ )
2850
+ options = _active_options(arguments)
2851
+ if options is not None:
2852
+ print(options, file=progress, flush=True)
2853
+ print("Connecting securely over FTPS...", file=progress, flush=True)
2854
+ with ExplicitFTPSTransport(profile) as transport, ExitStack() as sessions:
2855
+ local, remote, plan = _build_plan(
2856
+ arguments,
2857
+ root,
2858
+ transport,
2859
+ _command_rules(arguments, store, profile),
2860
+ direction=arguments.command,
2861
+ progress=progress,
2862
+ include_excluded=arguments.command == "push",
2863
+ recover_artifacts=not getattr(arguments, "dry", False),
2864
+ )
2865
+ dry_run = getattr(arguments, "dry", False)
2866
+ upload_paths = {
2867
+ entry.path for entry in plan.entries
2868
+ if entry.action in {"upload", "replace-remote"}
2869
+ }
2870
+ uploads = {
2871
+ entry.path: entry.size or 0
2872
+ for entry in local.entries
2873
+ if entry.path in upload_paths
2874
+ } if arguments.command == "push" else {}
2875
+ feedback = _UploadProgress(progress, uploads, dry_run=dry_run)
2876
+ upload_sessions = (
2877
+ _open_upload_sessions(
2878
+ profile, arguments.jobs, len(uploads), sessions, progress
2879
+ )
2880
+ if uploads and not dry_run
2881
+ else ()
2882
+ )
2883
+ executable_actions = {
2884
+ "create-remote",
2885
+ "upload",
2886
+ "replace-remote",
2887
+ "replace-local",
2888
+ "delete-remote",
2889
+ }
2890
+ if any(entry.action in executable_actions for entry in plan.entries):
2891
+ progress_message = (
2892
+ "Dry push..."
2893
+ if dry_run
2894
+ else (
2895
+ "Pushing changes..."
2896
+ if arguments.command == "push"
2897
+ else "Pulling changes..."
2898
+ )
2899
+ )
2900
+ print(progress_message, file=progress, flush=True)
2901
+ try:
2902
+ feedback.draw(force=True)
2903
+ result = execute_transfer(
2904
+ plan,
2905
+ local_root=root,
2906
+ local=local,
2907
+ remote=remote,
2908
+ transport=transport,
2909
+ progress=feedback.report,
2910
+ dry_run=dry_run,
2911
+ byte_progress=feedback.advance if uploads and not dry_run else None,
2912
+ upload_sessions=upload_sessions,
2913
+ )
2914
+ finally:
2915
+ feedback.finish()
2916
+ return (
2917
+ _format_transfer(
2918
+ name,
2919
+ result,
2920
+ dry_run=dry_run,
2921
+ connections=len(upload_sessions) + 1 if uploads and not dry_run else 0,
2922
+ ),
2923
+ result.succeeded,
2924
+ )
2925
+
2926
+
2927
+ def _show_help(
2928
+ parser: argparse.ArgumentParser,
2929
+ topic: str | None,
2930
+ stdin: TextIO,
2931
+ stdout: TextIO,
2932
+ ) -> str:
2933
+ if topic is None:
2934
+ return parser.format_help().rstrip()
2935
+ subparser = next(
2936
+ action
2937
+ for action in parser._actions
2938
+ if isinstance(action, argparse._SubParsersAction)
2939
+ )
2940
+ resolved = _resolve_command_name(topic, stdin=stdin, stdout=stdout)
2941
+ return subparser.choices[resolved].format_help().rstrip()
2942
+
2943
+
2944
+ def run(
2945
+ argv: Sequence[str] | None = None,
2946
+ *,
2947
+ store: ConfigurationStore | None = None,
2948
+ stdin: TextIO = sys.stdin,
2949
+ stdout: TextIO = sys.stdout,
2950
+ stderr: TextIO = sys.stderr,
2951
+ ) -> int:
2952
+ parser = build_parser()
2953
+ raw_arguments = list(sys.argv[1:] if argv is None else argv)
2954
+ try:
2955
+ raw_arguments, profile_prefix = _resolve_invocation(
2956
+ raw_arguments,
2957
+ stdin=stdin,
2958
+ stdout=stdout,
2959
+ )
2960
+ except ConfigurationError as error:
2961
+ parser.error(str(error))
2962
+ arguments = parser.parse_args(raw_arguments)
2963
+ arguments.profile_prefix = profile_prefix
2964
+ if arguments.legend:
2965
+ if arguments.command is not None:
2966
+ parser.error("--legend cannot be combined with a command")
2967
+ print(_format_legend(stdout), file=stdout)
2968
+ return 0
2969
+ if arguments.command is None:
2970
+ parser.error("a command is required unless --legend is supplied")
2971
+ configuration_store = store or ConfigurationStore()
2972
+ exit_status = 0
2973
+ try:
2974
+ _validate_profile_prefix(arguments)
2975
+ if arguments.command == "create":
2976
+ message = _create_profile(arguments, configuration_store, stdin, stdout)
2977
+ elif arguments.command == "connect":
2978
+ message = _connect(arguments, configuration_store)
2979
+ elif arguments.command == "map":
2980
+ message = _map(arguments, configuration_store, stdin, stdout)
2981
+ elif arguments.command == "rules":
2982
+ message = _manage_rules(arguments, configuration_store)
2983
+ elif arguments.command in {"exclude", "include"}:
2984
+ message = _change_rules(
2985
+ arguments,
2986
+ configuration_store,
2987
+ include=arguments.command == "include",
2988
+ )
2989
+ elif arguments.command == "remove":
2990
+ message = _remove(arguments, configuration_store)
2991
+ elif arguments.command == "root":
2992
+ message = _show_root(arguments, configuration_store)
2993
+ elif arguments.command == "profile":
2994
+ message = _show_profile(arguments, configuration_store)
2995
+ elif arguments.command == "profiles":
2996
+ message = _list_profiles(configuration_store)
2997
+ elif arguments.command == "list":
2998
+ message = (
2999
+ _list_remote(arguments, configuration_store, stderr, stdout)
3000
+ if arguments.remote
3001
+ else _list_local(arguments, configuration_store, stdout)
3002
+ )
3003
+ elif arguments.command == "diff":
3004
+ _diff(arguments, configuration_store, stderr, stdout)
3005
+ message = None
3006
+ elif arguments.command in {"push", "pull"}:
3007
+ message, succeeded = _transfer(
3008
+ arguments,
3009
+ configuration_store,
3010
+ stderr,
3011
+ )
3012
+ if not succeeded:
3013
+ exit_status = 1
3014
+ elif arguments.command == "help":
3015
+ message = _show_help(parser, arguments.topic, stdin, stdout)
3016
+ elif arguments.command == "version":
3017
+ message = __version__
3018
+ else:
3019
+ parser.error(f"unknown command: {arguments.command}")
3020
+ return 2
3021
+ except (
3022
+ ConfigurationError,
3023
+ RuleError,
3024
+ PatternOperandError,
3025
+ SelectionError,
3026
+ SnapshotError,
3027
+ TransportError,
3028
+ TransferError,
3029
+ ) as error:
3030
+ print(f"hlsync: error: {error}", file=stderr)
3031
+ return 1
3032
+ if message is not None:
3033
+ print(message, file=stdout)
3034
+ return exit_status
3035
+
3036
+
3037
+ def main(argv: Sequence[str] | None = None) -> int:
3038
+ return run(argv)