networka 0.1.9__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.
Files changed (93) hide show
  1. network_toolkit/__about__.py +4 -0
  2. network_toolkit/__init__.py +8 -0
  3. network_toolkit/__main__.py +10 -0
  4. network_toolkit/builtin_sequences/arista_eos/common.yml +53 -0
  5. network_toolkit/builtin_sequences/mikrotik_routeros/common.yml +52 -0
  6. network_toolkit/cli.py +265 -0
  7. network_toolkit/commands/__init__.py +8 -0
  8. network_toolkit/commands/backup.py +441 -0
  9. network_toolkit/commands/complete.py +172 -0
  10. network_toolkit/commands/config.py +1068 -0
  11. network_toolkit/commands/diff.py +485 -0
  12. network_toolkit/commands/download.py +197 -0
  13. network_toolkit/commands/firmware.py +780 -0
  14. network_toolkit/commands/info.py +377 -0
  15. network_toolkit/commands/list.py +345 -0
  16. network_toolkit/commands/routerboard_upgrade.py +204 -0
  17. network_toolkit/commands/run.py +839 -0
  18. network_toolkit/commands/schema_unified.py +91 -0
  19. network_toolkit/commands/sequence.py +17 -0
  20. network_toolkit/commands/ssh.py +540 -0
  21. network_toolkit/commands/ssh_engines.py +0 -0
  22. network_toolkit/commands/ssh_fallback.py +97 -0
  23. network_toolkit/commands/ssh_platform.py +120 -0
  24. network_toolkit/commands/upload.py +237 -0
  25. network_toolkit/commands/vendor_config_backup.py +378 -0
  26. network_toolkit/common/color_magic.py +177 -0
  27. network_toolkit/common/command.py +135 -0
  28. network_toolkit/common/command_base.py +135 -0
  29. network_toolkit/common/command_helpers.py +214 -0
  30. network_toolkit/common/credentials.py +86 -0
  31. network_toolkit/common/defaults.py +17 -0
  32. network_toolkit/common/errors.py +130 -0
  33. network_toolkit/common/interactive_confirmation.py +144 -0
  34. network_toolkit/common/logging.py +47 -0
  35. network_toolkit/common/output.py +594 -0
  36. network_toolkit/common/output_clean.py +244 -0
  37. network_toolkit/common/paths.py +86 -0
  38. network_toolkit/common/resolver.py +207 -0
  39. network_toolkit/common/styles.py +199 -0
  40. network_toolkit/common/table_generator.py +169 -0
  41. network_toolkit/common/table_providers.py +716 -0
  42. network_toolkit/config.py +1506 -0
  43. network_toolkit/credentials.py +288 -0
  44. network_toolkit/device.py +1658 -0
  45. network_toolkit/device_transfers.py +170 -0
  46. network_toolkit/exceptions.py +78 -0
  47. network_toolkit/ip_device.py +241 -0
  48. network_toolkit/platforms/__init__.py +21 -0
  49. network_toolkit/platforms/base.py +267 -0
  50. network_toolkit/platforms/cisco_ios/__init__.py +6 -0
  51. network_toolkit/platforms/cisco_ios/constants.py +15 -0
  52. network_toolkit/platforms/cisco_ios/operations.py +426 -0
  53. network_toolkit/platforms/cisco_iosxe/__init__.py +6 -0
  54. network_toolkit/platforms/cisco_iosxe/constants.py +15 -0
  55. network_toolkit/platforms/cisco_iosxe/operations.py +580 -0
  56. network_toolkit/platforms/cisco_shared/__init__.py +0 -0
  57. network_toolkit/platforms/cisco_shared/operations.py +0 -0
  58. network_toolkit/platforms/factory.py +190 -0
  59. network_toolkit/platforms/mikrotik_routeros/__init__.py +8 -0
  60. network_toolkit/platforms/mikrotik_routeros/confirmation_patterns.py +24 -0
  61. network_toolkit/platforms/mikrotik_routeros/constants.py +31 -0
  62. network_toolkit/platforms/mikrotik_routeros/operations.py +686 -0
  63. network_toolkit/results_enhanced.py +364 -0
  64. network_toolkit/schemas/__init__.py +8 -0
  65. network_toolkit/sequence_manager.py +239 -0
  66. network_toolkit/shell_completion/bash_completion_nw.sh +339 -0
  67. network_toolkit/shell_completion/zsh_completion_nw.zsh +136 -0
  68. network_toolkit/transport/__init__.py +15 -0
  69. network_toolkit/transport/factory.py +113 -0
  70. network_toolkit/transport/interfaces.py +46 -0
  71. network_toolkit/transport/nornir_inventory.py +173 -0
  72. network_toolkit/transport/nornir_netmiko.py +277 -0
  73. network_toolkit/transport/scrapli_sync.py +36 -0
  74. network_toolkit/tui/__init__.py +18 -0
  75. network_toolkit/tui/app.py +1275 -0
  76. network_toolkit/tui/clipboard.py +46 -0
  77. network_toolkit/tui/compat.py +111 -0
  78. network_toolkit/tui/constants.py +111 -0
  79. network_toolkit/tui/controller.py +550 -0
  80. network_toolkit/tui/data.py +149 -0
  81. network_toolkit/tui/dialogs.py +196 -0
  82. network_toolkit/tui/helpers.py +55 -0
  83. network_toolkit/tui/keymap.py +31 -0
  84. network_toolkit/tui/layout.py +111 -0
  85. network_toolkit/tui/models.py +93 -0
  86. network_toolkit/tui/output_manager.py +372 -0
  87. network_toolkit/tui/prompt.py +172 -0
  88. network_toolkit/tui/services.py +285 -0
  89. networka-0.1.9.dist-info/METADATA +316 -0
  90. networka-0.1.9.dist-info/RECORD +93 -0
  91. networka-0.1.9.dist-info/WHEEL +4 -0
  92. networka-0.1.9.dist-info/entry_points.txt +2 -0
  93. networka-0.1.9.dist-info/licenses/LICENSE +73 -0
@@ -0,0 +1,485 @@
1
+ """`nw diff` command implementation.
2
+
3
+ Provides smart diffing of device configuration and operational state:
4
+ - Config diff: compares current RouterOS export (compact) with a baseline file
5
+ - Command diff: compares a single command output with a baseline file
6
+ - Sequence diff: compares a sequence's per-command outputs with files in a baseline directory
7
+
8
+ Subject-based UX:
9
+ nw diff <targets> <subject>
10
+ Where subject is one of:
11
+ - "config" (special keyword for /export compact)
12
+ - "/..." (a RouterOS command)
13
+ - a sequence name (resolved per-device)
14
+
15
+ Device-to-device: if exactly two devices are provided and no --baseline is supplied,
16
+ the command compares outputs directly between the devices.
17
+
18
+ Exit codes:
19
+ - 0: No differences
20
+ - 1: Differences found or baseline missing/mismatched
21
+ - 2: Usage / configuration error (bad inputs)
22
+ """
23
+
24
+ from __future__ import annotations
25
+
26
+ import difflib
27
+ import re
28
+ from dataclasses import dataclass
29
+ from pathlib import Path
30
+ from typing import Annotated
31
+
32
+ import typer
33
+
34
+ from network_toolkit.common.command import CommandContext
35
+ from network_toolkit.common.defaults import DEFAULT_CONFIG_PATH
36
+ from network_toolkit.common.output import OutputMode
37
+ from network_toolkit.config import load_config
38
+ from network_toolkit.exceptions import NetworkToolkitError
39
+ from network_toolkit.results_enhanced import ResultsManager
40
+ from network_toolkit.sequence_manager import SequenceManager
41
+
42
+
43
+ @dataclass
44
+ class DiffOutcome:
45
+ changed: bool
46
+ output: str
47
+
48
+
49
+ def _sanitize_filename(text: str) -> str:
50
+ return re.sub(r"[\\/:*?\"<>|\s]+", "_", text).strip("_.")
51
+
52
+
53
+ def _read_text(path: Path) -> str:
54
+ return path.read_text(encoding="utf-8")
55
+
56
+
57
+ def _write_text(path: Path, text: str) -> None:
58
+ path.parent.mkdir(parents=True, exist_ok=True)
59
+ path.write_text(text, encoding="utf-8")
60
+
61
+
62
+ def _filter_lines(text: str, ignore_patterns: list[str]) -> list[str]:
63
+ if not ignore_patterns:
64
+ return text.splitlines(keepends=False)
65
+ regexes = [re.compile(p) for p in ignore_patterns]
66
+ lines: list[str] = []
67
+ for line in text.splitlines(keepends=False):
68
+ if any(r.search(line) for r in regexes):
69
+ continue
70
+ lines.append(line)
71
+ return lines
72
+
73
+
74
+ def _make_unified_diff(
75
+ a_lines: list[str], b_lines: list[str], a_label: str, b_label: str
76
+ ) -> str:
77
+ diff = difflib.unified_diff(a_lines, b_lines, fromfile=a_label, tofile=b_label)
78
+ return "\n".join(diff)
79
+
80
+
81
+ def _diff_texts(
82
+ *,
83
+ baseline_text: str,
84
+ current_text: str,
85
+ baseline_label: str,
86
+ current_label: str,
87
+ ignore_patterns: list[str],
88
+ ) -> DiffOutcome:
89
+ a = _filter_lines(baseline_text, ignore_patterns)
90
+ b = _filter_lines(current_text, ignore_patterns)
91
+ out = _make_unified_diff(a, b, baseline_label, current_label)
92
+ return DiffOutcome(changed=bool(out.strip()), output=out)
93
+
94
+
95
+ def _find_baseline_file_for_command(base_dir: Path, command: str) -> Path | None:
96
+ stem = f"cmd_{_sanitize_filename(command)}"
97
+ for ext in (".txt", ".log", ".out"):
98
+ candidate = base_dir / f"{stem}{ext}"
99
+ if candidate.exists():
100
+ return candidate
101
+ return None
102
+
103
+
104
+ def register(app: typer.Typer) -> None:
105
+ @app.command(rich_help_panel="Remote Operations")
106
+ def diff(
107
+ target: Annotated[
108
+ str,
109
+ typer.Argument(
110
+ help=(
111
+ "Device/group name or comma-separated list (e.g. 'sw-1,lab_devices')"
112
+ ),
113
+ ),
114
+ ],
115
+ subject: Annotated[
116
+ str,
117
+ typer.Argument(
118
+ help=(
119
+ "Subject to diff: 'config' for /export compact, a RouterOS command "
120
+ "starting with '/', or the name of a configured sequence."
121
+ ),
122
+ ),
123
+ ],
124
+ *,
125
+ baseline: Annotated[
126
+ Path | None,
127
+ typer.Option(
128
+ "--baseline",
129
+ "-b",
130
+ help=(
131
+ "Baseline file (for config/command) or directory (for sequence)."
132
+ ),
133
+ ),
134
+ ] = None,
135
+ ignore: Annotated[
136
+ list[str] | None,
137
+ typer.Option(
138
+ "--ignore",
139
+ help=("Regex to ignore lines; repeat for multiple patterns."),
140
+ ),
141
+ ] = None,
142
+ save_current: Annotated[
143
+ Path | None,
144
+ typer.Option(
145
+ "--save-current",
146
+ help=(
147
+ "Optional path to save the current fetched state "
148
+ "(file or directory)."
149
+ ),
150
+ ),
151
+ ] = None,
152
+ config_file: Annotated[
153
+ Path, typer.Option("--config", "-c", help="Configuration file path")
154
+ ] = DEFAULT_CONFIG_PATH,
155
+ output_mode: Annotated[
156
+ OutputMode | None,
157
+ typer.Option(
158
+ "--output-mode",
159
+ "-o",
160
+ help="Output decoration mode: default, light, dark, no-color, raw",
161
+ show_default=False,
162
+ ),
163
+ ] = None,
164
+ verbose: Annotated[
165
+ bool, typer.Option("--verbose", "-v", help="Enable verbose logging")
166
+ ] = False,
167
+ store_results: Annotated[
168
+ bool,
169
+ typer.Option(
170
+ "--store-results",
171
+ "-s",
172
+ help="Store diff outputs to files",
173
+ ),
174
+ ] = False,
175
+ results_dir: Annotated[
176
+ str | None,
177
+ typer.Option("--results-dir", help="Override results directory"),
178
+ ] = None,
179
+ ) -> None:
180
+ """Diff config, a command, or a sequence.
181
+
182
+ Examples:
183
+ - nw diff sw-acc1 config -b baseline/export_compact.txt
184
+ - nw diff sw-acc1 "/system/resource/print" -b baseline/resource.txt
185
+ - nw diff lab_devices system_info -b baseline_dir/
186
+ - nw diff sw-acc1,sw-acc2 "/system/resource/print" # device-to-device
187
+ - nw diff sw-acc1,sw-acc2 config # device-to-device
188
+ """
189
+ # Create command context with proper styling
190
+ ctx = CommandContext(
191
+ output_mode=output_mode,
192
+ verbose=verbose,
193
+ config_file=config_file,
194
+ )
195
+
196
+ subj = subject.strip()
197
+ is_config = subj.lower() == "config"
198
+ is_command = subj.startswith("/")
199
+
200
+ try:
201
+ config = load_config(config_file)
202
+ except Exception as e: # pragma: no cover - load errors covered elsewhere
203
+ ctx.print_error(f"Failed to load config: {e}")
204
+ raise typer.Exit(2) from None
205
+
206
+ sm = SequenceManager(config)
207
+ mode_label = (
208
+ "config" if is_config else ("command" if is_command else "sequence")
209
+ )
210
+ cmd_ctx = f"diff_{target}_{mode_label}_{_sanitize_filename(subj)}"
211
+ results_mgr = ResultsManager(
212
+ config,
213
+ store_results=store_results,
214
+ results_dir=results_dir,
215
+ command_context=cmd_ctx,
216
+ )
217
+
218
+ # Resolve device list (comma-separated targets supported)
219
+ def resolve_targets(target_expr: str) -> tuple[list[str], list[str]]:
220
+ requested = [t.strip() for t in target_expr.split(",") if t.strip()]
221
+ devices: list[str] = []
222
+ unknowns: list[str] = []
223
+
224
+ def _add(name: str) -> None:
225
+ if name not in devices:
226
+ devices.append(name)
227
+
228
+ for name in requested:
229
+ if config.devices and name in config.devices:
230
+ _add(name)
231
+ elif config.device_groups and name in config.device_groups:
232
+ for m in config.get_group_members(name):
233
+ _add(m)
234
+ else:
235
+ unknowns.append(name)
236
+ return devices, unknowns
237
+
238
+ devices, unknown = resolve_targets(target)
239
+ if unknown and not devices:
240
+ ctx.print_error("Error: target(s) not found: " + ", ".join(unknown))
241
+ raise typer.Exit(2)
242
+ if unknown:
243
+ ctx.print_warning("Ignoring unknown target(s): " + ", ".join(unknown))
244
+
245
+ # Late import to preserve test patches of network_toolkit.cli.DeviceSession
246
+ from network_toolkit.cli import DeviceSession
247
+
248
+ total_changed = 0
249
+ total_missing = 0
250
+ per_device_reports: list[
251
+ tuple[str, list[tuple[str, DiffOutcome | None, str]]]
252
+ ] = []
253
+
254
+ # Helper to optionally save current fetches
255
+ def _save_current_artifact(dev: str, name: str, text: str) -> None:
256
+ if not save_current:
257
+ return
258
+ path = Path(save_current)
259
+ if path.suffix: # looks like a file path
260
+ # For multi-artifact (sequence), append sanitized name
261
+ if name:
262
+ parent = path.parent / _sanitize_filename(dev)
263
+ _write_text(parent / f"{_sanitize_filename(name)}.txt", text)
264
+ else:
265
+ _write_text(path, text)
266
+ else:
267
+ # Directory
268
+ dst = path / _sanitize_filename(dev)
269
+ _write_text(dst / (f"{_sanitize_filename(name) or 'config'}.txt"), text)
270
+
271
+ try:
272
+ # Device-to-device mode: exactly two devices and no baseline
273
+ device_pair = 2
274
+ if baseline is None and len(devices) == device_pair:
275
+ dev_a, dev_b = devices[0], devices[1]
276
+ label_pair = f"{dev_a} vs {dev_b}"
277
+ rows: list[tuple[str, DiffOutcome | None, str]] = []
278
+
279
+ if is_config:
280
+ with DeviceSession(dev_a, config) as sa:
281
+ curr_a = sa.execute_command("/export compact")
282
+ with DeviceSession(dev_b, config) as sb:
283
+ curr_b = sb.execute_command("/export compact")
284
+ _save_current_artifact(dev_a, "export_compact", curr_a)
285
+ _save_current_artifact(dev_b, "export_compact", curr_b)
286
+ outcome = _diff_texts(
287
+ baseline_text=curr_a,
288
+ current_text=curr_b,
289
+ baseline_label=f"{dev_a}:/export compact",
290
+ current_label=f"{dev_b}:/export compact",
291
+ ignore_patterns=ignore or [],
292
+ )
293
+ rows.append(("config", outcome, ""))
294
+
295
+ elif is_command:
296
+ with DeviceSession(dev_a, config) as sa:
297
+ curr_a = sa.execute_command(subj)
298
+ with DeviceSession(dev_b, config) as sb:
299
+ curr_b = sb.execute_command(subj)
300
+ _save_current_artifact(dev_a, subj, curr_a)
301
+ _save_current_artifact(dev_b, subj, curr_b)
302
+ outcome = _diff_texts(
303
+ baseline_text=curr_a,
304
+ current_text=curr_b,
305
+ baseline_label=f"{dev_a}:{subj}",
306
+ current_label=f"{dev_b}:{subj}",
307
+ ignore_patterns=ignore or [],
308
+ )
309
+ rows.append((subj, outcome, ""))
310
+
311
+ else: # sequence
312
+ cmds_a: list[str] | None = sm.resolve(subj, dev_a)
313
+ cmds_b: list[str] | None = sm.resolve(subj, dev_b)
314
+ if not cmds_a and not cmds_b:
315
+ rows.append(
316
+ (
317
+ subj,
318
+ None,
319
+ f"Sequence '{subj}' not found for {label_pair}",
320
+ )
321
+ )
322
+ else:
323
+ base_list = cmds_a or cmds_b or []
324
+ with (
325
+ DeviceSession(dev_a, config) as sa,
326
+ DeviceSession(dev_b, config) as sb,
327
+ ):
328
+ for cmd in base_list:
329
+ curr_a = sa.execute_command(cmd)
330
+ curr_b = sb.execute_command(cmd)
331
+ _save_current_artifact(dev_a, cmd, curr_a)
332
+ _save_current_artifact(dev_b, cmd, curr_b)
333
+ outcome = _diff_texts(
334
+ baseline_text=curr_a,
335
+ current_text=curr_b,
336
+ baseline_label=f"{dev_a}:{cmd}",
337
+ current_label=f"{dev_b}:{cmd}",
338
+ ignore_patterns=ignore or [],
339
+ )
340
+ rows.append((cmd, outcome, ""))
341
+
342
+ per_device_reports.append((label_pair, rows))
343
+ total_changed = sum(int(r[1].changed) for r in rows if r[1] is not None)
344
+ total_missing = sum(1 for r in rows if r[1] is None)
345
+
346
+ elif is_config:
347
+ if baseline is None:
348
+ ctx.print_error(
349
+ "--baseline FILE is required for 'config' diffs when "
350
+ "not comparing two devices."
351
+ )
352
+ raise typer.Exit(2)
353
+
354
+ for dev in devices:
355
+ with DeviceSession(dev, config) as session:
356
+ current = session.execute_command("/export compact")
357
+ _save_current_artifact(dev, "export_compact", current)
358
+ base_text = _read_text(baseline)
359
+ outcome = _diff_texts(
360
+ baseline_text=base_text,
361
+ current_text=current,
362
+ baseline_label=str(baseline),
363
+ current_label=f"{dev}:/export compact",
364
+ ignore_patterns=ignore or [],
365
+ )
366
+ per_device_reports.append((dev, [("config", outcome, "")]))
367
+ total_changed += int(outcome.changed)
368
+
369
+ elif is_command:
370
+ if baseline is None:
371
+ ctx.print_error(
372
+ "--baseline FILE is required for single-device command "
373
+ "diffs. Use two devices (comma-separated) to diff "
374
+ "device-to-device."
375
+ )
376
+ raise typer.Exit(2)
377
+ for dev in devices:
378
+ with DeviceSession(dev, config) as session:
379
+ current = session.execute_command(subj)
380
+ _save_current_artifact(dev, subj, current)
381
+ base_text = _read_text(baseline)
382
+ outcome = _diff_texts(
383
+ baseline_text=base_text,
384
+ current_text=current,
385
+ baseline_label=str(baseline),
386
+ current_label=f"{dev}:{subj}",
387
+ ignore_patterns=ignore or [],
388
+ )
389
+ per_device_reports.append((dev, [(subj, outcome, "")]))
390
+ total_changed += int(outcome.changed)
391
+
392
+ else: # sequence
393
+ if baseline is None:
394
+ ctx.print_error(
395
+ "--baseline DIR is required for single-device sequence "
396
+ "diffs. Use two devices (comma-separated) to diff "
397
+ "device-to-device."
398
+ )
399
+ raise typer.Exit(2)
400
+ if not baseline.exists() or not baseline.is_dir():
401
+ ctx.print_error("Baseline must be an existing directory.")
402
+ raise typer.Exit(2)
403
+
404
+ for dev in devices:
405
+ commands: list[str] | None = sm.resolve(subj, dev)
406
+ if not commands:
407
+ per_device_reports.append(
408
+ (
409
+ dev,
410
+ [
411
+ (
412
+ subj,
413
+ None,
414
+ f"Sequence '{subj}' not found for device",
415
+ )
416
+ ],
417
+ )
418
+ )
419
+ total_missing += 1
420
+ continue
421
+
422
+ report_rows: list[tuple[str, DiffOutcome | None, str]] = []
423
+ with DeviceSession(dev, config) as session:
424
+ for cmd in commands:
425
+ current = session.execute_command(cmd)
426
+ _save_current_artifact(dev, cmd, current)
427
+ base_file = _find_baseline_file_for_command(baseline, cmd)
428
+ if not base_file:
429
+ note = (
430
+ f"No baseline file found for command: {cmd} "
431
+ f"(expected like 'cmd_"
432
+ f"{_sanitize_filename(cmd)}.txt')"
433
+ )
434
+ report_rows.append((cmd, None, note))
435
+ total_missing += 1
436
+ continue
437
+
438
+ base_text = _read_text(base_file)
439
+ outcome = _diff_texts(
440
+ baseline_text=base_text,
441
+ current_text=current,
442
+ baseline_label=str(base_file),
443
+ current_label=f"{dev}:{cmd}",
444
+ ignore_patterns=ignore or [],
445
+ )
446
+ report_rows.append((cmd, outcome, ""))
447
+ total_changed += int(outcome.changed)
448
+
449
+ per_device_reports.append((dev, report_rows))
450
+
451
+ # Render report and optionally store
452
+ any_diffs = total_changed > 0 or total_missing > 0
453
+
454
+ for dev, rows in per_device_reports:
455
+ ctx.print_info(f"Device: {dev}")
456
+ for name, res, note in rows:
457
+ if res is None:
458
+ ctx.print_warning(f"- {name}: {note}")
459
+ elif not res.changed:
460
+ ctx.print_success(f"- {name}: no changes")
461
+ else:
462
+ ctx.print_error(f"- {name}: differences")
463
+ if res.output:
464
+ ctx.output.print_output(res.output)
465
+
466
+ if results_mgr.store_results and results_mgr.session_dir:
467
+ # Store diff output as a command result for visibility
468
+ results_mgr.store_command_result(
469
+ dev, f"DIFF {name}", res.output or "(no diff)"
470
+ )
471
+
472
+ ctx.output.print_separator()
473
+
474
+ if any_diffs:
475
+ ctx.print_info(
476
+ f"Summary: diffs={total_changed}, missing_baseline={total_missing}"
477
+ )
478
+ raise typer.Exit(1)
479
+ else:
480
+ ctx.print_success("No differences detected.")
481
+ raise typer.Exit(0)
482
+
483
+ except NetworkToolkitError as e: # pragma: no cover - error path
484
+ ctx.print_error(str(e))
485
+ raise typer.Exit(1) from None
@@ -0,0 +1,197 @@
1
+ # SPDX-License-Identifier: MIT
2
+ """`nw download` command implementation."""
3
+
4
+ from __future__ import annotations
5
+
6
+ from importlib import import_module
7
+ from pathlib import Path
8
+ from typing import Annotated, Any, cast
9
+
10
+ import typer
11
+
12
+ from network_toolkit.common.command_helpers import CommandContext
13
+ from network_toolkit.common.defaults import DEFAULT_CONFIG_PATH
14
+ from network_toolkit.common.logging import setup_logging
15
+ from network_toolkit.config import load_config
16
+ from network_toolkit.exceptions import NetworkToolkitError
17
+
18
+
19
+ def register(app: typer.Typer) -> None:
20
+ @app.command(rich_help_panel="Remote Operations")
21
+ def download( # pyright: ignore[reportUnusedFunction]
22
+ target_name: Annotated[
23
+ str,
24
+ typer.Argument(
25
+ help="Device or group name from configuration",
26
+ metavar="<device|group>",
27
+ ),
28
+ ],
29
+ remote_file: Annotated[
30
+ str, typer.Argument(help="Remote filename on the device (e.g. export.rsc)")
31
+ ],
32
+ local_path: Annotated[
33
+ Path,
34
+ typer.Argument(
35
+ help=(
36
+ "Destination path. For groups, treated as a directory and files "
37
+ "are saved under <local_path>/<device>/<remote_file>"
38
+ )
39
+ ),
40
+ ],
41
+ *,
42
+ delete_remote: Annotated[
43
+ bool,
44
+ typer.Option(
45
+ "--delete-remote/--keep-remote",
46
+ help="Delete remote file after successful download",
47
+ ),
48
+ ] = False,
49
+ verify_download: Annotated[
50
+ bool,
51
+ typer.Option(
52
+ "--verify/--no-verify",
53
+ help="Verify download by comparing file sizes",
54
+ ),
55
+ ] = True,
56
+ config_file: Annotated[
57
+ Path, typer.Option("--config", "-c", help="Configuration file path")
58
+ ] = DEFAULT_CONFIG_PATH,
59
+ verbose: Annotated[
60
+ bool, typer.Option("--verbose", "-v", help="Enable verbose output")
61
+ ] = False,
62
+ ) -> None:
63
+ """Download a file from a device or all devices in a group."""
64
+ setup_logging("DEBUG" if verbose else "INFO")
65
+
66
+ # ACTION command - use global config theme
67
+ ctx = CommandContext(
68
+ config_file=config_file,
69
+ verbose=verbose,
70
+ output_mode=None, # Use global config theme
71
+ )
72
+
73
+ try:
74
+ config = load_config(config_file)
75
+
76
+ # Resolve DeviceSession from cli to preserve test patching path
77
+ module = import_module("network_toolkit.cli")
78
+ device_session = cast(Any, module).DeviceSession
79
+
80
+ devices = config.devices or {}
81
+ groups = config.device_groups or {}
82
+ is_device = target_name in devices
83
+ is_group = target_name in groups
84
+
85
+ if not (is_device or is_group):
86
+ ctx.print_error(
87
+ f"'{target_name}' not found as device or group in configuration"
88
+ )
89
+ raise typer.Exit(1)
90
+
91
+ if is_device:
92
+ # Show summary
93
+ transport_type = config.get_transport_type(target_name)
94
+ ctx.print_info("File Download Details:")
95
+ ctx.print_detail_line("Device", target_name)
96
+ ctx.print_detail_line("Transport", transport_type)
97
+ ctx.print_detail_line("Remote file", remote_file)
98
+ ctx.print_detail_line("Local path", str(local_path))
99
+ ctx.print_detail_line(
100
+ "Delete remote after download", "Yes" if delete_remote else "No"
101
+ )
102
+ ctx.print_detail_line(
103
+ "Verify download", "Yes" if verify_download else "No"
104
+ )
105
+ ctx.print_blank_line()
106
+
107
+ with ctx.output_manager.status(
108
+ f"Downloading {remote_file} from {target_name}..."
109
+ ):
110
+ with device_session(target_name, config) as session:
111
+ success = session.download_file(
112
+ remote_filename=remote_file,
113
+ local_path=local_path,
114
+ delete_remote=delete_remote,
115
+ verify_download=verify_download,
116
+ )
117
+
118
+ if success:
119
+ ctx.print_success("Download successful!")
120
+ ctx.print_success(
121
+ f"File '{remote_file}' downloaded to '{local_path}'"
122
+ )
123
+ else:
124
+ ctx.print_error("Download failed!")
125
+ raise typer.Exit(1)
126
+ return
127
+
128
+ # Group path
129
+ try:
130
+ members: list[str] = config.get_group_members(target_name)
131
+ except Exception:
132
+ group_obj = groups.get(target_name)
133
+ members = group_obj.members if group_obj and group_obj.members else []
134
+
135
+ if not members:
136
+ ctx.print_error(f"No devices found in group '{target_name}'")
137
+ raise typer.Exit(1)
138
+
139
+ ctx.print_info("Group File Download Details:")
140
+ ctx.print_detail_line("Group", target_name)
141
+ ctx.print_detail_line("Devices", str(len(members)))
142
+ ctx.print_detail_line("Remote file", remote_file)
143
+ ctx.print_detail_line(
144
+ "Base path",
145
+ f"{local_path} (files saved under <base>/<device>/{remote_file})",
146
+ )
147
+ ctx.print_detail_line(
148
+ "Delete remote after download", "Yes" if delete_remote else "No"
149
+ )
150
+ ctx.print_detail_line("Verify download", "Yes" if verify_download else "No")
151
+ ctx.print_blank_line()
152
+
153
+ successes = 0
154
+ results: dict[str, bool] = {}
155
+
156
+ for dev in members:
157
+ dest = (local_path / dev / remote_file).resolve()
158
+ with ctx.output_manager.status(
159
+ f"Downloading {remote_file} from {dev}..."
160
+ ):
161
+ try:
162
+ with device_session(dev, config) as session:
163
+ ok = session.download_file(
164
+ remote_filename=remote_file,
165
+ local_path=dest,
166
+ delete_remote=delete_remote,
167
+ verify_download=verify_download,
168
+ )
169
+ results[dev] = ok
170
+ if ok:
171
+ successes += 1
172
+ ctx.print_success(f"OK {dev}: downloaded to {dest}")
173
+ else:
174
+ ctx.print_error(f"FAIL {dev}: download failed")
175
+ except Exception as e: # pragma: no cover - unexpected
176
+ results[dev] = False
177
+ ctx.print_error(f"FAIL {dev}: error during download: {e}")
178
+
179
+ total = len(members)
180
+ ctx.print_info("Group Download Results:")
181
+ ctx.print_success(f" Successful: {successes}/{total}")
182
+ ctx.print_error(f" Failed: {total - successes}/{total}")
183
+
184
+ if successes < total:
185
+ raise typer.Exit(1)
186
+
187
+ except NetworkToolkitError as e:
188
+ ctx.print_error(f"Error: {e.message}")
189
+ if verbose and getattr(e, "details", None):
190
+ ctx.print_error(f"Details: {e.details}")
191
+ raise typer.Exit(1) from None
192
+ except typer.Exit:
193
+ # Allow clean exits (e.g., user cancellation) to pass through
194
+ raise
195
+ except Exception as e: # pragma: no cover - unexpected
196
+ ctx.print_error(f"Unexpected error: {e}")
197
+ raise typer.Exit(1) from None