lupaxa-github-intel 0.1.0__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 (41) hide show
  1. lupaxa/github_intel/__init__.py +13 -0
  2. lupaxa/github_intel/__main__.py +8 -0
  3. lupaxa/github_intel/app.py +493 -0
  4. lupaxa/github_intel/checks/__init__.py +1 -0
  5. lupaxa/github_intel/checks/base.py +17 -0
  6. lupaxa/github_intel/checks/releases.py +59 -0
  7. lupaxa/github_intel/checks/workflows.py +34 -0
  8. lupaxa/github_intel/cli.py +699 -0
  9. lupaxa/github_intel/config/__init__.py +1 -0
  10. lupaxa/github_intel/config/defaults.py +150 -0
  11. lupaxa/github_intel/config/editor.py +316 -0
  12. lupaxa/github_intel/config/loader.py +412 -0
  13. lupaxa/github_intel/config/models.py +310 -0
  14. lupaxa/github_intel/config/paths.py +84 -0
  15. lupaxa/github_intel/config/profiles.py +143 -0
  16. lupaxa/github_intel/constants.py +54 -0
  17. lupaxa/github_intel/dates.py +179 -0
  18. lupaxa/github_intel/errors.py +72 -0
  19. lupaxa/github_intel/github/__init__.py +1 -0
  20. lupaxa/github_intel/github/auth.py +40 -0
  21. lupaxa/github_intel/github/client.py +239 -0
  22. lupaxa/github_intel/github/rate_limit.py +107 -0
  23. lupaxa/github_intel/layout.py +141 -0
  24. lupaxa/github_intel/logging_setup.py +51 -0
  25. lupaxa/github_intel/present.py +361 -0
  26. lupaxa/github_intel/reports/__init__.py +1 -0
  27. lupaxa/github_intel/reports/render.py +113 -0
  28. lupaxa/github_intel/storage/__init__.py +1 -0
  29. lupaxa/github_intel/storage/database.py +419 -0
  30. lupaxa/github_intel/sync/__init__.py +1 -0
  31. lupaxa/github_intel/sync/engine.py +671 -0
  32. lupaxa/github_intel/sync/summary.py +308 -0
  33. lupaxa/github_intel/tui/__init__.py +1 -0
  34. lupaxa/github_intel/tui/application.py +487 -0
  35. lupaxa/github_intel/views.py +896 -0
  36. lupaxa_github_intel-0.1.0.dist-info/METADATA +180 -0
  37. lupaxa_github_intel-0.1.0.dist-info/RECORD +41 -0
  38. lupaxa_github_intel-0.1.0.dist-info/WHEEL +5 -0
  39. lupaxa_github_intel-0.1.0.dist-info/entry_points.txt +2 -0
  40. lupaxa_github_intel-0.1.0.dist-info/licenses/LICENCE +21 -0
  41. lupaxa_github_intel-0.1.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,487 @@
1
+ """
2
+ Textual interface.
3
+
4
+ The widgets call :class:`Service`. They do not call GitHub themselves.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import asyncio
10
+
11
+ from rich.text import Text
12
+ from textual.app import App, ComposeResult
13
+ from textual.binding import Binding
14
+ from textual.containers import Horizontal, Vertical, VerticalScroll
15
+ from textual.screen import ModalScreen
16
+ from textual.widgets import DataTable, Footer, Header, Input, OptionList, Static
17
+
18
+ from lupaxa.github_intel.app import Service
19
+ from lupaxa.github_intel.config.paths import default_config_file
20
+ from lupaxa.github_intel.config.profiles import check_defaults, resolve_profile
21
+ from lupaxa.github_intel.dates import DEFAULT_DATE_FORMAT
22
+ from lupaxa.github_intel.errors import ConfigError, SyncTooSoon
23
+ from lupaxa.github_intel.layout import RIGHT_ALIGNED, Layout, resolve_layout, view_names
24
+ from lupaxa.github_intel.present import _present_cell, list_row, repo_title
25
+ from lupaxa.github_intel.views import RepositoryView, detail_rows
26
+
27
+ __all__ = ["IntelTui", "RepoDetail", "ViewPicker", "run_tui"]
28
+
29
+
30
+ class RepoDetail(ModalScreen[None]):
31
+ """Popup table of one repository."""
32
+
33
+ BINDINGS = [Binding("escape", "dismiss", "Close", priority=True)]
34
+
35
+ def __init__(
36
+ self,
37
+ view: RepositoryView,
38
+ date_format: str,
39
+ fields: tuple[str, ...] | None = None,
40
+ ) -> None:
41
+ """
42
+ Create the popup.
43
+
44
+ Args:
45
+ view: Repository to show.
46
+ date_format: Pattern such as ``DD/MM/YYYY HH:mm UTC``.
47
+ fields: Catalogue labels. ``None`` keeps the hardcoded detail.
48
+
49
+ """
50
+
51
+ super().__init__()
52
+ self.view = view
53
+ self.date_format = date_format
54
+ self.fields = fields
55
+
56
+ def compose(self) -> ComposeResult:
57
+ """
58
+ Build the field and value table.
59
+
60
+ Returns:
61
+ A bordered dialog.
62
+
63
+ """
64
+
65
+ with VerticalScroll(id="dialog"):
66
+ yield Static(repo_title(self.view), id="detail-title")
67
+ with Vertical(id="detail"):
68
+ for field, value in detail_rows(
69
+ self.view,
70
+ date_format=self.date_format,
71
+ fields=self.fields,
72
+ ):
73
+ with Horizontal(classes="detail-row"):
74
+ yield Static(field, classes="detail-field")
75
+ yield Static(
76
+ _present_cell(field, value, self.view),
77
+ classes="detail-value",
78
+ )
79
+
80
+
81
+ class ViewPicker(ModalScreen[str | None]):
82
+ """Saved view names. Enter chooses one. Escape closes the list."""
83
+
84
+ BINDINGS = [Binding("escape", "dismiss", "Close", priority=True)]
85
+
86
+ def __init__(self, names: tuple[str, ...]) -> None:
87
+ """
88
+ Create the picker.
89
+
90
+ Args:
91
+ names: View names, with the default first.
92
+
93
+ """
94
+
95
+ super().__init__()
96
+ self.names = names
97
+
98
+ def compose(self) -> ComposeResult:
99
+ """
100
+ Build the view list.
101
+
102
+ Returns:
103
+ A bordered dialog.
104
+
105
+ """
106
+
107
+ with VerticalScroll(id="dialog"):
108
+ yield Static("Views", id="detail-title")
109
+ yield OptionList(*self.names, id="view-list")
110
+
111
+ def on_mount(self) -> None:
112
+ """Focus the list so Enter selects the highlighted view."""
113
+
114
+ self.query_one(OptionList).focus()
115
+
116
+ def on_option_list_option_selected(
117
+ self,
118
+ event: OptionList.OptionSelected,
119
+ ) -> None:
120
+ """
121
+ Close the picker with the chosen name.
122
+
123
+ Args:
124
+ event: Selection from the list.
125
+
126
+ """
127
+
128
+ prompt = event.option.prompt
129
+ self.dismiss(prompt if isinstance(prompt, str) else str(prompt))
130
+
131
+
132
+ class IntelTui(App[None]):
133
+ """Repository browser backed by the local cache."""
134
+
135
+ CSS = """
136
+ #summary { height: auto; padding: 0 1; }
137
+ #search { margin: 0 1; }
138
+ DataTable { height: 1fr; }
139
+ DataTable > .datatable--header {
140
+ color: cyan;
141
+ text-style: bold;
142
+ }
143
+ DataTable > .datatable--header-cursor {
144
+ color: cyan;
145
+ }
146
+ RepoDetail { align: center middle; }
147
+ ViewPicker { align: center middle; }
148
+ #dialog {
149
+ width: 90%;
150
+ max-width: 120;
151
+ height: auto;
152
+ max-height: 90%;
153
+ border: thick $accent;
154
+ background: $surface;
155
+ padding: 1 2;
156
+ overflow-x: hidden;
157
+ }
158
+ #detail-title { text-style: bold; padding: 0 0 1 0; height: auto; }
159
+ #detail { height: auto; }
160
+ .detail-row { height: auto; width: 100%; }
161
+ .detail-field { width: 20; height: auto; color: cyan; text-style: bold; }
162
+ .detail-value { width: 1fr; height: auto; }
163
+ """
164
+ BINDINGS = [
165
+ Binding("ctrl+q", "quit", "Quit", key_display="control + q", priority=True),
166
+ Binding("r", "sync", "Sync"),
167
+ Binding("slash", "search", "Search"),
168
+ Binding("p", "profiles", "Profiles"),
169
+ Binding("c", "config", "Config"),
170
+ Binding("v", "views", "Views"),
171
+ Binding("escape", "cancel", "Cancel"),
172
+ ]
173
+
174
+ def __init__(self, service: Service, view: str | None = None) -> None:
175
+ """
176
+ Create the interface.
177
+
178
+ Args:
179
+ service: Shared application service.
180
+ view: Named layout requested from the command line.
181
+
182
+ """
183
+
184
+ super().__init__()
185
+ self.service = service
186
+ self.views: list[RepositoryView] = []
187
+ self._requested_view = view
188
+ self._view_name = view or "default"
189
+ self._picked = False
190
+ self._layout: Layout | None = None
191
+ self.date_format = DEFAULT_DATE_FORMAT
192
+ self._mode = "repos"
193
+ self._sync_task: asyncio.Task[None] | None = None
194
+
195
+ def compose(self) -> ComposeResult:
196
+ """
197
+ Build the browser layout.
198
+
199
+ Returns:
200
+ Header, summary, search, table, and footer.
201
+
202
+ """
203
+
204
+ yield Header()
205
+ yield Static("Loading cache…", id="summary")
206
+ yield Input(placeholder="Search repositories...", id="search")
207
+ yield DataTable(id="table")
208
+ yield Footer()
209
+
210
+ async def on_mount(self) -> None:
211
+ """Load cached repositories without contacting GitHub, then focus the table."""
212
+
213
+ table = self.query_one(DataTable)
214
+ table.cursor_type = "row"
215
+ await self._reload()
216
+ table.focus()
217
+
218
+ async def on_input_changed(self, event: Input.Changed) -> None:
219
+ """
220
+ Filter the current table.
221
+
222
+ Args:
223
+ event: Search box change.
224
+
225
+ """
226
+
227
+ self._fill(event.value)
228
+
229
+ def action_search(self) -> None:
230
+ """Focus the search box."""
231
+
232
+ self.query_one("#search", Input).focus()
233
+
234
+ async def action_sync(self) -> None:
235
+ """Start synchronisation without blocking the interface."""
236
+
237
+ if self._sync_task is not None and not self._sync_task.done():
238
+ return
239
+ self._sync_task = asyncio.create_task(self._run_sync())
240
+
241
+ def action_cancel(self) -> None:
242
+ """Cancel the in-progress synchronisation."""
243
+
244
+ if self._sync_task is not None and not self._sync_task.done():
245
+ self._sync_task.cancel()
246
+
247
+ async def action_profiles(self) -> None:
248
+ """Show profiles and the repositories that use them."""
249
+
250
+ try:
251
+ loaded = self.service.load()
252
+ except ConfigError as exc:
253
+ self._show_config_error(exc)
254
+ return
255
+ self._mode = "profiles"
256
+ table = self.query_one(DataTable)
257
+ table.clear(columns=True)
258
+ table.add_columns("Profile", "Inheritance", "Repositories")
259
+ counts: dict[str, int] = {}
260
+ for view in self.views:
261
+ counts[view.profile] = counts.get(view.profile, 0) + 1
262
+ for name in loaded.profiles:
263
+ resolved = resolve_profile(
264
+ loaded.profiles,
265
+ name,
266
+ {},
267
+ **check_defaults(loaded.config.defaults),
268
+ )
269
+ table.add_row(name, " -> ".join(resolved.chain), str(counts.get(name, 0)))
270
+
271
+ async def action_config(self) -> None:
272
+ """Show the resolved configuration paths and sync settings."""
273
+
274
+ try:
275
+ loaded = self.service.load()
276
+ except ConfigError as exc:
277
+ self._show_config_error(exc)
278
+ return
279
+ self.query_one("#summary", Static).update(
280
+ "\n".join(
281
+ [
282
+ f"Config: {loaded.path}",
283
+ f"Profiles: {loaded.profiles_path}",
284
+ f"Repositories: {loaded.repositories_path}",
285
+ f"Concurrency: {loaded.config.sync.concurrency}",
286
+ "Configuration editing from the TUI is not available yet.",
287
+ ]
288
+ )
289
+ )
290
+
291
+ def action_views(self) -> None:
292
+ """Open the saved view picker."""
293
+
294
+ try:
295
+ loaded = self.service.load()
296
+ except ConfigError as exc:
297
+ self._show_config_error(exc)
298
+ return
299
+ self.push_screen(
300
+ ViewPicker(view_names(loaded.config.display)),
301
+ self._choose_view,
302
+ )
303
+
304
+ async def on_data_table_row_selected(self, event: DataTable.RowSelected) -> None:
305
+ """
306
+ Show the selected repository.
307
+
308
+ Args:
309
+ event: Table selection.
310
+
311
+ """
312
+
313
+ if self._mode != "repos":
314
+ return
315
+ repo = str(event.row_key.value)
316
+ view = next((item for item in self.views if item.repo == repo), None)
317
+ if view is None or self._layout is None:
318
+ return
319
+ self.push_screen(
320
+ RepoDetail(view, self.date_format, self._layout.detail_fields),
321
+ )
322
+
323
+ async def _run_sync(self) -> None:
324
+ try:
325
+ await self.service.assert_sync_allowed()
326
+ except SyncTooSoon as exc:
327
+ self.query_one("#summary", Static).update(str(exc))
328
+ self.notify(str(exc), severity="warning")
329
+ return
330
+ except ConfigError as exc:
331
+ self._show_config_error(exc)
332
+ return
333
+ self.query_one("#summary", Static).update("Synchronising…")
334
+ try:
335
+ report = await self.service.sync()
336
+ except asyncio.CancelledError:
337
+ self.query_one("#summary", Static).update("Synchronisation cancelled.")
338
+ await self._reload()
339
+ return
340
+ except SyncTooSoon as exc:
341
+ self.query_one("#summary", Static).update(str(exc))
342
+ self.notify(str(exc), severity="warning")
343
+ return
344
+ except ConfigError as exc:
345
+ self._show_config_error(exc)
346
+ return
347
+ self.query_one("#summary", Static).update(
348
+ f"Successful {report.successful} Failed {report.failed} "
349
+ f"Requests {report.requests} Elapsed {report.elapsed:.1f}s"
350
+ )
351
+ await self._reload()
352
+
353
+ def _show_config_error(self, exc: ConfigError) -> None:
354
+ self.query_one("#summary", Static).update(_config_problem(exc, self.service))
355
+ self.notify("Configuration could not be loaded.", severity="error")
356
+
357
+ def _choose_view(self, name: str | None) -> None:
358
+ if name is None:
359
+ return
360
+ self._picked = True
361
+ self._view_name = name
362
+ self._mode = "repos"
363
+ self._rebuild_table()
364
+
365
+ def _rebuild_table(self) -> None:
366
+ try:
367
+ loaded = self.service.load()
368
+ except ConfigError as exc:
369
+ self._show_config_error(exc)
370
+ return
371
+ self.date_format = loaded.config.display.date_format
372
+ try:
373
+ layout = resolve_layout(
374
+ loaded.config.display,
375
+ self._view_name,
376
+ self.views,
377
+ )
378
+ except ConfigError as exc:
379
+ self._show_config_error(exc)
380
+ return
381
+ self._show_repositories(layout)
382
+
383
+ async def _reload(self) -> None:
384
+ try:
385
+ loaded = self.service.load()
386
+ self.date_format = loaded.config.display.date_format
387
+ self.views = await self.service.views()
388
+ except ConfigError as exc:
389
+ self.views = []
390
+ self._show_config_error(exc)
391
+ return
392
+ selected = self._requested_view or loaded.config.display.view
393
+ if self._picked:
394
+ selected = self._view_name
395
+ try:
396
+ layout = resolve_layout(loaded.config.display, selected, self.views)
397
+ except ConfigError as exc:
398
+ self._show_config_error(exc)
399
+ return
400
+ self._show_repositories(layout)
401
+
402
+ def _show_repositories(self, layout: Layout) -> None:
403
+ self._layout = layout
404
+ self._mode = "repos"
405
+ table = self.query_one(DataTable)
406
+ table.clear(columns=True)
407
+ for label in layout.list_fields:
408
+ heading: str | Text = label
409
+ if label in RIGHT_ALIGNED:
410
+ heading = Text(label, justify="right")
411
+ table.add_column(heading, key=label)
412
+ self._fill(self.query_one("#search", Input).value)
413
+ self.query_one("#summary", Static).update(_counts(self.views))
414
+
415
+ def _fill(self, query: str) -> None:
416
+ if self._mode != "repos" or self._layout is None:
417
+ return
418
+ folded = query.casefold()
419
+ table = self.query_one(DataTable)
420
+ table.clear()
421
+ fields = self._layout.list_fields
422
+ rows = sorted(self.views, key=lambda view: view.repo.casefold())
423
+ for view in rows:
424
+ haystack = f"{view.repo} {view.description}".casefold()
425
+ if folded and folded not in haystack:
426
+ continue
427
+ painted = list_row(view, fields, self.date_format)
428
+ table.add_row(
429
+ *(
430
+ _aligned(label, cell)
431
+ for label, cell in zip(fields, painted, strict=True)
432
+ ),
433
+ key=view.repo,
434
+ )
435
+
436
+
437
+ def _aligned(label: str, cell: str | Text) -> str | Text:
438
+ if label not in RIGHT_ALIGNED:
439
+ return cell
440
+ if isinstance(cell, Text):
441
+ cell.justify = "right"
442
+ return cell
443
+ return Text(cell, justify="right")
444
+
445
+
446
+ def run_tui(service: Service, view: str | None = None) -> None:
447
+ """
448
+ Run the interactive interface until the operator quits.
449
+
450
+ Args:
451
+ service: Shared application service.
452
+ view: Named layout from the command line.
453
+
454
+ """
455
+
456
+ IntelTui(service, view).run()
457
+
458
+
459
+ def _config_problem(exc: ConfigError, service: Service) -> str:
460
+ location = service.config_path or default_config_file()
461
+ lines = ["Configuration could not be loaded.", "", str(exc)]
462
+ if str(location) not in str(exc):
463
+ lines.extend(["", f"Expected file: {location}"])
464
+ lines.extend(
465
+ [
466
+ "",
467
+ "Create the configuration with:",
468
+ "",
469
+ " github-intel repo add owner/name",
470
+ "",
471
+ "Or press control + q to quit.",
472
+ ]
473
+ )
474
+ return "\n".join(lines)
475
+
476
+
477
+ def _counts(views: list[RepositoryView]) -> str:
478
+ total = len(views)
479
+ pending = {"Healthy", "Current", "Disabled", "No releases"}
480
+ review = sum(1 for view in views if view.status not in pending)
481
+ cached = sum(
482
+ 1
483
+ for view in views
484
+ if "cached" in view.statuses and "stale" not in view.statuses
485
+ )
486
+ percent = 0 if total == 0 else round(cached / total * 100)
487
+ return f"Repositories {total} Need review {review} Cache fresh {percent}%"