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,550 @@
1
+ """Controller for the Textual TUI.
2
+
3
+ Encapsulates event handling and run lifecycle logic. Keeps UI plumbing
4
+ methods in the App class while coordinating behavior here for clarity.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import asyncio
10
+ import logging
11
+ import threading
12
+ import time
13
+ from typing import Any
14
+
15
+ from network_toolkit.tui.constants import STARTUP_NOTICE
16
+ from network_toolkit.tui.models import CancellationToken
17
+
18
+ # Single-source cancel prompt text used in toasts
19
+ CANCEL_TOAST = (
20
+ "1) Keep running\n"
21
+ "2) Cancel (soft) — recommended\n"
22
+ "3) Cancel (hard) — may disconnect sessions and leave devices in a partial state"
23
+ )
24
+
25
+
26
+ class TuiController:
27
+ def __init__(
28
+ self, app: Any, compat: Any, data: Any, service: Any, state: Any
29
+ ) -> None:
30
+ self.app = app
31
+ self.compat = compat
32
+ self.data = data
33
+ self.service = service
34
+ self.state = state
35
+
36
+ async def on_mount(self) -> None:
37
+ app = self.app
38
+ data = self.data
39
+ try:
40
+ t = data.targets()
41
+ a = data.actions()
42
+ # Keep base lists for filtering
43
+ app._all_devices = list(t.devices)
44
+ app._all_groups = list(t.groups)
45
+ app._all_sequences = list(a.sequences)
46
+ app._populate_selection_list("list-devices", app._all_devices)
47
+ app._populate_selection_list("list-groups", app._all_groups)
48
+ app._populate_selection_list("list-sequences", app._all_sequences)
49
+ except Exception:
50
+ pass
51
+ # Startup notice: use toast notification (lower-right, orange frame)
52
+ try:
53
+ self.compat.notify(app, STARTUP_NOTICE, timeout=3, severity="warning")
54
+ except Exception:
55
+ # If notify isn't available, skip (avoid status-line fallback)
56
+ pass
57
+ # Record UI thread identity for safe callback dispatching
58
+ try:
59
+ app._ui_thread_ident = threading.get_ident()
60
+ except Exception:
61
+ app._ui_thread_ident = -1
62
+ # Toggling states
63
+ app._summary_user_hidden = False
64
+ app._output_user_hidden = False
65
+ app._run_active = False
66
+ try:
67
+ app._dark_mode = bool(getattr(app, "dark", True))
68
+ except Exception:
69
+ app._dark_mode = True
70
+ app._summary_filter = ""
71
+ app._output_filter = ""
72
+ app._output_lines = []
73
+ app._refresh_bottom_visibility()
74
+ # Async task + cancellation token for active run
75
+ app._run_task = None
76
+ app._cancel_token = None
77
+ # Background tasks and toast-prompt state flags
78
+ app._bg_tasks = set()
79
+ app._cancel_prompt_active = False
80
+ # legacy flag no longer used; kept off for compatibility
81
+ app._quit_prompt_active = False
82
+
83
+ async def on_input_changed(self, event: Any) -> None:
84
+ app = self.app
85
+ try:
86
+ sender = (
87
+ getattr(event, "input", None)
88
+ or getattr(event, "control", None)
89
+ or getattr(event, "sender", None)
90
+ )
91
+ sender_id = getattr(sender, "id", "") or ""
92
+ value = getattr(sender, "value", "") or ""
93
+ except Exception:
94
+ return
95
+ text = value.strip().lower()
96
+ if sender_id == "filter-devices":
97
+ base: list[str] = list(getattr(app, "_all_devices", []) or [])
98
+ try:
99
+ sel_widget = app.query_one("#list-devices")
100
+ current_sel: set[str] = app._selected_values(sel_widget)
101
+ except Exception:
102
+ current_sel = set()
103
+ items = [d for d in base if text in d.lower()]
104
+ app._populate_selection_list("list-devices", items, selected=current_sel)
105
+ return
106
+ if sender_id == "filter-groups":
107
+ base = list(getattr(app, "_all_groups", []) or [])
108
+ try:
109
+ sel_widget = app.query_one("#list-groups")
110
+ current_sel = app._selected_values(sel_widget)
111
+ except Exception:
112
+ current_sel = set()
113
+ items = [g for g in base if text in g.lower()]
114
+ app._populate_selection_list("list-groups", items, selected=current_sel)
115
+ return
116
+ if sender_id == "filter-sequences":
117
+ base = list(getattr(app, "_all_sequences", []) or [])
118
+ try:
119
+ sel_widget = app.query_one("#list-sequences")
120
+ current_sel = app._selected_values(sel_widget)
121
+ except Exception:
122
+ current_sel = set()
123
+ items = [s for s in base if text in s.lower()]
124
+ app._populate_selection_list("list-sequences", items, selected=current_sel)
125
+ return
126
+ if sender_id == "filter-summary":
127
+ app._summary_filter = value
128
+ app._render_summary()
129
+ return
130
+ if sender_id == "filter-output":
131
+ app._apply_output_filter(value)
132
+
133
+ async def action_confirm(self) -> None:
134
+ app = self.app
135
+ service = self.service
136
+ state = self.state
137
+ # Disallow starting a new run if one is active: single-step cancel/keep prompt
138
+ if getattr(app, "_run_active", False):
139
+ app._cancel_prompt_active = True
140
+ app._add_meta(
141
+ "Run already in progress — choose: 1) keep, 2) soft cancel, 3) hard cancel"
142
+ )
143
+ try:
144
+ self.compat.notify(app, CANCEL_TOAST, timeout=8, severity="warning")
145
+ except Exception:
146
+ pass
147
+ return
148
+
149
+ # Prepare UI for a new run
150
+ out_log = app.query_one("#output-log")
151
+ if hasattr(out_log, "clear"):
152
+ out_log.clear()
153
+ try:
154
+ app._output_lines = []
155
+ except Exception:
156
+ pass
157
+ # Clear per-device tabs and buffers to start fresh
158
+ try:
159
+ app._reset_output_tabs()
160
+ except Exception:
161
+ pass
162
+ app._errors = []
163
+ app._meta = []
164
+ # Keep the previous summary visible to avoid flicker; we'll update it once the new plan is ready.
165
+ try:
166
+ app._hide_output_panel()
167
+ except Exception:
168
+ pass
169
+
170
+ app._add_meta("Starting run...")
171
+ app._run_active = True
172
+ app._cancel_token = CancellationToken()
173
+ app._set_inputs_enabled(False)
174
+ app._set_run_enabled(False)
175
+
176
+ async def _runner() -> None:
177
+ start_ts: float | None = None
178
+ try:
179
+ logging.disable(logging.CRITICAL)
180
+ start_ts = time.monotonic()
181
+ app._collect_state()
182
+ devices = await asyncio.to_thread(
183
+ service.resolve_devices, state.devices, state.groups
184
+ )
185
+ if not devices:
186
+ app._dispatch_ui(app._render_summary, "No devices selected.")
187
+ try:
188
+ msg = "Status: idle — No devices selected."
189
+ app.query_one("#run-status").update(msg)
190
+ app._refresh_bottom_visibility()
191
+ except Exception:
192
+ pass
193
+ return
194
+ plan = service.build_plan(devices, state.sequences, state.command_text)
195
+ if not plan:
196
+ app._dispatch_ui(
197
+ app._render_summary, "No sequences or commands provided."
198
+ )
199
+ try:
200
+ msg = "Status: idle — No sequences or commands provided."
201
+ app.query_one("#run-status").update(msg)
202
+ app._refresh_bottom_visibility()
203
+ except Exception:
204
+ pass
205
+ return
206
+ total = len(plan)
207
+ # Render an upfront summary of what will run and show summary panel
208
+ try:
209
+ device_list = ", ".join(list(plan.keys()))
210
+ summary_intro = (
211
+ f"Planned devices: {device_list} — commands per device vary"
212
+ )
213
+ app._render_summary(summary_intro)
214
+ app._show_summary_panel()
215
+ except Exception:
216
+ pass
217
+ try:
218
+ app._show_bottom_panel()
219
+ app.query_one("#run-status").update(
220
+ f"Status: running 0/{total} (press Ctrl+C to cancel)"
221
+ )
222
+ except Exception:
223
+ pass
224
+ from network_toolkit.tui.models import RunCallbacks
225
+
226
+ summary_result = await service.run_plan(
227
+ plan,
228
+ RunCallbacks(
229
+ on_output=lambda m: app._dispatch_ui(app._output_append, m),
230
+ on_error=lambda m: app._dispatch_ui(app._add_error, m),
231
+ on_meta=lambda m: app._dispatch_ui(app._add_meta, m),
232
+ on_device_output=lambda d, m: app._dispatch_ui(
233
+ app._output_append_device, d, m
234
+ ),
235
+ ),
236
+ cancel=app._cancel_token,
237
+ )
238
+ try:
239
+ if getattr(app, "_output_lines", None):
240
+ app._show_output_panel()
241
+ try:
242
+ out_log2 = app.query_one("#output-log")
243
+ if hasattr(out_log2, "clear"):
244
+ out_log2.clear()
245
+ filt = (
246
+ (getattr(app, "_output_filter", "") or "")
247
+ .strip()
248
+ .lower()
249
+ )
250
+ lines: list[str] = [
251
+ str(x)
252
+ for x in (getattr(app, "_output_lines", []) or [])
253
+ ]
254
+ for line in lines:
255
+ if not filt or (filt in line.lower()):
256
+ from network_toolkit.tui.helpers import log_write
257
+
258
+ log_write(out_log2, line)
259
+ except Exception:
260
+ pass
261
+ elapsed = time.monotonic() - start_ts
262
+ summary_with_time = (
263
+ f"{summary_result.human_summary()} (duration: {elapsed:.2f}s)"
264
+ )
265
+ app._render_summary(summary_with_time)
266
+ try:
267
+ err_count = len(getattr(app, "_errors", []) or [])
268
+ except Exception:
269
+ err_count = 0
270
+ status_msg = f"Status: idle — {summary_with_time}"
271
+ if err_count:
272
+ status_msg += " — errors available (press s)"
273
+ app.query_one("#run-status").update(status_msg)
274
+ app._refresh_bottom_visibility()
275
+ except Exception:
276
+ pass
277
+ except Exception as e:
278
+ try:
279
+ elapsed = (
280
+ (time.monotonic() - start_ts) if (start_ts is not None) else 0.0
281
+ )
282
+ except Exception:
283
+ elapsed = 0.0
284
+ app._dispatch_ui(
285
+ app._render_summary, f"Run failed: {e} (after {elapsed:.2f}s)"
286
+ )
287
+ try:
288
+ app.query_one("#run-status").update(
289
+ f"Status: idle — Run failed: {e}"
290
+ )
291
+ if getattr(app, "_output_lines", None):
292
+ app._show_output_panel()
293
+ app._refresh_bottom_visibility()
294
+ except Exception:
295
+ pass
296
+ finally:
297
+ logging.disable(logging.NOTSET)
298
+ try:
299
+ app._run_active = False
300
+ app._set_inputs_enabled(True)
301
+ app._set_run_enabled(True)
302
+ app._cancel_token = None
303
+ app._run_task = None
304
+ try:
305
+ app._dispatch_ui(app._clear_all_selections)
306
+ except Exception:
307
+ pass
308
+ except Exception:
309
+ pass
310
+
311
+ # Schedule runner without blocking UI loop
312
+ try:
313
+ loop = asyncio.get_running_loop()
314
+ app._run_task = loop.create_task(_runner())
315
+ except Exception:
316
+ # Fallback: run inline (still async) if loop is not accessible
317
+ await _runner()
318
+
319
+ async def action_cancel(self) -> None:
320
+ app = self.app
321
+ # Trigger cooperative cancellation and update UI; do nothing if idle
322
+ try:
323
+ token = getattr(app, "_cancel_token", None)
324
+ if token is not None:
325
+ token.set()
326
+ app._add_meta("Cancellation requested")
327
+ try:
328
+ status = app.query_one("#run-status")
329
+ status.update("Status: cancelling…")
330
+ except Exception:
331
+ pass
332
+ # No prompt state flags
333
+ except Exception:
334
+ pass
335
+
336
+ async def action_cancel_hard(self) -> None:
337
+ """Hard cancel: set token and aggressively disconnect active sessions."""
338
+ app = self.app
339
+ try:
340
+ token = getattr(app, "_cancel_token", None)
341
+ if token is not None:
342
+ try:
343
+ token.set()
344
+ except Exception:
345
+ pass
346
+ try:
347
+ # Ask the service to close active sessions to interrupt blocking calls
348
+ self.service.request_hard_cancel(token)
349
+ except Exception:
350
+ pass
351
+ app._add_meta(
352
+ "Hard cancellation requested — connections will be terminated."
353
+ )
354
+ try:
355
+ status = app.query_one("#run-status")
356
+ status.update(
357
+ "Status: cancelling (hard) — connections will be terminated; in-flight operations may be partially applied"
358
+ )
359
+ except Exception:
360
+ pass
361
+ # No prompt state flags
362
+ except Exception:
363
+ pass
364
+
365
+ async def on_input_submitted(self, event: Any) -> None:
366
+ try:
367
+ sender = (
368
+ getattr(event, "input", None)
369
+ or getattr(event, "control", None)
370
+ or getattr(event, "sender", None)
371
+ )
372
+ if getattr(sender, "id", "") == "input-commands":
373
+ await self.action_confirm()
374
+ if hasattr(event, "stop"):
375
+ event.stop()
376
+ except Exception:
377
+ pass
378
+
379
+ async def on_button_pressed(self, event: Any) -> None:
380
+ try:
381
+ btn = getattr(event, "button", None)
382
+ if getattr(btn, "id", "") == "run-button":
383
+ await self.action_confirm()
384
+ if hasattr(event, "stop"):
385
+ event.stop()
386
+ except Exception:
387
+ pass
388
+
389
+ def on_key(self, event: Any) -> None:
390
+ app = self.app
391
+ try:
392
+ key = str(getattr(event, "key", "")).lower()
393
+ except Exception:
394
+ key = ""
395
+ # Handle toast-driven prompts first (cancel/quit flows)
396
+ try:
397
+ if getattr(app, "_cancel_prompt_active", False):
398
+ if key in {"2"}: # soft cancel
399
+ app._cancel_prompt_active = False
400
+ try:
401
+ task = asyncio.create_task(self.action_cancel())
402
+ self.app._bg_tasks.add(task)
403
+ task.add_done_callback(self.app._bg_tasks.discard)
404
+ except Exception:
405
+ pass
406
+ if hasattr(event, "stop"):
407
+ event.stop()
408
+ return
409
+ if key in {"3"}: # hard cancel
410
+ app._cancel_prompt_active = False
411
+ try:
412
+ task = asyncio.create_task(self.action_cancel_hard())
413
+ self.app._bg_tasks.add(task)
414
+ task.add_done_callback(self.app._bg_tasks.discard)
415
+ except Exception:
416
+ pass
417
+ if hasattr(event, "stop"):
418
+ event.stop()
419
+ return
420
+ if key in {"1", "enter", "return", "escape"}: # keep running
421
+ app._cancel_prompt_active = False
422
+ try:
423
+ status = app.query_one("#run-status")
424
+ status.update("Status: running — Continuing current run")
425
+ app._refresh_bottom_visibility()
426
+ except Exception:
427
+ try:
428
+ self.compat.notify(
429
+ app,
430
+ "Continuing current run",
431
+ timeout=2,
432
+ severity="info",
433
+ )
434
+ except Exception:
435
+ pass
436
+ if hasattr(event, "stop"):
437
+ event.stop()
438
+ return
439
+ if getattr(app, "_quit_prompt_active", False):
440
+ if key == "y":
441
+ app._quit_prompt_active = False
442
+ try:
443
+ if hasattr(app, "exit"):
444
+ app.exit()
445
+ else:
446
+ raise SystemExit(0)
447
+ except Exception:
448
+ raise SystemExit(0) from None
449
+ if key in {"n", "enter", "return", "escape"}:
450
+ app._quit_prompt_active = False
451
+ if hasattr(event, "stop"):
452
+ event.stop()
453
+ return
454
+ except Exception:
455
+ pass
456
+ if key == "q":
457
+ # If any overlay is visible, close it; otherwise ask to quit
458
+ try:
459
+ sum_panel = app.query_one("#summary-panel")
460
+ help_panel = app.query_one("#help-panel")
461
+ out_panel = app.query_one("#output-panel")
462
+ s_hidden = "hidden" in (getattr(sum_panel, "classes", []) or [])
463
+ h_hidden = "hidden" in (getattr(help_panel, "classes", []) or [])
464
+ o_hidden = "hidden" in (getattr(out_panel, "classes", []) or [])
465
+ any_visible = not (s_hidden and h_hidden and o_hidden)
466
+ except Exception:
467
+ any_visible = False
468
+ if any_visible:
469
+ try:
470
+ app.action_close_overlays()
471
+ except Exception:
472
+ pass
473
+ try:
474
+ if hasattr(event, "stop"):
475
+ event.stop()
476
+ except Exception:
477
+ pass
478
+ return
479
+
480
+ # No overlays: ask to quit via toast and let on_key handle y/N
481
+ app._quit_prompt_active = True
482
+ try:
483
+ self.compat.notify(
484
+ app, "Do you want to quit? [y/N]", timeout=5, severity="warning"
485
+ )
486
+ except Exception:
487
+ pass
488
+ try:
489
+ if hasattr(event, "stop"):
490
+ event.stop()
491
+ except Exception:
492
+ pass
493
+ return
494
+ if key == "escape":
495
+ try:
496
+ app.action_close_overlays()
497
+ if hasattr(event, "stop"):
498
+ event.stop()
499
+ except Exception:
500
+ pass
501
+ elif key in {"ctrl+q"}:
502
+ # Disable Ctrl+Q quitting entirely
503
+ try:
504
+ if hasattr(event, "stop"):
505
+ event.stop()
506
+ except Exception:
507
+ pass
508
+ elif key == "s":
509
+ try:
510
+ app.action_toggle_summary()
511
+ if hasattr(event, "stop"):
512
+ event.stop()
513
+ except Exception:
514
+ pass
515
+ elif key == "o":
516
+ try:
517
+ app.action_toggle_output()
518
+ if hasattr(event, "stop"):
519
+ event.stop()
520
+ except Exception:
521
+ pass
522
+ elif key == "t":
523
+ try:
524
+ app.action_toggle_theme()
525
+ if hasattr(event, "stop"):
526
+ event.stop()
527
+ except Exception:
528
+ pass
529
+ elif key == "h":
530
+ try:
531
+ app.action_toggle_help()
532
+ if hasattr(event, "stop"):
533
+ event.stop()
534
+ except Exception:
535
+ pass
536
+ elif key in {"ctrl+c"}:
537
+ # Ctrl+C: show single-step cancel toast; on_key will handle response
538
+ try:
539
+ if getattr(app, "_run_active", False):
540
+ app._cancel_prompt_active = True
541
+ try:
542
+ self.compat.notify(
543
+ app, CANCEL_TOAST, timeout=8, severity="warning"
544
+ )
545
+ except Exception:
546
+ pass
547
+ if hasattr(event, "stop"):
548
+ event.stop()
549
+ except Exception:
550
+ pass
@@ -0,0 +1,149 @@
1
+ """Data access layer for the TUI.
2
+
3
+ This module isolates interactions with the existing codebase so the
4
+ Textual UI remains a thin layer on top.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import os
10
+ from collections.abc import Iterable
11
+ from pathlib import Path
12
+ from typing import Any, cast
13
+
14
+ from pydantic import BaseModel, ConfigDict
15
+
16
+ from network_toolkit.config import NetworkConfig, load_config
17
+ from network_toolkit.sequence_manager import SequenceManager
18
+
19
+
20
+ class Targets(BaseModel):
21
+ """Lists of available targets."""
22
+
23
+ model_config = ConfigDict(frozen=True)
24
+
25
+ devices: list[str]
26
+ groups: list[str]
27
+
28
+
29
+ class Actions(BaseModel):
30
+ """Lists of available actions to run."""
31
+
32
+ model_config = ConfigDict(frozen=True)
33
+
34
+ sequences: list[str]
35
+ # Free-form commands are user provided, not discovered here
36
+
37
+
38
+ class TuiData:
39
+ """Load and expose configuration data for the TUI.
40
+
41
+ Contract:
42
+ - targets() -> Targets
43
+ - actions() -> Actions
44
+ - sequence_commands(name) -> list[str] | None
45
+ """
46
+
47
+ def __init__(self, config_path: str | Path = "config") -> None:
48
+ self._config_path = Path(config_path)
49
+ self._config: NetworkConfig | None = None
50
+ self._seq_mgr: SequenceManager | None = None
51
+ self._load()
52
+
53
+ @property
54
+ def config(self) -> NetworkConfig:
55
+ assert self._config is not None
56
+ return self._config
57
+
58
+ @property
59
+ def sequence_manager(self) -> SequenceManager:
60
+ assert self._seq_mgr is not None
61
+ return self._seq_mgr
62
+
63
+ def _load(self) -> None:
64
+ cfg_path = self._config_path
65
+ try:
66
+ cfg = load_config(cfg_path)
67
+ except FileNotFoundError:
68
+ fallback = self._resolve_fallback_config_path(cfg_path)
69
+ if fallback is None:
70
+ raise
71
+ cfg = load_config(fallback)
72
+ # Remember the resolved path for later
73
+ self._config_path = fallback
74
+ self._config = cfg
75
+ self._seq_mgr = SequenceManager(cfg)
76
+
77
+ def _resolve_fallback_config_path(self, _original: Path) -> Path | None:
78
+ """Best-effort fallback discovery for config directory.
79
+
80
+ Attempts the following in order:
81
+ 1. NW_CONFIG_DIR environment variable
82
+ 2. Search upwards from current working directory for a 'config' directory
83
+ 3. Search upwards from this module's parent directories for a 'config' directory
84
+ """
85
+ # 1) Explicit environment override
86
+ env_dir = os.environ.get("NW_CONFIG_DIR")
87
+ if env_dir:
88
+ p = Path(env_dir)
89
+ if p.exists():
90
+ return p
91
+
92
+ # Function to search ancestors for a folder named 'config'
93
+ def search_up(start: Path) -> Path | None:
94
+ cur = start
95
+ seen = 0
96
+ while True:
97
+ candidate = cur / "config"
98
+ if candidate.exists() and candidate.is_dir():
99
+ return candidate
100
+ if cur.parent == cur or seen > 10:
101
+ return None
102
+ cur = cur.parent
103
+ seen += 1
104
+
105
+ # 2) From CWD
106
+ cwd_found = search_up(Path.cwd())
107
+ if cwd_found is not None:
108
+ return cwd_found
109
+
110
+ # 3) From path of the originally requested config (best-effort)
111
+ try:
112
+ module_found = search_up(_original.resolve())
113
+ except Exception:
114
+ module_found = None
115
+ if module_found is not None:
116
+ return module_found
117
+
118
+ return None
119
+
120
+ def targets(self) -> Targets:
121
+ devs = cast(dict[str, Any], self.config.devices or {})
122
+ grps = cast(dict[str, Any], self.config.device_groups or {})
123
+ devices: list[str] = sorted(devs.keys())
124
+ groups: list[str] = sorted(grps.keys())
125
+ return Targets(devices=devices, groups=groups)
126
+
127
+ def actions(self) -> Actions:
128
+ sequences = sorted(self._discover_all_sequences())
129
+ return Actions(sequences=sequences)
130
+
131
+ def _discover_all_sequences(self) -> Iterable[str]:
132
+ names: set[str] = set()
133
+ # Global
134
+ if self.config.global_command_sequences:
135
+ names |= set(self.config.global_command_sequences.keys())
136
+ # Vendor via SequenceManager
137
+ for vendor_map in self.sequence_manager.list_all_sequences().values():
138
+ names |= set(vendor_map.keys())
139
+ # Device-defined sequences
140
+ if self.config.devices:
141
+ for dev in self.config.devices.values():
142
+ if dev.command_sequences:
143
+ names |= set(dev.command_sequences.keys())
144
+ return names
145
+
146
+ def sequence_commands(
147
+ self, name: str, device_name: str | None = None
148
+ ) -> list[str] | None:
149
+ return self.sequence_manager.resolve(name, device_name)