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,441 @@
1
+ """Unified backup command for network_toolkit."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from importlib import import_module
6
+ from pathlib import Path
7
+ from typing import Annotated, Any, cast
8
+
9
+ import typer
10
+
11
+ from network_toolkit.common.command_helpers import CommandContext
12
+ from network_toolkit.common.defaults import DEFAULT_CONFIG_PATH
13
+ from network_toolkit.common.logging import setup_logging
14
+ from network_toolkit.config import NetworkConfig, load_config
15
+ from network_toolkit.exceptions import NetworkToolkitError
16
+ from network_toolkit.platforms import (
17
+ UnsupportedOperationError,
18
+ check_operation_support,
19
+ get_platform_operations,
20
+ )
21
+
22
+ MAX_LIST_PREVIEW = 10
23
+
24
+ # Create a sub-app for backup commands
25
+ backup_app = typer.Typer(
26
+ name="backup",
27
+ help="Backup operations for network devices",
28
+ context_settings={"help_option_names": ["-h", "--help"]},
29
+ )
30
+
31
+
32
+ @backup_app.command("config")
33
+ def config_backup(
34
+ target_name: Annotated[str, typer.Argument(help="Device or group name")],
35
+ download: Annotated[
36
+ bool,
37
+ typer.Option(
38
+ "--download/--no-download",
39
+ help="Download created backup/export files after running the sequence",
40
+ ),
41
+ ] = True,
42
+ delete_remote: Annotated[
43
+ bool,
44
+ typer.Option(
45
+ "--delete-remote/--keep-remote",
46
+ help="Delete remote backup/export files after successful download",
47
+ ),
48
+ ] = False,
49
+ config_file: Annotated[
50
+ Path, typer.Option("--config", "-c", help="Configuration file path")
51
+ ] = DEFAULT_CONFIG_PATH,
52
+ verbose: Annotated[
53
+ bool, typer.Option("--verbose", "-v", help="Enable verbose output")
54
+ ] = False,
55
+ ) -> None:
56
+ """Backup device configuration.
57
+
58
+ Performs a configuration backup for the specified device or group.
59
+ """
60
+ setup_logging("DEBUG" if verbose else "INFO")
61
+ ctx = CommandContext(
62
+ output_mode=None, # Use global config theme
63
+ verbose=verbose,
64
+ config_file=config_file,
65
+ )
66
+
67
+ try:
68
+ config = load_config(config_file)
69
+
70
+ # Resolve DeviceSession from cli to preserve tests patching path
71
+ module = import_module("network_toolkit.cli")
72
+ device_session = cast(Any, module).DeviceSession
73
+ handle_downloads = cast(Any, module)._handle_file_downloads
74
+
75
+ devices = config.devices or {}
76
+ groups = config.device_groups or {}
77
+ is_device = target_name in devices
78
+ is_group = target_name in groups
79
+
80
+ if not (is_device or is_group):
81
+ ctx.output_manager.print_error(
82
+ f"'{target_name}' not found as device or group in configuration"
83
+ )
84
+ if devices:
85
+ dev_names = sorted(devices.keys())
86
+ preview = ", ".join(dev_names[:MAX_LIST_PREVIEW])
87
+ if len(dev_names) > MAX_LIST_PREVIEW:
88
+ preview += " ..."
89
+ ctx.print_info("Known devices: " + preview)
90
+ if groups:
91
+ grp_names = sorted(groups.keys())
92
+ preview = ", ".join(grp_names[:MAX_LIST_PREVIEW])
93
+ if len(grp_names) > MAX_LIST_PREVIEW:
94
+ preview += " ..."
95
+ ctx.print_info("Known groups: " + preview)
96
+ raise typer.Exit(1)
97
+
98
+ def resolve_backup_sequence(
99
+ config: NetworkConfig, device_name: str
100
+ ) -> list[str]:
101
+ """Resolve the backup sequence for a device."""
102
+ seq_name = "backup_config"
103
+ devices = config.devices or {}
104
+ device_config = devices.get(device_name)
105
+
106
+ # Try device-specific sequences first
107
+ if (
108
+ device_config
109
+ and device_config.command_sequences
110
+ and seq_name in device_config.command_sequences
111
+ ):
112
+ return device_config.command_sequences[seq_name]
113
+
114
+ # Fall back to global sequences
115
+ if (
116
+ config.global_command_sequences
117
+ and seq_name in config.global_command_sequences
118
+ ):
119
+ return config.global_command_sequences[seq_name].commands
120
+
121
+ return []
122
+
123
+ def process_device(dev: str) -> bool:
124
+ try:
125
+ with device_session(dev, config) as session:
126
+ # Get platform-specific operations
127
+ try:
128
+ platform_ops = get_platform_operations(session)
129
+ except UnsupportedOperationError as e:
130
+ ctx.print_error(f"Error on {dev}: {e}")
131
+ return False
132
+
133
+ # Resolve backup sequence (device-specific or global)
134
+ seq_cmds = resolve_backup_sequence(config, dev)
135
+ if not seq_cmds:
136
+ ctx.print_error(
137
+ f"backup sequence 'backup_config' not defined for {dev}"
138
+ )
139
+ return False
140
+
141
+ ctx.print_operation_header("Configuration Backup", dev, "device")
142
+ transport_type = config.get_transport_type(dev)
143
+ platform_name = platform_ops.get_platform_name()
144
+ ctx.print_info(f"Platform: {platform_name}")
145
+ ctx.print_info(f"Transport: {transport_type}")
146
+
147
+ # Use platform-specific backup creation
148
+ backup_success = platform_ops.create_backup(
149
+ backup_sequence=seq_cmds,
150
+ download_files=None, # Will handle downloads separately
151
+ )
152
+
153
+ if not backup_success:
154
+ ctx.print_error(f"Backup creation failed on {dev}")
155
+ return False
156
+
157
+ if download:
158
+ downloads: list[dict[str, Any]] = [
159
+ {
160
+ "remote_file": "nw-backup.backup",
161
+ "local_path": str(config.general.backup_dir),
162
+ "local_filename": ("{device}_{date}_nw.backup"),
163
+ "delete_remote": delete_remote,
164
+ },
165
+ {
166
+ "remote_file": "nw-export.rsc",
167
+ "local_path": str(config.general.backup_dir),
168
+ "local_filename": ("{device}_{date}_nw-export.rsc"),
169
+ "delete_remote": delete_remote,
170
+ },
171
+ ]
172
+ handle_downloads(
173
+ session=session,
174
+ device_name=dev,
175
+ download_files=downloads,
176
+ config=config,
177
+ )
178
+ return True
179
+ except NetworkToolkitError as e:
180
+ ctx.print_error(f"Error on {dev}: {e.message}")
181
+ if verbose and e.details:
182
+ ctx.print_error(f"Details: {e.details}")
183
+ return False
184
+ except Exception as e: # pragma: no cover
185
+ ctx.print_error(f"Unexpected error on {dev}: {e}")
186
+ return False
187
+
188
+ if is_device:
189
+ ok = process_device(target_name)
190
+ if not ok:
191
+ raise typer.Exit(1)
192
+ ctx.print_operation_complete("Backup", success=True)
193
+ return
194
+
195
+ # Group path
196
+ members: list[str] = []
197
+ try:
198
+ members = config.get_group_members(target_name)
199
+ except Exception:
200
+ grp = groups.get(target_name)
201
+ if grp and getattr(grp, "members", None):
202
+ members = grp.members or []
203
+
204
+ if not members:
205
+ ctx.print_error(f"No devices found in group '{target_name}'")
206
+ raise typer.Exit(1)
207
+
208
+ ctx.print_operation_header("Backup", target_name, "group")
209
+ failures = 0
210
+ for dev in members:
211
+ ok = process_device(dev)
212
+ failures += 0 if ok else 1
213
+
214
+ total = len(members)
215
+ ctx.print_info(f"Completed: {total - failures}/{total} successful backups")
216
+ if failures:
217
+ raise typer.Exit(1)
218
+
219
+ except NetworkToolkitError as e:
220
+ ctx.handle_error(e)
221
+ except Exception as e: # pragma: no cover
222
+ ctx.handle_error(e)
223
+
224
+
225
+ @backup_app.command("comprehensive")
226
+ def comprehensive_backup(
227
+ target_name: Annotated[str, typer.Argument(help="Device or group name")],
228
+ download: Annotated[
229
+ bool,
230
+ typer.Option(
231
+ "--download/--no-download",
232
+ help="Download created backup/export files after running the sequence",
233
+ ),
234
+ ] = True,
235
+ delete_remote: Annotated[
236
+ bool,
237
+ typer.Option(
238
+ "--delete-remote/--keep-remote",
239
+ help="Delete remote backup/export files after successful download",
240
+ ),
241
+ ] = False,
242
+ config_file: Annotated[
243
+ Path, typer.Option("--config", "-c", help="Configuration file path")
244
+ ] = DEFAULT_CONFIG_PATH,
245
+ verbose: Annotated[
246
+ bool, typer.Option("--verbose", "-v", help="Enable verbose output")
247
+ ] = False,
248
+ ) -> None:
249
+ """Perform comprehensive backup including vendor-specific data.
250
+
251
+ Performs a comprehensive backup for the specified device or group,
252
+ including vendor-specific configuration and operational data.
253
+ """
254
+ setup_logging("DEBUG" if verbose else "INFO")
255
+ ctx = CommandContext(
256
+ config_file=config_file,
257
+ verbose=verbose,
258
+ output_mode=None, # Use global config theme
259
+ )
260
+
261
+ try:
262
+ config = load_config(config_file)
263
+
264
+ module = import_module("network_toolkit.cli")
265
+ device_session = cast(Any, module).DeviceSession
266
+ handle_downloads = cast(Any, module)._handle_file_downloads
267
+
268
+ devices = config.devices or {}
269
+ groups = config.device_groups or {}
270
+ is_device = target_name in devices
271
+ is_group = target_name in groups
272
+
273
+ if not (is_device or is_group):
274
+ ctx.print_error(
275
+ f"'{target_name}' not found as device or group in configuration"
276
+ )
277
+ if devices:
278
+ dev_names = sorted(devices.keys())
279
+ preview = ", ".join(dev_names[:MAX_LIST_PREVIEW])
280
+ if len(dev_names) > MAX_LIST_PREVIEW:
281
+ preview += " ..."
282
+ ctx.print_info("Known devices: " + preview)
283
+ if groups:
284
+ grp_names = sorted(groups.keys())
285
+ preview = ", ".join(grp_names[:MAX_LIST_PREVIEW])
286
+ if len(grp_names) > MAX_LIST_PREVIEW:
287
+ preview += " ..."
288
+ ctx.print_info("Known groups: " + preview)
289
+ raise typer.Exit(1)
290
+
291
+ def resolve_comprehensive_backup_sequence(
292
+ config: NetworkConfig, device_name: str
293
+ ) -> list[str]:
294
+ """Resolve the comprehensive backup command sequence for a device."""
295
+ devices = config.devices or {}
296
+ dev_cfg = devices.get(device_name)
297
+
298
+ # Device-specific override
299
+ if dev_cfg and dev_cfg.command_sequences:
300
+ seq = dev_cfg.command_sequences.get("backup")
301
+ if seq:
302
+ return list(seq)
303
+
304
+ # Global sequence
305
+ global_seqs = config.global_command_sequences or {}
306
+ if "backup" in global_seqs:
307
+ return list(global_seqs["backup"].commands)
308
+
309
+ return []
310
+
311
+ def process_device(dev: str) -> bool:
312
+ try:
313
+ with device_session(dev, config) as session:
314
+ try:
315
+ platform_ops = get_platform_operations(session)
316
+ except UnsupportedOperationError as e:
317
+ ctx.print_error(f"Error on {dev}: {e}")
318
+ return False
319
+
320
+ seq_cmds = resolve_comprehensive_backup_sequence(config, dev)
321
+ if not seq_cmds:
322
+ ctx.print_error(
323
+ f"backup sequence 'backup' not defined for {dev}"
324
+ )
325
+ return False
326
+
327
+ ctx.print_operation_header("Comprehensive Backup", dev, "device")
328
+ transport_type = config.get_transport_type(dev)
329
+ platform_name = platform_ops.get_platform_name()
330
+ ctx.print_info(f"Platform: {platform_name}")
331
+ ctx.print_info(f"Transport: {transport_type}")
332
+
333
+ backup_success = platform_ops.create_backup(
334
+ backup_sequence=seq_cmds,
335
+ download_files=None, # Will handle downloads separately
336
+ )
337
+
338
+ if not backup_success:
339
+ ctx.print_error(
340
+ f"Comprehensive backup creation failed on {dev}"
341
+ )
342
+ return False
343
+
344
+ if download:
345
+ downloads: list[dict[str, Any]] = [
346
+ {
347
+ "remote_file": "nw-backup.backup",
348
+ "local_path": str(config.general.backup_dir),
349
+ "local_filename": "{device}_{date}_nw.backup",
350
+ "delete_remote": delete_remote,
351
+ },
352
+ {
353
+ "remote_file": "nw-export.rsc",
354
+ "local_path": str(config.general.backup_dir),
355
+ "local_filename": "{device}_{date}_nw-export.rsc",
356
+ "delete_remote": delete_remote,
357
+ },
358
+ ]
359
+ handle_downloads(
360
+ session=session,
361
+ device_name=dev,
362
+ download_files=downloads,
363
+ config=config,
364
+ )
365
+ return True
366
+ except NetworkToolkitError as e:
367
+ ctx.print_error(f"Error on {dev}: {e.message}")
368
+ if verbose and e.details:
369
+ ctx.print_error(f"Details: {e.details}")
370
+ return False
371
+ except Exception as e: # pragma: no cover
372
+ ctx.print_error(f"Unexpected error on {dev}: {e}")
373
+ return False
374
+
375
+ if is_device:
376
+ ok = process_device(target_name)
377
+ if not ok:
378
+ raise typer.Exit(1)
379
+ ctx.print_operation_complete("Comprehensive Backup", success=True)
380
+ return
381
+
382
+ # Group processing
383
+ members: list[str] = []
384
+ try:
385
+ members = config.get_group_members(target_name)
386
+ except Exception:
387
+ grp = groups.get(target_name)
388
+ if grp and getattr(grp, "members", None):
389
+ members = grp.members or []
390
+
391
+ if not members:
392
+ ctx.print_error(f"No devices found in group '{target_name}'")
393
+ raise typer.Exit(1)
394
+
395
+ ctx.print_operation_header("Comprehensive Backup", target_name, "group")
396
+ failures = 0
397
+ for dev in members:
398
+ ok = process_device(dev)
399
+ failures += 0 if ok else 1
400
+
401
+ total = len(members)
402
+ ctx.print_info(f"Completed: {total - failures}/{total} successful backups")
403
+ if failures:
404
+ raise typer.Exit(1)
405
+
406
+ except NetworkToolkitError as e:
407
+ ctx.handle_error(e)
408
+ except Exception as e: # pragma: no cover
409
+ ctx.handle_error(e)
410
+
411
+
412
+ @backup_app.command("vendors")
413
+ def show_vendors() -> None:
414
+ """Show which vendors support backup operations.
415
+
416
+ Lists all supported vendors and their backup operation capabilities.
417
+ """
418
+ from network_toolkit.platforms.factory import get_supported_platforms
419
+
420
+ platforms = get_supported_platforms()
421
+
422
+ ctx = CommandContext()
423
+ ctx.print_info("Vendor backup operation support:")
424
+
425
+ operations = [
426
+ ("config_backup", "Configuration Backup"),
427
+ ("create_backup", "Comprehensive Backup"),
428
+ ]
429
+
430
+ for device_type, vendor_name in platforms.items():
431
+ ctx.print_info(f"\n{vendor_name} ({device_type}):")
432
+
433
+ for op_name, op_display in operations:
434
+ supported, _ = check_operation_support(device_type, op_name)
435
+ status = "✓ Supported" if supported else "✗ Not supported"
436
+ ctx.print_info(f" {op_display}: {status}")
437
+
438
+
439
+ def register(app: typer.Typer) -> None:
440
+ """Register the unified backup command with the main CLI app."""
441
+ app.add_typer(backup_app, rich_help_panel="Vendor-Specific Remote Operations")
@@ -0,0 +1,172 @@
1
+ """Hidden completion helper for dynamic shell completions.
2
+
3
+ This command is intentionally undocumented in user help and prints plain
4
+ newline-separated values for use by completion scripts (bash/zsh/fish).
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from pathlib import Path
10
+ from typing import Annotated
11
+
12
+ import typer
13
+
14
+ from network_toolkit.common.defaults import DEFAULT_CONFIG_PATH
15
+ from network_toolkit.config import NetworkConfig, load_config
16
+ from network_toolkit.sequence_manager import SequenceManager
17
+
18
+
19
+ def _list_commands() -> list[str]:
20
+ """Return top-level command names exposed by the CLI.
21
+
22
+ Keep this in sync with registrations in cli.py. We avoid importing the app
23
+ object to prevent circular imports.
24
+ """
25
+ return [
26
+ "info",
27
+ "run",
28
+ "upload",
29
+ "download",
30
+ "backup",
31
+ "firmware",
32
+ "ssh",
33
+ "diff",
34
+ "list",
35
+ "config",
36
+ "schema",
37
+ "complete",
38
+ ]
39
+
40
+
41
+ def _list_devices(config: NetworkConfig) -> list[str]:
42
+ return list(config.devices.keys()) if config.devices else []
43
+
44
+
45
+ def _list_groups(config: NetworkConfig) -> list[str]:
46
+ return list(config.device_groups.keys()) if config.device_groups else []
47
+
48
+
49
+ def _list_sequence_groups(config: NetworkConfig) -> list[str]:
50
+ return (
51
+ list(config.command_sequence_groups.keys())
52
+ if config.command_sequence_groups
53
+ else []
54
+ )
55
+
56
+
57
+ def _list_tags(config: NetworkConfig) -> list[str]:
58
+ tags: set[str] = set()
59
+ if config.devices:
60
+ for device in config.devices.values():
61
+ if device.tags:
62
+ tags.update(device.tags)
63
+ return sorted(tags)
64
+
65
+
66
+ def _list_sequences(config: NetworkConfig, *, target: str | None) -> list[str]:
67
+ names: set[str] = set()
68
+
69
+ # Global sequences
70
+ if config.global_command_sequences:
71
+ names.update(config.global_command_sequences.keys())
72
+
73
+ # Device-specific sequences (either for a specific device/group or across all)
74
+ if config.devices:
75
+ if target and target in config.devices:
76
+ dev = config.devices[target]
77
+ if dev.command_sequences:
78
+ names.update(dev.command_sequences.keys())
79
+ elif (
80
+ target
81
+ and getattr(config, "device_groups", None)
82
+ and (config.device_groups is not None and target in config.device_groups)
83
+ ):
84
+ # Include device-defined sequences from all devices in the group
85
+ for dev_name in config.get_group_members(target):
86
+ dev2 = config.devices.get(dev_name)
87
+ if dev2 and dev2.command_sequences:
88
+ names.update(dev2.command_sequences.keys())
89
+ else:
90
+ for dev in config.devices.values():
91
+ if dev.command_sequences:
92
+ names.update(dev.command_sequences.keys())
93
+
94
+ # Vendor/user sequences via SequenceManager if we have a target context
95
+ sm = SequenceManager(config)
96
+ if target and config.devices:
97
+ if target in config.devices:
98
+ # Single device: include its vendor sequences
99
+ platform = config.devices[target].device_type
100
+ vendor = sm.list_vendor_sequences(platform)
101
+ names.update(vendor.keys())
102
+ elif getattr(config, "device_groups", None) and (
103
+ config.device_groups is not None and target in config.device_groups
104
+ ):
105
+ # Group: union sequences across all vendors in the group
106
+ platforms: set[str] = set()
107
+ for dev_name in config.get_group_members(target):
108
+ dev3 = config.devices.get(dev_name)
109
+ if dev3 and dev3.device_type:
110
+ platforms.add(dev3.device_type)
111
+ for plat in platforms:
112
+ vendor_map = sm.list_vendor_sequences(plat)
113
+ names.update(vendor_map.keys())
114
+
115
+ return sorted(names)
116
+
117
+
118
+ def register(app: typer.Typer) -> None:
119
+ @app.command("__complete", hidden=True)
120
+ def __complete(
121
+ for_: Annotated[
122
+ str,
123
+ typer.Option(
124
+ "--for",
125
+ "-f",
126
+ help=(
127
+ "Completion target: commands|devices|groups|sequences|"
128
+ "sequence-groups|tags"
129
+ ),
130
+ ),
131
+ ],
132
+ config_file: Annotated[
133
+ Path, typer.Option("--config", "-c", help="Configuration file path")
134
+ ] = DEFAULT_CONFIG_PATH,
135
+ device: Annotated[
136
+ str | None,
137
+ typer.Option(
138
+ "--device",
139
+ "-d",
140
+ help=(
141
+ "Optional target context (device or group) to improve sequence "
142
+ "suggestions by including vendor and device-defined sequences"
143
+ ),
144
+ ),
145
+ ] = None,
146
+ ) -> None:
147
+ """Print completion candidates for the requested category."""
148
+ try:
149
+ # Only load config when not completing top-level commands
150
+ if for_ == "commands":
151
+ items = _list_commands()
152
+ else:
153
+ cfg = load_config(config_file)
154
+ if for_ == "devices":
155
+ items = _list_devices(cfg)
156
+ elif for_ == "groups":
157
+ items = _list_groups(cfg)
158
+ elif for_ == "sequences":
159
+ items = _list_sequences(cfg, target=device)
160
+ elif for_ == "sequence-groups":
161
+ items = _list_sequence_groups(cfg)
162
+ elif for_ == "tags":
163
+ items = _list_tags(cfg)
164
+ else:
165
+ items = []
166
+
167
+ for item in items:
168
+ # Plain newline-delimited output; no styles
169
+ typer.echo(item)
170
+ except Exception as _exc:
171
+ # On error, return no suggestions to avoid noisy completion
172
+ raise typer.Exit(0) from None