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