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,1068 @@
1
+ """Unified config commands for the network toolkit CLI."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import logging
6
+ import os
7
+ import shutil
8
+ from pathlib import Path
9
+ from typing import Annotated, cast
10
+
11
+ import typer
12
+
13
+ from network_toolkit.common.command_helpers import CommandContext
14
+ from network_toolkit.common.defaults import DEFAULT_CONFIG_PATH
15
+ from network_toolkit.common.logging import setup_logging
16
+ from network_toolkit.common.output import (
17
+ OutputMode,
18
+ get_output_manager,
19
+ get_output_manager_with_config,
20
+ set_output_mode,
21
+ )
22
+ from network_toolkit.common.paths import default_config_root, default_modular_config_dir
23
+ from network_toolkit.config import load_config
24
+ from network_toolkit.exceptions import (
25
+ ConfigurationError,
26
+ FileTransferError,
27
+ NetworkToolkitError,
28
+ )
29
+
30
+ logger = logging.getLogger(__name__)
31
+
32
+
33
+ def _discover_config_metadata(original: Path) -> dict[str, object]:
34
+ """Discover where config was loaded from and which files are involved.
35
+
36
+ Mirrors the resolution logic in `load_config` to report:
37
+ - mode: "modular" or "legacy"
38
+ - root: Path of the modular root directory or the legacy file path
39
+ - files: list[Path] of relevant files that were validated
40
+ - display_name: user-facing name for the target (keep "config" when used)
41
+ """
42
+ # Keep the provided token for display (we want to show just "config" when used)
43
+ display_name = str(original)
44
+ path = Path(original)
45
+
46
+ # Helper: collect existing files under a directory with a stable, readable order
47
+ def collect_modular_files(root: Path) -> list[Path]:
48
+ files: list[Path] = []
49
+ for name in ("config.yml", "devices.yml", "groups.yml", "sequences.yml"):
50
+ p = root / name
51
+ if p.exists():
52
+ files.append(p)
53
+ # Include nested directories if present
54
+ for sub in ("devices", "groups", "sequences"):
55
+ d = root / sub
56
+ if d.exists() and d.is_dir():
57
+ # Collect YAML & CSV fragments, sorted for stable output
58
+ for ext in ("*.yml", "*.yaml", "*.csv"):
59
+ files.extend(sorted(d.rglob(ext)))
60
+ return files
61
+
62
+ # Resolution logic (aligned with config.load_config)
63
+ # 1) Explicit "config" directory
64
+ if path.name in ["config", "config/"] and path.exists():
65
+ root = path
66
+ return {
67
+ "mode": "modular",
68
+ "root": root.resolve(),
69
+ "files": collect_modular_files(root),
70
+ "display_name": display_name,
71
+ }
72
+
73
+ # 2) Directory input with direct modular files
74
+ if path.exists() and path.is_dir():
75
+ direct_cfg = path / "config.yml"
76
+ direct_dev = path / "devices.yml"
77
+ if direct_cfg.exists() and direct_dev.exists():
78
+ root = path
79
+ return {
80
+ "mode": "modular",
81
+ "root": root.resolve(),
82
+ "files": collect_modular_files(root),
83
+ "display_name": display_name,
84
+ }
85
+ # Nested config directory next to provided path
86
+ cfg_dir = path / "config"
87
+ if cfg_dir.exists():
88
+ root = cfg_dir
89
+ return {
90
+ "mode": "modular",
91
+ "root": root.resolve(),
92
+ "files": collect_modular_files(root),
93
+ "display_name": display_name,
94
+ }
95
+
96
+ # 3) Legacy file directly
97
+ if path.exists() and path.is_file():
98
+ return {
99
+ "mode": "legacy",
100
+ "root": path.resolve(),
101
+ "files": [path.resolve()],
102
+ "display_name": display_name,
103
+ }
104
+
105
+ # 4) Fallbacks for default names (platform/user cwd)
106
+ if str(path) in ["config", "devices.yml"]:
107
+ # Prefer platform default modular directory
108
+ platform_default = default_modular_config_dir()
109
+ cfg_yaml = platform_default / "config.yml"
110
+ if cfg_yaml.exists():
111
+ root = platform_default
112
+ return {
113
+ "mode": "modular",
114
+ "root": root.resolve(),
115
+ "files": collect_modular_files(root),
116
+ "display_name": display_name,
117
+ }
118
+
119
+ # Current working directory fallbacks
120
+ cwd_cfg_yaml = Path("config/config.yml")
121
+ if cwd_cfg_yaml.exists():
122
+ root = cwd_cfg_yaml.parent
123
+ return {
124
+ "mode": "modular",
125
+ "root": root.resolve(),
126
+ "files": collect_modular_files(root),
127
+ "display_name": display_name,
128
+ }
129
+
130
+ cwd_legacy = Path("devices.yml")
131
+ if cwd_legacy.exists():
132
+ return {
133
+ "mode": "legacy",
134
+ "root": cwd_legacy.resolve(),
135
+ "files": [cwd_legacy.resolve()],
136
+ "display_name": display_name,
137
+ }
138
+
139
+ # 5) Final attempt similar to load_config last check
140
+ platform_default = default_modular_config_dir()
141
+ if (platform_default / "config.yml").exists():
142
+ root = platform_default
143
+ return {
144
+ "mode": "modular",
145
+ "root": root.resolve(),
146
+ "files": collect_modular_files(root),
147
+ "display_name": display_name,
148
+ }
149
+
150
+ # Unknown — return best-effort with the original path
151
+ return {
152
+ "mode": "unknown",
153
+ "root": path.resolve(),
154
+ "files": [],
155
+ "display_name": display_name,
156
+ }
157
+
158
+
159
+ def create_env_file(target_dir: Path) -> None:
160
+ """Create a minimal .env file with credential templates."""
161
+ env_content = """# Network Toolkit Environment Variables
162
+ # =================================
163
+
164
+ # Default credentials (used when device-specific ones aren't found)
165
+ NW_USER_DEFAULT=admin
166
+ NW_PASSWORD_DEFAULT=your_password_here
167
+
168
+ # Device-specific credentials (optional)
169
+ # NW_ROUTER1_USER=admin
170
+ # NW_ROUTER1_PASSWORD=specific_password
171
+
172
+ # Global settings
173
+ # NW_TIMEOUT=30
174
+ # NW_LOG_LEVEL=INFO
175
+ """
176
+ env_file = target_dir / ".env"
177
+ env_file.write_text(env_content)
178
+
179
+
180
+ def create_config_yml(config_dir: Path) -> None:
181
+ """Create the main config.yml file."""
182
+ config_content = """# Network Toolkit Configuration
183
+ # =============================
184
+
185
+ general:
186
+ output_mode: default # Options: default, light, dark, no-color, raw
187
+ log_level: INFO # Options: DEBUG, INFO, WARNING, ERROR
188
+
189
+ # Default transport for all devices (can be overridden per device)
190
+ transport: system # Options: system, paramiko, ssh
191
+
192
+ # Device configurations are loaded from devices/ directory
193
+ # Group configurations are loaded from groups/ directory
194
+ # Sequence configurations are loaded from sequences/ directory
195
+ """
196
+ config_file = config_dir / "config.yml"
197
+ config_file.write_text(config_content)
198
+
199
+
200
+ def create_example_devices(devices_dir: Path) -> None:
201
+ """Create example device configurations."""
202
+ devices_dir.mkdir(parents=True, exist_ok=True)
203
+
204
+ devices_content = """# Example Device Configurations
205
+ devices:
206
+ router1:
207
+ host: 192.168.1.1
208
+ device_type: mikrotik_routeros
209
+ platform: tile
210
+ description: "Main office router"
211
+ tags:
212
+ - office
213
+ - critical
214
+
215
+ switch1:
216
+ host: 192.168.1.2
217
+ device_type: cisco_ios
218
+ platform: cisco_ios
219
+ description: "Access switch"
220
+ tags:
221
+ - switch
222
+ - access
223
+ """
224
+
225
+ (devices_dir / "devices.yml").write_text(devices_content)
226
+
227
+
228
+ def create_example_groups(groups_dir: Path) -> None:
229
+ """Create example group configurations."""
230
+ groups_dir.mkdir(parents=True, exist_ok=True)
231
+
232
+ groups_content = """# Example Group Configurations
233
+ groups:
234
+ office:
235
+ description: "All office network devices"
236
+ match_tags:
237
+ - office
238
+
239
+ critical:
240
+ description: "Critical network infrastructure"
241
+ match_tags:
242
+ - critical
243
+ """
244
+
245
+ (groups_dir / "groups.yml").write_text(groups_content)
246
+
247
+
248
+ def create_example_sequences(sequences_dir: Path) -> None:
249
+ """Create example sequence configurations."""
250
+ sequences_dir.mkdir(parents=True, exist_ok=True)
251
+
252
+ sequences_content = """# Example Command Sequences
253
+ sequences:
254
+ health_check:
255
+ description: "Basic device health check"
256
+ commands:
257
+ - "/system resource print"
258
+ - "/interface print brief"
259
+
260
+ backup_config:
261
+ description: "Backup device configuration"
262
+ commands:
263
+ - "/export file=backup"
264
+ """
265
+
266
+ (sequences_dir / "sequences.yml").write_text(sequences_content)
267
+
268
+ # Create vendor-specific directories
269
+ (sequences_dir / "mikrotik").mkdir(exist_ok=True)
270
+ (sequences_dir / "cisco").mkdir(exist_ok=True)
271
+
272
+ # Create vendor-specific sequences
273
+ mikrotik_content = """# MikroTik RouterOS Sequences
274
+ system_info:
275
+ description: "System information and status"
276
+ commands:
277
+ - "/system resource print"
278
+ - "/system identity print"
279
+ - "/system clock print"
280
+
281
+ interface_status:
282
+ description: "Interface status and configuration"
283
+ commands:
284
+ - "/interface print brief"
285
+ - "/ip address print"
286
+ """
287
+
288
+ cisco_content = """# Cisco IOS Sequences
289
+ system_info:
290
+ description: "System information and status"
291
+ commands:
292
+ - "show version"
293
+ - "show running-config | include hostname"
294
+ - "show clock"
295
+
296
+ interface_status:
297
+ description: "Interface status and configuration"
298
+ commands:
299
+ - "show ip interface brief"
300
+ - "show interface status"
301
+ """
302
+
303
+ (sequences_dir / "mikrotik" / "system.yml").write_text(mikrotik_content)
304
+ (sequences_dir / "cisco" / "system.yml").write_text(cisco_content)
305
+
306
+
307
+ def _validate_git_url(url: str) -> None:
308
+ """Validate Git URL for security."""
309
+ if not url:
310
+ msg = "Git URL cannot be empty"
311
+ raise ConfigurationError(msg)
312
+
313
+ if not url.startswith(("https://", "git@")):
314
+ msg = "Git URL must use HTTPS or SSH protocol"
315
+ raise ConfigurationError(msg)
316
+
317
+ # Block localhost and private IPs for security
318
+ if any(
319
+ pattern in url.lower()
320
+ for pattern in ["localhost", "127.", "192.168.", "10.", "172."]
321
+ ):
322
+ msg = "Private IP addresses not allowed in Git URLs"
323
+ raise ConfigurationError(msg)
324
+
325
+
326
+ def _find_git_executable() -> str:
327
+ """Find git executable with full path for security."""
328
+ import shutil as sh
329
+
330
+ git_path = sh.which("git")
331
+ if not git_path:
332
+ msg = "Git executable not found in PATH"
333
+ raise ConfigurationError(msg)
334
+ return git_path
335
+
336
+
337
+ def _detect_repo_root() -> Path | None:
338
+ """Detect the repository root directory (development mode only)."""
339
+ # Look for a .git folder upwards as a strong signal
340
+ here = Path(__file__).resolve()
341
+ for parent in [here, *here.parents]:
342
+ if (parent / ".git").exists() and (parent / "shell_completion").exists():
343
+ return parent
344
+ # Fallback to pyproject presence
345
+ for parent in [here, *here.parents]:
346
+ if (parent / "pyproject.toml").exists() and (
347
+ parent / "shell_completion"
348
+ ).exists():
349
+ return parent
350
+ return None
351
+
352
+
353
+ def detect_shell(shell: str | None = None) -> str | None:
354
+ """Detect the user's shell for completion installation."""
355
+ if shell in {"bash", "zsh"}:
356
+ return shell
357
+ env_shell = os.environ.get("SHELL", "")
358
+ for name in ("bash", "zsh"):
359
+ if name in env_shell:
360
+ return name
361
+ return None
362
+
363
+
364
+ def install_shell_completions(selected: str) -> tuple[Path | None, Path | None]:
365
+ """Install shell completion scripts.
366
+
367
+ Tries packaged resources first, then falls back to repo-root files in dev.
368
+ """
369
+ if selected not in {"bash", "zsh"}:
370
+ msg = "Only bash and zsh shells are supported for completion installation"
371
+ raise ConfigurationError(msg)
372
+
373
+ # Try packaged resources under network_toolkit.shell_completion first
374
+ pkg_src: Path | None = None
375
+ try:
376
+ import importlib.resources as ir
377
+
378
+ if selected == "bash":
379
+ with ir.path(
380
+ "network_toolkit.shell_completion", "bash_completion_nw.sh"
381
+ ) as p:
382
+ pkg_src = p if p.exists() else None
383
+ else:
384
+ with ir.path(
385
+ "network_toolkit.shell_completion", "zsh_completion_nw.zsh"
386
+ ) as p:
387
+ pkg_src = p if p.exists() else None
388
+ except Exception: # pragma: no cover - safety
389
+ pkg_src = None
390
+
391
+ # Fallback to repo-root scripts in development mode
392
+ repo_src: Path | None = None
393
+ repo_root = _detect_repo_root()
394
+ if repo_root:
395
+ sc_dir = repo_root / "shell_completion"
396
+ if selected == "bash":
397
+ cand = sc_dir / "bash_completion_nw.sh"
398
+ else:
399
+ cand = sc_dir / "zsh_completion_netkit.zsh"
400
+ if cand.exists():
401
+ repo_src = cand
402
+
403
+ if not pkg_src and not repo_src:
404
+ logger.warning("Completion scripts not found; skipping")
405
+ return (None, None)
406
+
407
+ try:
408
+ home = Path.home()
409
+ # Pick packaged source first, otherwise repo source
410
+ src = pkg_src or repo_src
411
+ assert src is not None # for type checkers
412
+ if selected == "bash":
413
+ dest = home / ".local" / "share" / "bash-completion" / "completions" / "nw"
414
+ dest.parent.mkdir(parents=True, exist_ok=True)
415
+ shutil.copy2(src, dest)
416
+ return (dest, home / ".bashrc")
417
+ else: # zsh
418
+ dest = home / ".zsh" / "completions" / "_nw"
419
+ dest.parent.mkdir(parents=True, exist_ok=True)
420
+ shutil.copy2(src, dest)
421
+ return (dest, home / ".zshrc")
422
+
423
+ except OSError as e:
424
+ msg = f"Failed to install {selected} completion: {e}"
425
+ raise FileTransferError(msg) from e
426
+
427
+
428
+ def activate_shell_completion(
429
+ shell: str, installed: Path, rc_file: Path | None
430
+ ) -> None:
431
+ """Activate shell completion by updating RC file."""
432
+ if rc_file is None:
433
+ return
434
+
435
+ try:
436
+ begin = "# >>> NW COMPLETION >>>"
437
+ end = "# <<< NW COMPLETION <<<"
438
+ if shell == "bash":
439
+ snippet = f'\n{begin}\n# Networka bash completion\nif [ -f "{installed}" ]; then\n source "{installed}"\nfi\n{end}\n'
440
+ else:
441
+ compdir = installed.parent
442
+ snippet = f"\n{begin}\n# Networka zsh completion\nfpath=({compdir} $fpath)\nautoload -Uz compinit && compinit\n{end}\n"
443
+
444
+ if not rc_file.exists():
445
+ rc_file.write_text(snippet, encoding="utf-8")
446
+ logger.debug(f"Created rc file with completion: {rc_file}")
447
+ return
448
+
449
+ content = rc_file.read_text(encoding="utf-8")
450
+ if begin in content and end in content:
451
+ logger.debug("Completion activation already present in rc; skipping")
452
+ return
453
+
454
+ with rc_file.open("a", encoding="utf-8") as fh:
455
+ fh.write(snippet)
456
+ logger.debug(f"Activated shell completion in: {rc_file}")
457
+
458
+ except OSError as e:
459
+ msg = f"Failed to activate shell completion: {e}"
460
+ raise FileTransferError(msg) from e
461
+
462
+
463
+ def install_sequences_from_repo(url: str, ref: str, dest: Path) -> int:
464
+ """Install sequences from a Git repository.
465
+
466
+ Returns:
467
+ Number of files installed
468
+ """
469
+ import shutil
470
+ import subprocess
471
+ import tempfile
472
+
473
+ _validate_git_url(url)
474
+ git_exe = _find_git_executable()
475
+
476
+ with tempfile.TemporaryDirectory() as tmp_dir:
477
+ tmp_root = Path(tmp_dir) / "repo"
478
+ try:
479
+ subprocess.run(
480
+ [
481
+ git_exe,
482
+ "clone",
483
+ "--depth",
484
+ "1",
485
+ "--branch",
486
+ ref,
487
+ url,
488
+ str(tmp_root),
489
+ ],
490
+ check=True,
491
+ capture_output=True,
492
+ text=True,
493
+ )
494
+
495
+ src = tmp_root / "config" / "sequences"
496
+ if not src.exists():
497
+ logger.debug("No sequences found in repo under config/sequences")
498
+ return 0
499
+
500
+ # Copy sequences to destination
501
+ files_copied = 0
502
+ for item in src.iterdir():
503
+ if item.name.startswith(".git"):
504
+ continue
505
+ target = dest / item.name
506
+ if item.is_dir():
507
+ shutil.copytree(item, target, dirs_exist_ok=True)
508
+ files_copied += 1
509
+ else:
510
+ shutil.copy2(item, target)
511
+ files_copied += 1
512
+
513
+ logger.debug(
514
+ f"Copied {files_copied} sequence files from {url}@{ref} to {dest}"
515
+ )
516
+ return files_copied
517
+
518
+ except subprocess.CalledProcessError as e:
519
+ error_msg = e.stderr if e.stderr else str(e)
520
+ msg = f"Git clone failed: {error_msg}"
521
+ raise FileTransferError(msg) from e
522
+ except OSError as e:
523
+ msg = f"Failed to copy sequences: {e}"
524
+ raise FileTransferError(msg) from e
525
+
526
+
527
+ def install_editor_schemas(
528
+ config_root: Path, git_url: str | None = None, git_ref: str = "main"
529
+ ) -> int:
530
+ """Install JSON schemas and VS Code settings for YAML editor validation.
531
+
532
+ Returns:
533
+ Number of schema files installed
534
+ """
535
+ import json
536
+ import urllib.request
537
+
538
+ try:
539
+ # Create schemas directory
540
+ schemas_dir = config_root / "schemas"
541
+ schemas_dir.mkdir(exist_ok=True)
542
+
543
+ # Schema files to download from GitHub
544
+ schema_files = [
545
+ "network-config.schema.json",
546
+ "device-config.schema.json",
547
+ "groups-config.schema.json",
548
+ ]
549
+
550
+ github_base_url = (
551
+ f"{git_url or 'https://github.com/narrowin/networka.git'}".replace(
552
+ ".git", ""
553
+ )
554
+ + f"/raw/{git_ref}/schemas"
555
+ )
556
+
557
+ # Download each schema file
558
+ files_downloaded = 0
559
+ for schema_file in schema_files:
560
+ try:
561
+ schema_url = f"{github_base_url}/{schema_file}"
562
+ schema_path = schemas_dir / schema_file
563
+
564
+ # Validate URL scheme for security
565
+ if not schema_url.startswith(("http:", "https:")):
566
+ msg = "URL must start with 'http:' or 'https:'"
567
+ raise ValueError(msg)
568
+
569
+ with urllib.request.urlopen(schema_url) as response: # noqa: S310
570
+ schema_content = response.read().decode("utf-8")
571
+ schema_path.write_text(schema_content, encoding="utf-8")
572
+
573
+ logger.debug(f"Downloaded {schema_file}")
574
+ files_downloaded += 1
575
+ except Exception as e:
576
+ logger.debug(f"Failed to download {schema_file}: {e}")
577
+
578
+ # Create VS Code settings for YAML validation
579
+ vscode_dir = config_root / ".vscode"
580
+ vscode_dir.mkdir(exist_ok=True)
581
+
582
+ settings_path = vscode_dir / "settings.json"
583
+ yaml_schema_config = {
584
+ "yaml.schemas": {
585
+ "./schemas/network-config.schema.json": [
586
+ "config/config.yml",
587
+ "devices.yml",
588
+ ],
589
+ "./schemas/device-config.schema.json": [
590
+ "config/devices/*.yml",
591
+ "config/devices.yml",
592
+ ],
593
+ "./schemas/groups-config.schema.json": [
594
+ "config/groups/*.yml",
595
+ "config/groups.yml",
596
+ ],
597
+ }
598
+ }
599
+
600
+ if settings_path.exists():
601
+ try:
602
+ with settings_path.open(encoding="utf-8") as f:
603
+ existing_settings = json.load(f)
604
+ existing_settings.update(yaml_schema_config)
605
+ yaml_schema_config = existing_settings
606
+ except (json.JSONDecodeError, OSError) as e:
607
+ logger.debug(f"Failed to merge existing VS Code settings: {e}")
608
+
609
+ settings_path.write_text(
610
+ json.dumps(yaml_schema_config, indent=2), encoding="utf-8"
611
+ )
612
+
613
+ logger.debug("Configured JSON schemas and VS Code settings")
614
+ return files_downloaded
615
+
616
+ except OSError as e:
617
+ msg = f"Failed to install schemas: {e}"
618
+ raise FileTransferError(msg) from e
619
+
620
+
621
+ def _config_init_impl(
622
+ target_dir: Path | None = None,
623
+ force: bool = False,
624
+ yes: bool = False,
625
+ dry_run: bool = False,
626
+ install_sequences: bool | None = None,
627
+ git_url: str | None = None,
628
+ git_ref: str = "main",
629
+ install_completions: bool | None = None,
630
+ shell: str | None = None,
631
+ activate_completions: bool | None = None,
632
+ install_schemas: bool | None = None,
633
+ verbose: bool = False,
634
+ ) -> None:
635
+ """Implementation logic for config init."""
636
+ # Create command context for consistent output
637
+ ctx = CommandContext()
638
+
639
+ # Determine whether we prompt (interactive) or not
640
+ interactive = target_dir is None and not yes
641
+
642
+ # Resolve target path
643
+ if target_dir is not None:
644
+ target_path = Path(target_dir).expanduser().resolve()
645
+ else:
646
+ default_path = default_config_root()
647
+ if yes:
648
+ target_path = default_path
649
+ else:
650
+ ctx.output_manager.print_text(
651
+ "\nWhere should Networka store its configuration?"
652
+ )
653
+ ctx.print_detail_line("Default", str(default_path))
654
+ user_input = typer.prompt("Location", default=str(default_path))
655
+ target_path = Path(user_input).expanduser().resolve()
656
+
657
+ # Check if configuration already exists and handle force flag
658
+ if target_path.exists() and any(target_path.iterdir()) and not force:
659
+ if yes:
660
+ # In --yes mode, we proceed without prompting (same as if user said yes)
661
+ pass
662
+ else:
663
+ overwrite = typer.confirm(
664
+ f"Configuration directory {target_path} already exists and is not empty. "
665
+ "Overwrite?",
666
+ default=False,
667
+ )
668
+ if not overwrite:
669
+ ctx.print_info("Configuration initialization cancelled.")
670
+ raise typer.Exit(0)
671
+
672
+ if dry_run:
673
+ ctx.print_info(f"DRY RUN: Would create configuration in {target_path}")
674
+ return
675
+
676
+ # Create directory structure
677
+ target_path.mkdir(parents=True, exist_ok=True)
678
+ (target_path / "devices").mkdir(exist_ok=True)
679
+ (target_path / "groups").mkdir(exist_ok=True)
680
+ (target_path / "sequences").mkdir(exist_ok=True)
681
+
682
+ # Create core configuration files
683
+ ctx.print_info("Creating configuration files...")
684
+ create_env_file(target_path)
685
+ ctx.print_success(f"Created credential template: {target_path / '.env'}")
686
+
687
+ create_config_yml(target_path)
688
+ ctx.print_success(f"Created main configuration: {target_path / 'config.yml'}")
689
+
690
+ create_example_devices(target_path / "devices")
691
+ ctx.print_success(f"Created example devices: {target_path / 'devices'}")
692
+
693
+ create_example_groups(target_path / "groups")
694
+ ctx.print_success(f"Created example groups: {target_path / 'groups'}")
695
+
696
+ create_example_sequences(target_path / "sequences")
697
+ ctx.print_success(f"Created example sequences: {target_path / 'sequences'}")
698
+
699
+ ctx.print_success(f"Base configuration initialized in {target_path}")
700
+
701
+ # Handle optional features
702
+ default_seq_repo = "https://github.com/narrowin/networka.git"
703
+ do_install_sequences = False
704
+ do_install_compl = False
705
+ do_install_schemas = False
706
+ chosen_shell: str | None = None
707
+ do_activate_compl = False
708
+
709
+ interactive_extras = interactive and not dry_run
710
+
711
+ if install_sequences is not None:
712
+ do_install_sequences = install_sequences
713
+ elif interactive_extras:
714
+ do_install_sequences = typer.confirm(
715
+ "Install additional predefined vendor sequences from GitHub?",
716
+ default=True,
717
+ )
718
+
719
+ if install_completions is not None:
720
+ do_install_compl = install_completions
721
+ elif interactive_extras:
722
+ do_install_compl = typer.confirm("Install shell completions?", default=True)
723
+
724
+ if install_schemas is not None:
725
+ do_install_schemas = install_schemas
726
+ elif interactive_extras:
727
+ do_install_schemas = typer.confirm(
728
+ "Install JSON schemas for YAML editor validation and auto-completion?",
729
+ default=True,
730
+ )
731
+
732
+ if do_install_compl:
733
+ detected = (
734
+ detect_shell(shell)
735
+ if interactive_extras
736
+ else (shell if shell in {"bash", "zsh"} else None)
737
+ )
738
+ if interactive_extras:
739
+ default_shell = detected or "bash"
740
+ answer = typer.prompt(
741
+ "Choose shell for completions (bash|zsh)", default=default_shell
742
+ )
743
+ chosen_shell = answer if answer in {"bash", "zsh"} else default_shell
744
+ else:
745
+ chosen_shell = detected or "bash"
746
+
747
+ if activate_completions is not None:
748
+ do_activate_compl = activate_completions
749
+ elif interactive_extras:
750
+ do_activate_compl = typer.confirm(
751
+ f"Activate {chosen_shell} completions by updating your shell profile?",
752
+ default=True,
753
+ )
754
+
755
+ # Execute optional installations
756
+ if do_install_sequences:
757
+ try:
758
+ ctx.print_info("Installing additional vendor sequences...")
759
+ files_installed = install_sequences_from_repo(
760
+ git_url or default_seq_repo,
761
+ git_ref,
762
+ target_path / "sequences",
763
+ )
764
+ if files_installed > 0:
765
+ ctx.print_success(
766
+ f"Installed {files_installed} sequence files from {git_url or default_seq_repo}"
767
+ )
768
+ else:
769
+ ctx.print_warning("No sequence files found in repository")
770
+ except Exception as e:
771
+ ctx.print_error(f"Failed to install sequences: {e}")
772
+
773
+ if do_install_compl and chosen_shell:
774
+ try:
775
+ ctx.print_info(f"Installing {chosen_shell} shell completion...")
776
+ installed_path, rc_file = install_shell_completions(chosen_shell)
777
+ if installed_path is not None:
778
+ ctx.print_success(f"Installed completion script: {installed_path}")
779
+ if do_activate_compl and rc_file:
780
+ activate_shell_completion(chosen_shell, installed_path, rc_file)
781
+ ctx.print_success(f"Activated completion in: {rc_file}")
782
+ ctx.print_info(
783
+ "Restart your shell or run 'source ~/.bashrc' to enable completions"
784
+ )
785
+ else:
786
+ ctx.print_info("Completion script installed but not activated")
787
+ else:
788
+ ctx.print_warning("Shell completion installation failed")
789
+ except Exception as e:
790
+ ctx.print_error(f"Failed to install completions: {e}")
791
+
792
+ if do_install_schemas:
793
+ try:
794
+ ctx.print_info("Installing JSON schemas for YAML editor validation...")
795
+ schema_count = install_editor_schemas(target_path, git_url, git_ref)
796
+ if schema_count > 0:
797
+ ctx.print_success(
798
+ f"Installed {schema_count} schema files in: {target_path / 'schemas'}"
799
+ )
800
+ ctx.print_success(
801
+ f"Configured VS Code settings: {target_path / '.vscode' / 'settings.json'}"
802
+ )
803
+ else:
804
+ ctx.print_warning("No schema files could be downloaded")
805
+ except Exception as e:
806
+ ctx.print_error(f"Failed to install schemas: {e}")
807
+
808
+
809
+ def _config_validate_impl(
810
+ config_file: Path,
811
+ output_mode: OutputMode | None = None,
812
+ verbose: bool = False,
813
+ ) -> None:
814
+ """Implementation logic for config validate."""
815
+ output_manager = None
816
+ try:
817
+ config = load_config(config_file)
818
+
819
+ # Handle output mode configuration
820
+ if output_mode is not None:
821
+ set_output_mode(output_mode)
822
+ output_manager = get_output_manager()
823
+ else:
824
+ # Use config-based output mode
825
+ output_manager = get_output_manager_with_config(config.general.output_mode)
826
+
827
+ # Discover and display where the config was resolved from
828
+ meta = _discover_config_metadata(config_file)
829
+ display_name = str(meta.get("display_name", str(config_file)))
830
+ resolved_root = meta.get("root")
831
+ files = meta.get("files")
832
+ mode = meta.get("mode")
833
+
834
+ output_manager.print_info(f"Validating Configuration: {display_name}")
835
+ if isinstance(resolved_root, Path):
836
+ output_manager.print_info(f"Path: {resolved_root}")
837
+ if isinstance(mode, str) and mode in {"modular", "legacy"}:
838
+ output_manager.print_info(f"Mode: {mode}")
839
+ if isinstance(files, list) and files:
840
+ output_manager.print_info("Files:")
841
+ files_typed = cast(list[Path], files)
842
+ for f in files_typed:
843
+ output_manager.print_info(f" - {f}")
844
+ output_manager.print_blank_line()
845
+
846
+ output_manager.print_success("Configuration is valid!")
847
+ output_manager.print_blank_line()
848
+
849
+ device_count = len(config.devices) if config.devices else 0
850
+ group_count = len(config.device_groups) if config.device_groups else 0
851
+ global_seq_count = (
852
+ len(config.global_command_sequences)
853
+ if config.global_command_sequences
854
+ else 0
855
+ )
856
+
857
+ output_manager.print_info(f"Devices: {device_count}")
858
+ output_manager.print_info(f"Device Groups: {group_count}")
859
+ output_manager.print_info(f"Global Sequences: {global_seq_count}")
860
+
861
+ if verbose and device_count > 0 and config.devices:
862
+ output_manager.print_blank_line()
863
+ output_manager.print_info("Device Summary:")
864
+ for name, device in config.devices.items():
865
+ output_manager.print_info(
866
+ f" • {name} ({device.host}) - {device.device_type}"
867
+ )
868
+
869
+ except NetworkToolkitError as e:
870
+ # Initialize output_manager if not already set
871
+ if output_manager is None:
872
+ output_manager = get_output_manager()
873
+ output_manager.print_error("Configuration validation failed!")
874
+ output_manager.print_error(f"Error: {e.message}")
875
+ if verbose and e.details:
876
+ output_manager.print_error(f"Details: {e.details}")
877
+ raise typer.Exit(1) from None
878
+ except Exception as e: # pragma: no cover - unexpected
879
+ # Initialize output_manager if not already set
880
+ if output_manager is None:
881
+ output_manager = get_output_manager()
882
+ output_manager.print_error(f"Unexpected error during validation: {e}")
883
+ raise typer.Exit(1) from None
884
+
885
+
886
+ def register(app: typer.Typer) -> None:
887
+ """Register the unified config command group with the main CLI app."""
888
+ config_app = typer.Typer(
889
+ name="config",
890
+ help="Configuration management commands",
891
+ no_args_is_help=True,
892
+ )
893
+
894
+ @config_app.command("init")
895
+ def init(
896
+ target_dir: Annotated[
897
+ Path | None,
898
+ typer.Argument(
899
+ help=(
900
+ "Directory to initialize (default: system config location for your OS)"
901
+ ),
902
+ ),
903
+ ] = None,
904
+ force: Annotated[
905
+ bool, typer.Option("--force", "-f", help="Overwrite existing files")
906
+ ] = False,
907
+ yes: Annotated[
908
+ bool, typer.Option("--yes", "-y", help="Non-interactive: accept defaults")
909
+ ] = False,
910
+ dry_run: Annotated[
911
+ bool, typer.Option("--dry-run", help="Show actions without writing changes")
912
+ ] = False,
913
+ install_sequences: Annotated[
914
+ bool | None,
915
+ typer.Option(
916
+ "--install-sequences/--no-install-sequences",
917
+ help="Install additional predefined vendor sequences from GitHub",
918
+ ),
919
+ ] = None,
920
+ git_url: Annotated[
921
+ str | None,
922
+ typer.Option(
923
+ "--git-url",
924
+ help="Git URL for sequences when using --sequences-source git",
925
+ ),
926
+ ] = None,
927
+ git_ref: Annotated[
928
+ str,
929
+ typer.Option(
930
+ "--git-ref", help="Git branch/tag/ref for sequences", show_default=True
931
+ ),
932
+ ] = "main",
933
+ install_completions: Annotated[
934
+ bool | None,
935
+ typer.Option(
936
+ "--install-completions/--no-install-completions",
937
+ help="Install shell completion scripts",
938
+ ),
939
+ ] = None,
940
+ shell: Annotated[
941
+ str | None,
942
+ typer.Option("--shell", help="Shell for completions (bash or zsh)"),
943
+ ] = None,
944
+ activate_completions: Annotated[
945
+ bool | None,
946
+ typer.Option(
947
+ "--activate-completions/--no-activate-completions",
948
+ help="Activate completions by updating shell rc file",
949
+ ),
950
+ ] = None,
951
+ install_schemas: Annotated[
952
+ bool | None,
953
+ typer.Option(
954
+ "--install-schemas/--no-install-schemas",
955
+ help="Install JSON schemas for YAML editor validation and auto-completion",
956
+ ),
957
+ ] = None,
958
+ verbose: Annotated[
959
+ bool, typer.Option("--verbose", "-v", help="Enable verbose logging")
960
+ ] = False,
961
+ ) -> None:
962
+ """Initialize a network toolkit configuration in OS-appropriate location.
963
+
964
+ Creates a complete starter configuration with:
965
+ - .env file with credential templates
966
+ - config.yml with core settings
967
+ - devices/ with MikroTik and Cisco examples
968
+ - groups/ with tag-based and explicit groups
969
+ - sequences/ with global and vendor-specific sequences
970
+ - JSON schemas for YAML editor validation (optional)
971
+ - Shell completions (optional)
972
+ - Additional predefined sequences from GitHub (optional)
973
+
974
+ Default locations by OS:
975
+ - Linux: ~/.config/networka/
976
+ - macOS: ~/Library/Application Support/networka/
977
+ - Windows: %APPDATA%/networka/
978
+
979
+ The 'nw' command will automatically find configurations in these locations.
980
+ """
981
+ setup_logging("DEBUG" if verbose else "INFO")
982
+
983
+ try:
984
+ # Use the local implementation
985
+ _config_init_impl(
986
+ target_dir=target_dir,
987
+ force=force,
988
+ yes=yes,
989
+ dry_run=dry_run,
990
+ install_sequences=install_sequences,
991
+ git_url=git_url,
992
+ git_ref=git_ref,
993
+ install_completions=install_completions,
994
+ shell=shell,
995
+ activate_completions=activate_completions,
996
+ install_schemas=install_schemas,
997
+ verbose=verbose,
998
+ )
999
+
1000
+ except NetworkToolkitError as e:
1001
+ from network_toolkit.common.command_helpers import CommandContext
1002
+
1003
+ ctx = CommandContext()
1004
+ ctx.print_error(str(e))
1005
+ if verbose and hasattr(e, "details") and e.details:
1006
+ ctx.print_error(f"Details: {e.details}")
1007
+ raise typer.Exit(1) from None
1008
+ except typer.Exit:
1009
+ # Allow clean exits (e.g., user cancellation) to pass through
1010
+ raise
1011
+ except Exception as e: # pragma: no cover - unexpected
1012
+ from network_toolkit.common.command_helpers import CommandContext
1013
+
1014
+ ctx = CommandContext()
1015
+ ctx.print_error(f"Unexpected error: {e}")
1016
+ raise typer.Exit(1) from None
1017
+
1018
+ @config_app.command("validate")
1019
+ def validate(
1020
+ config_file: Annotated[
1021
+ Path, typer.Option("--config", "-c", help="Configuration file path")
1022
+ ] = DEFAULT_CONFIG_PATH,
1023
+ output_mode: Annotated[
1024
+ OutputMode | None,
1025
+ typer.Option(
1026
+ "--output-mode",
1027
+ "-o",
1028
+ help="Output decoration mode: default, light, dark, no-color, raw",
1029
+ show_default=False,
1030
+ ),
1031
+ ] = None,
1032
+ verbose: Annotated[
1033
+ bool,
1034
+ typer.Option(
1035
+ "--verbose", "-v", help="Show detailed validation information"
1036
+ ),
1037
+ ] = False,
1038
+ ) -> None:
1039
+ """Validate the configuration file and show any issues."""
1040
+ setup_logging("DEBUG" if verbose else "INFO")
1041
+
1042
+ try:
1043
+ # Use the local implementation
1044
+ _config_validate_impl(
1045
+ config_file=config_file,
1046
+ output_mode=output_mode,
1047
+ verbose=verbose,
1048
+ )
1049
+
1050
+ except NetworkToolkitError as e:
1051
+ from network_toolkit.common.command_helpers import CommandContext
1052
+
1053
+ ctx = CommandContext()
1054
+ ctx.print_error(str(e))
1055
+ if verbose and hasattr(e, "details") and e.details:
1056
+ ctx.print_error(f"Details: {e.details}")
1057
+ raise typer.Exit(1) from None
1058
+ except typer.Exit:
1059
+ # Allow clean exits (e.g., user cancellation) to pass through
1060
+ raise
1061
+ except Exception as e: # pragma: no cover - unexpected
1062
+ from network_toolkit.common.command_helpers import CommandContext
1063
+
1064
+ ctx = CommandContext()
1065
+ ctx.print_error(f"Unexpected error: {e}")
1066
+ raise typer.Exit(1) from None
1067
+
1068
+ app.add_typer(config_app, name="config", rich_help_panel="Info & Configuration")