arctiq-cli 0.2.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.
arctiq_cli/tui/app.py ADDED
@@ -0,0 +1,1208 @@
1
+ """The TUI (ADR 0027; docs/ui-mockups/tui): Home, Repositories (an artefact beside its folder),
2
+ Checks, Partners, one partnership, Who can see this, and the command palette.
3
+
4
+ Everything comes through `Source` (`/api/v1` only). Each screen loads in a worker thread, so the
5
+ terminal never waits on the network; `r` loads again, and Home's activity refreshes itself.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import datetime as dt
11
+ import webbrowser
12
+ from collections.abc import Callable
13
+ from functools import partial
14
+ from pathlib import Path
15
+ from typing import Any
16
+
17
+ from rich.text import Text
18
+ from textual import work
19
+ from textual.app import App, ComposeResult
20
+ from textual.binding import Binding
21
+ from textual.command import DiscoveryHit, Hit, Hits, Provider
22
+ from textual.containers import Horizontal, Vertical, VerticalScroll
23
+ from textual.screen import ModalScreen, Screen
24
+ from textual.theme import Theme
25
+ from textual.widgets import (
26
+ DataTable,
27
+ Footer,
28
+ OptionList,
29
+ ProgressBar,
30
+ RichLog,
31
+ Sparkline,
32
+ Static,
33
+ Tree,
34
+ )
35
+ from textual.widgets.option_list import Option
36
+
37
+ from arctiq_cli.client import ApiError
38
+ from arctiq_cli.tui import draw, folder
39
+ from arctiq_cli.tui.draw import ACC, AMBER, INK, INK2, MUTE, OK, RED, T, clip, lines
40
+ from arctiq_cli.tui.source import JSON, Source
41
+
42
+ THEME = Theme(
43
+ name="arctiq",
44
+ primary="#d9d9d6",
45
+ secondary=INK2,
46
+ accent=ACC,
47
+ foreground=INK,
48
+ background="#0b0b0b",
49
+ surface="#111111",
50
+ panel="#181818",
51
+ success=OK,
52
+ warning=AMBER,
53
+ error=RED,
54
+ dark=True,
55
+ )
56
+ TABS = (("1", "Home", "home"), ("2", "Repositories", "repos"), ("3", "Checks", "checks"),
57
+ ("4", "Partners", "partners")) # fmt: skip
58
+ REFRESH_SECONDS = 30
59
+ SIDE = 37 # characters a line in Home's side column can hold
60
+ TONE = {"acc": ACC, "red": RED, "ink": INK, "amber": AMBER}
61
+ STATE_WORDS = {
62
+ "draft": "draft", "submitted": "submitted", "validating": "submitted",
63
+ "needs_review": "waiting for review", "approved": "approved", "ingested": "approved",
64
+ "live": "live in Discover", "revision_requested": "sent back", "rejected": "rejected",
65
+ } # fmt: skip
66
+ MARK = {
67
+ folder.SAME: ("✓ same", OK), folder.CHANGED: ("● changed", AMBER), folder.NEW: ("+ to add", ACC),
68
+ folder.CLASH: ("! two files share this name", RED), folder.MISSING: ("only in ARCTIQ", INK2),
69
+ folder.OTHER: ("", MUTE),
70
+ } # fmt: skip
71
+
72
+
73
+ def panel(title: str, *children, **kw) -> Vertical:
74
+ v = Vertical(*children, classes="panel " + kw.pop("classes", ""), **kw)
75
+ v.border_title = title
76
+ return v
77
+
78
+
79
+ def ago(at: dt.datetime | None, now: dt.datetime | None = None) -> str:
80
+ if at is None:
81
+ return ""
82
+ now = now or dt.datetime.now(dt.UTC)
83
+ seconds = (now - at).total_seconds()
84
+ if seconds < 3600 * 20 and at.date() == now.date():
85
+ return f"{at:%H:%M}"
86
+ if (now.date() - at.date()).days == 1:
87
+ return "yesterday"
88
+ return draw.short(at)
89
+
90
+
91
+ # ====================================================================== the frame
92
+ class TopBar(Horizontal):
93
+ def __init__(self, active: str) -> None:
94
+ super().__init__(classes="top")
95
+ self.active = active
96
+
97
+ def compose(self) -> ComposeResult:
98
+ yield Static(id="top-left")
99
+ yield Static(id="top-right")
100
+
101
+ def on_mount(self) -> None:
102
+ self.refresh_text()
103
+
104
+ def refresh_text(self) -> None:
105
+ app = self.app
106
+ assert isinstance(app, ArctiqApp)
107
+ left = T((" ARCTIQ ", "bold #0b0b0b on #e6e6e3"), (f" {app.org_name} ", f"bold {INK}"))
108
+ if app.org_role:
109
+ left.append(f"{app.org_role}", style=INK2)
110
+ left.append(" ")
111
+ for key, name, _ in TABS:
112
+ if name == self.active:
113
+ left.append(f" {key} {name} ", style=f"bold #0b0b0b on {INK}")
114
+ else:
115
+ left.append(f" {key} ", style=MUTE)
116
+ left.append(f"{name} ", style=INK2)
117
+ left.append(" ")
118
+ self.query_one("#top-left", Static).update(left)
119
+ right = T(("● ", OK if app.signed_in else RED), (app.server_host, INK2))
120
+ if app.person:
121
+ right.append(f" · {app.person} ", style=INK2)
122
+ self.query_one("#top-right", Static).update(right)
123
+
124
+
125
+ class Base(Screen):
126
+ """A screen that loads its data in a worker and shows it when it arrives."""
127
+
128
+ TAB = "Home"
129
+ BINDINGS = [Binding("r", "reload", "Reload")]
130
+
131
+ @property
132
+ def arctiq(self) -> ArctiqApp:
133
+ app = self.app
134
+ assert isinstance(app, ArctiqApp)
135
+ return app
136
+
137
+ @property
138
+ def source(self) -> Source:
139
+ return self.arctiq.source
140
+
141
+ def on_mount(self) -> None:
142
+ self.action_reload()
143
+
144
+ def on_screen_resume(self) -> None:
145
+ for bar in self.query(TopBar):
146
+ bar.refresh_text()
147
+
148
+ def action_reload(self) -> None:
149
+ self.load()
150
+
151
+ @work(thread=True, exclusive=True, group="load")
152
+ def load(self) -> None:
153
+ try:
154
+ data = self.gather()
155
+ except ApiError as exc:
156
+ self.app.call_from_thread(self.arctiq.failed, exc)
157
+ return
158
+ self.app.call_from_thread(self.show, data)
159
+
160
+ def gather(self) -> Any: # in the worker thread
161
+ return None
162
+
163
+ def show(self, data: Any) -> None: # back on the screen
164
+ del data
165
+
166
+ def commands(self) -> list[tuple[str, str, Callable[[], object]]]:
167
+ """This screen's lines in the command palette: (name, help, action)."""
168
+ return []
169
+
170
+
171
+ # ====================================================================== 1. home
172
+ class HomeScreen(Base):
173
+ TAB = "Home"
174
+ BINDINGS = [
175
+ Binding("enter", "open_repo", "Open repository"),
176
+ Binding("o", "browser", "Open in browser"),
177
+ Binding("r", "reload", "Reload"),
178
+ ]
179
+
180
+ def compose(self) -> ComposeResult:
181
+ yield TopBar("Home")
182
+ with Horizontal(classes="body"):
183
+ with Vertical(classes="main"):
184
+ yield panel("Repositories", DataTable(id="repos", cursor_type="row"),
185
+ id="repos-panel") # fmt: skip
186
+ yield panel("Activity · what happened in your repositories, newest first",
187
+ RichLog(id="live", wrap=False), id="live-panel") # fmt: skip
188
+ with Vertical(classes="side"):
189
+ yield panel("Needs you", Static(id="needs"), id="needs-panel")
190
+ yield panel("Partners", Static(id="mini"), id="mini-panel")
191
+ yield Footer()
192
+
193
+ def on_mount(self) -> None:
194
+ table = self.query_one("#repos", DataTable)
195
+ table.add_columns("Repository", "GitHub", "Artefacts", "Last ARCTIQ check", "Last change")
196
+ super().on_mount()
197
+ self.set_interval(REFRESH_SECONDS, self.load_activity)
198
+
199
+ def gather(self) -> JSON:
200
+ repos = self.source.repositories()
201
+ status = {}
202
+ for r in repos[:12]:
203
+ try:
204
+ status[r["slug"]] = self.source.status(r["slug"])
205
+ except ApiError:
206
+ status[r["slug"]] = {}
207
+ return {"repos": repos, "status": status, "activity": self.source.activity(60),
208
+ "partners": self.source.partners()} # fmt: skip
209
+
210
+ @work(thread=True, exclusive=True, group="activity")
211
+ def load_activity(self) -> None:
212
+ try:
213
+ events = self.source.activity(60)
214
+ except ApiError:
215
+ return
216
+ self.app.call_from_thread(self.show_activity, events)
217
+
218
+ def show(self, data: JSON) -> None:
219
+ self.arctiq.repositories = data["repos"]
220
+ self.arctiq.partner_cache = data["partners"]
221
+ latest: dict[str, JSON] = {}
222
+ for e in data["activity"]:
223
+ latest.setdefault(e["repository"], e)
224
+ table = self.query_one("#repos", DataTable)
225
+ table.clear()
226
+ for r in data["repos"]:
227
+ st = data["status"].get(r["slug"], {})
228
+ drafts = sum(1 for a in st.get("artefacts", []) if a.get("state") == "draft")
229
+ count = f"{r.get('artefacts', 0)}" + (f" ({drafts} draft)" if drafts else "")
230
+ check = st.get("last_check")
231
+ if check:
232
+ notes = check.get("notes", 0)
233
+ last = T(("! ", AMBER) if notes else ("✓ ", OK),
234
+ f"PR #{check['pull_request']} · " + (f"{notes} to look at" if notes else "all fine")) # fmt: skip
235
+ else:
236
+ last = T(("–", MUTE))
237
+ change = latest.get(r["slug"])
238
+ when = (
239
+ T((f"{ago(draw.when(change['at']))} · {change['who']}", INK2))
240
+ if change
241
+ else T(("–", MUTE))
242
+ )
243
+ github = st.get("github") or None
244
+ table.add_row(T((r["name"], f"bold {INK}")), github or T(("not linked", MUTE)), count,
245
+ last, when, key=r["slug"]) # fmt: skip
246
+ self.show_activity(data["activity"])
247
+ self.query_one("#needs", Static).update(self._needs(data))
248
+ self.query_one("#mini", Static).update(self._mini(data["partners"]))
249
+
250
+ def show_activity(self, events: list[JSON]) -> None:
251
+ log = self.query_one("#live", RichLog)
252
+ log.clear()
253
+ for e in events:
254
+ how = ""
255
+ if e.get("agent"):
256
+ how = f" · {e['agent']}"
257
+ elif e.get("program"):
258
+ how = f" · {e['program']}"
259
+ text = e["text"] + (f" {e['subject']}" if e.get("subject") else "")
260
+ log.write(T((f"{ago(draw.when(e['at'])):<11}", MUTE), (f"{e['who'][:22]:<24}", INK2),
261
+ (f"{e['repository'][:18]:<20}", MUTE), (text, INK), (how, ACC))) # fmt: skip
262
+ if not events:
263
+ log.write(T(("Nothing has happened in your repositories yet.", MUTE)))
264
+
265
+ def _needs(self, data: JSON) -> Text:
266
+ rows: list[Text | str] = []
267
+ for n in (data["partners"] or {}).get("needs", [])[:6]:
268
+ colour = TONE.get(n["tone"], INK)
269
+ rows += [T(("▌", colour), (" " + clip(n["title"], SIDE), f"bold {RED if n['tone'] == 'red' else INK}")),
270
+ T(("▌", colour), (" " + clip(n["text"], SIDE - 2), INK2)), ""] # fmt: skip
271
+ for slug, st in data["status"].items():
272
+ check = (st or {}).get("last_check")
273
+ if check and check.get("notes"):
274
+ rows += [T(("▌", AMBER), (" " + clip(f"PR #{check['pull_request']} in {slug}", SIDE), f"bold {INK}")),
275
+ T(("▌", AMBER), (f" {check['notes']} to look at · press 3", INK2)), ""] # fmt: skip
276
+ return lines(*rows[:-1]) if rows else T(("Nothing waits for you.", MUTE))
277
+
278
+ def _mini(self, partners: JSON) -> Text:
279
+ rows: list[Text | str] = []
280
+ for p in (partners or {}).get("partnerships", [])[:6]:
281
+ colour = RED if p["state"] == "ending" else (INK if p["state"] == "active" else MUTE)
282
+ out = sum(1 for r in p["you_share"] if r["live"])
283
+ into = sum(1 for r in p["they_share"] if r["live"])
284
+ step = p["step"] if p["state"] in draw.LIVE else 0
285
+ lit = max(0, min(4, step))
286
+ rows.append(T((f"{clip(p['partner'], 20):<21}", INK), ("━" * lit, colour), ("━" * (4 - lit), draw.LINE),
287
+ (f" {step} · {draw.SHORT[step]}" if step in draw.SHORT else "", colour))) # fmt: skip
288
+ tail = (f"ends in {p['days_left']} days" if p["state"] == "ending"
289
+ else p["label"].lower()) # fmt: skip
290
+ rows.append(T((f" {out} out · {into} in · ", MUTE),
291
+ (clip(tail, SIDE - 18), RED if p["state"] == "ending" else MUTE))) # fmt: skip
292
+ if not rows:
293
+ return T(("No partners yet.", MUTE))
294
+ return lines(*rows, "", T(("press 4 for the full picture", MUTE)))
295
+
296
+ def on_data_table_row_selected(self, event: DataTable.RowSelected) -> None:
297
+ if event.data_table.id == "repos" and event.row_key.value:
298
+ self.arctiq.open_repo(str(event.row_key.value))
299
+
300
+ def action_open_repo(self) -> None:
301
+ table = self.query_one("#repos", DataTable)
302
+ if table.row_count:
303
+ slug = table.coordinate_to_cell_key(table.cursor_coordinate).row_key.value
304
+ self.arctiq.open_repo(str(slug))
305
+
306
+ def action_browser(self) -> None:
307
+ self.arctiq.open_page("")
308
+
309
+
310
+ # ====================================================================== 2. an artefact
311
+ class RepoScreen(Base):
312
+ TAB = "Repositories"
313
+ BINDINGS = [
314
+ Binding("u", "upload", "Upload changed"),
315
+ Binding("a", "toggle_add", "Add / don't add"),
316
+ Binding("o", "browser", "Open in browser"),
317
+ Binding("r", "reload", "Reload"),
318
+ ]
319
+
320
+ def __init__(self) -> None:
321
+ super().__init__()
322
+ self.slug: str | None = None
323
+ self.artefact: JSON | None = None
324
+ self.entries: list[folder.Entry] = []
325
+ self.chosen: set[str] = set()
326
+ self.files: list[JSON] = []
327
+
328
+ def compose(self) -> ComposeResult:
329
+ yield TopBar("Repositories")
330
+ yield Static(id="crumb", classes="crumb")
331
+ with Horizontal(classes="body"):
332
+ yield panel("This folder ↔ the artefact", Tree("folder", id="tree"), id="tree-panel")
333
+ with VerticalScroll(classes="main"):
334
+ yield panel("Artefacts", OptionList(id="artefacts"), id="artefacts-panel")
335
+ yield panel(
336
+ "Uploading",
337
+ Vertical(id="uploads"),
338
+ Static(id="upload-note"),
339
+ id="uploads-panel",
340
+ )
341
+ with Horizontal(id="mid"):
342
+ yield panel(
343
+ "Scores · update as you work", Static(id="scores"), id="scores-panel"
344
+ )
345
+ yield panel(
346
+ "Readiness, part by part", Static(id="readiness"), id="readiness-panel"
347
+ )
348
+ yield panel(
349
+ "Pinned code · evidence that doesn't change",
350
+ Static(id="pins"),
351
+ id="pins-panel",
352
+ )
353
+ yield panel("History of this artefact · who did what, and how", Static(id="history"),
354
+ id="history-panel") # fmt: skip
355
+ yield Footer()
356
+
357
+ @property
358
+ def here(self) -> Path | None:
359
+ """The linked folder, when it is this repository's."""
360
+ a = self.arctiq
361
+ return a.folder if a.folder is not None and a.linked_repo == self.slug else None
362
+
363
+ def gather(self) -> JSON:
364
+ repos = self.arctiq.repositories or self.source.repositories()
365
+ slug = self.slug or self.arctiq.linked_repo or (repos[0]["slug"] if repos else None)
366
+ if slug is None:
367
+ return {"slug": None, "repos": repos}
368
+ artefacts = self.source.artefacts(slug)
369
+ chosen = self.artefact if self.artefact and self.slug == slug else None
370
+ if chosen is None and artefacts:
371
+ chosen = next((a for a in artefacts if a.get("state") == "draft"), artefacts[0])
372
+ if chosen is not None:
373
+ chosen = next((a for a in artefacts if a["id"] == chosen["id"]), chosen)
374
+ out: JSON = {"slug": slug, "artefacts": artefacts, "artefact": chosen, "repos": repos}
375
+ if chosen is not None:
376
+ out["files"] = self.source.files(slug, chosen["id"])
377
+ out["summary"] = self.source.summary(slug, chosen["id"])
378
+ return out
379
+
380
+ def show(self, data: JSON) -> None:
381
+ self.slug = data["slug"]
382
+ self.arctiq.repositories = self.arctiq.repositories or data.get("repos", [])
383
+ crumb = self.query_one("#crumb", Static)
384
+ if self.slug is None:
385
+ crumb.update(T((" No repositories yet. Make one on the pages, or with the CLI.", MUTE)))
386
+ return
387
+ self.artefact = data.get("artefact")
388
+ self.files = data.get("files", [])
389
+ options = self.query_one("#artefacts", OptionList)
390
+ options.clear_options()
391
+ for a in data["artefacts"]:
392
+ title = a.get("record", {}).get("problem") or "Untitled draft"
393
+ state = STATE_WORDS.get(a.get("state", ""), a.get("state", ""))
394
+ options.add_option(Option(T((title[:60], INK), (f" {state}", INK2)), id=a["id"]))
395
+ if self.artefact is not None:
396
+ idx = next(
397
+ (i for i, a in enumerate(data["artefacts"]) if a["id"] == self.artefact["id"]), None
398
+ )
399
+ if idx is not None:
400
+ options.highlighted = idx
401
+ a = self.artefact
402
+ linked = f"linked to {self.here.name}/" if self.here else "no linked folder here"
403
+ if a is None:
404
+ crumb.update(
405
+ T((f" {self.slug} ", f"bold {INK}"), ("› no artefacts yet · arctiq new", MUTE))
406
+ )
407
+ else:
408
+ title = a.get("record", {}).get("problem") or "Untitled draft"
409
+ state = a.get("state", "")
410
+ crumb.update(T((f" {self.slug} ", INK2), ("›", MUTE), (f" {title} ", f"bold {INK}"),
411
+ (f" {STATE_WORDS.get(state, state).upper()} ", f"bold {AMBER if state == 'draft' else OK}"),
412
+ (f"· {len(self.files)} file{'s' if len(self.files) != 1 else ''} ", INK2),
413
+ (linked, MUTE))) # fmt: skip
414
+ self._tree()
415
+ s = data.get("summary") or {}
416
+ scores = s.get("scores", [])
417
+ self.query_one("#scores", Static).update(
418
+ lines(*[T((f"{x['label']:<20}", INK2)) + draw.bar(x["score"]) for x in scores])
419
+ if scores
420
+ else T(("No scores yet.", MUTE)) # fmt: skip
421
+ )
422
+ ready = next((x for x in scores if x["key"] == "readiness"), None)
423
+ self.query_one("#readiness", Static).update(
424
+ lines(
425
+ *[
426
+ T(
427
+ (
428
+ "✓ " if p["earned"] >= p["points"] else "✗ ",
429
+ OK if p["earned"] >= p["points"] else RED,
430
+ ),
431
+ (f"{clip(p['label'], 38):<40}", INK),
432
+ (
433
+ f"{p['earned']}/{p['points']}"
434
+ if p["earned"] < p["points"]
435
+ else f"{p['points']}",
436
+ INK2,
437
+ ),
438
+ )
439
+ for p in ready["parts"]
440
+ ]
441
+ ) # fmt: skip
442
+ if ready
443
+ else T(("–", MUTE))
444
+ )
445
+ pins = s.get("pins", [])
446
+ self.query_one("#pins", Static).update(
447
+ lines(
448
+ *[
449
+ T(
450
+ ("● ", INK),
451
+ (p["github"], INK),
452
+ (f" @ {p['commit'][:7]}", ACC),
453
+ (
454
+ (" release · " if p["release"] else " at submission · ")
455
+ + draw.short(draw.when(p["pinned_at"]), True)
456
+ + (" · timestamped (RFC 3161)" if p.get("timestamped_at") else ""),
457
+ MUTE,
458
+ ),
459
+ )
460
+ for p in pins
461
+ ]
462
+ ) # fmt: skip
463
+ if pins
464
+ else T(
465
+ (
466
+ "Nothing pinned yet: code is pinned when you submit, and `arctiq pin` adds a release.",
467
+ MUTE,
468
+ )
469
+ )
470
+ )
471
+ hist = s.get("history", [])
472
+ self.query_one("#history", Static).update(
473
+ lines(
474
+ *[
475
+ T(
476
+ (f"{ago(draw.when(h['at'])):<11}", MUTE),
477
+ (f"{h['who'][:22]:<24}", INK),
478
+ (
479
+ f"{clip(h['text'] + (' ' + h['subject'] if h.get('subject') else ''), 58):<60}",
480
+ INK2,
481
+ ),
482
+ (
483
+ f"{h['agent'] or h['program'] or 'the pages'}"
484
+ if h.get("origin") == "api"
485
+ else "the pages",
486
+ ACC if h.get("origin") == "api" else MUTE,
487
+ ),
488
+ )
489
+ for h in hist[:8]
490
+ ]
491
+ ) # fmt: skip
492
+ if hist
493
+ else T(("–", MUTE))
494
+ )
495
+
496
+ def _tree(self) -> None:
497
+ tree = self.query_one("#tree", Tree)
498
+ tree.clear()
499
+ here = self.here
500
+ if here is None:
501
+ tree.root.set_label(T(("the artefact's files", INK)))
502
+ for f in self.files:
503
+ tree.root.add_leaf(T((f"{f['filename'][:30]:<32}", INK), (draw.size(f["size_bytes"]), MUTE)),
504
+ data=None) # fmt: skip
505
+ if not self.files:
506
+ tree.root.add_leaf(T(("no files yet", MUTE)))
507
+ tree.root.add_leaf(
508
+ T(("Run `arctiq tui` in the folder linked to this repository", MUTE))
509
+ )
510
+ tree.root.add_leaf(T(("to see it beside the artefact and upload from it.", MUTE)))
511
+ tree.root.expand()
512
+ return
513
+ self.entries = folder.compare(here, self.files, self.chosen)
514
+ tree.root.set_label(T((here.name + "/", f"bold {INK}")))
515
+ nodes: dict[str, Any] = {"": tree.root}
516
+ held = {
517
+ e.path.rsplit("/", 1)[0]
518
+ for e in self.entries
519
+ if e.state != folder.OTHER and "/" in e.path
520
+ }
521
+ for e in self.entries:
522
+ if e.state == folder.MISSING:
523
+ continue
524
+ parent = ""
525
+ for piece in e.path.split("/")[:-1]:
526
+ key = f"{parent}/{piece}" if parent else piece
527
+ if key not in nodes:
528
+ opened = any(h == key or h.startswith(key + "/") for h in held)
529
+ nodes[key] = nodes[parent].add(T((piece + "/", INK)), expand=opened)
530
+ parent = key
531
+ mark, colour = MARK[e.state]
532
+ label = T(
533
+ (f"{e.name[:30]:<32}", INK if e.state != folder.OTHER else INK2), (mark, colour)
534
+ )
535
+ nodes[parent].add_leaf(label, data=e.path)
536
+ for e in self.entries:
537
+ if e.state == folder.MISSING:
538
+ tree.root.add_leaf(T((f"{e.name[:30]:<32}", MUTE), MARK[e.state]), data=None)
539
+ tree.root.expand()
540
+ waiting = folder.to_send(self.entries)
541
+ note = (f"{len(waiting)} to upload: press u" if waiting
542
+ else "Nothing changed. Highlight a file and press a to add it.") # fmt: skip
543
+ self.query_one("#upload-note", Static).update(T((note, INK2 if waiting else MUTE)))
544
+
545
+ def on_option_list_option_selected(self, event: OptionList.OptionSelected) -> None:
546
+ if event.option_list.id == "artefacts":
547
+ picked = event.option.id
548
+ self.artefact = {"id": picked}
549
+ self.load()
550
+
551
+ def action_toggle_add(self) -> None:
552
+ node = self.query_one("#tree", Tree).cursor_node
553
+ path = node.data if node is not None else None
554
+ if not path or self.here is None:
555
+ return
556
+ entry = next((e for e in self.entries if e.path == path), None)
557
+ if entry is None or entry.state not in (folder.OTHER, folder.NEW):
558
+ self.notify(
559
+ "Only a file the artefact doesn't hold yet can be added.", severity="warning"
560
+ )
561
+ return
562
+ self.chosen.symmetric_difference_update({path})
563
+ self._tree()
564
+
565
+ def action_upload(self) -> None:
566
+ if self.here is None or self.artefact is None or self.slug is None:
567
+ self.notify(
568
+ "Open the TUI in the folder linked to this repository to upload.",
569
+ severity="warning",
570
+ )
571
+ return
572
+ waiting = folder.to_send(self.entries)
573
+ if not waiting:
574
+ self.notify("Nothing to upload: every file the artefact holds is the same here.")
575
+ return
576
+ box = self.query_one("#uploads", Vertical)
577
+ box.remove_children()
578
+ bars = {}
579
+ for e in waiting:
580
+ box.mount(Static(T((e.name, INK), (f" {draw.size(e.size)}", MUTE))))
581
+ bar = ProgressBar(total=max(e.size or 1, 1), show_eta=False)
582
+ box.mount(bar)
583
+ bars[e.path] = bar
584
+ self.send(waiting, bars)
585
+
586
+ @work(thread=True, exclusive=True, group="upload")
587
+ def send(self, waiting: list[folder.Entry], bars: dict[str, ProgressBar]) -> None:
588
+ assert self.here is not None and self.artefact is not None and self.slug is not None
589
+ done, failed = 0, []
590
+ for e in waiting:
591
+ bar = bars[e.path]
592
+ data = (self.here / e.path).read_bytes()
593
+
594
+ def step(sent: int, total: int, bar: ProgressBar = bar) -> None:
595
+ self.app.call_from_thread(bar.update, total=total, progress=sent)
596
+
597
+ # A changed file replaces the one the artefact holds: the platform takes one file per
598
+ # name, so the old copy comes off first (it stays in the file history).
599
+ replacing = e.state == folder.CHANGED and e.stored is not None
600
+ try:
601
+ if replacing:
602
+ assert e.stored is not None
603
+ self.source.remove(self.slug, self.artefact["id"], str(e.stored["id"]))
604
+ except ApiError as exc:
605
+ failed.append(f"{e.name}: not replaced: {exc.detail}")
606
+ continue
607
+ try:
608
+ self.source.upload(self.slug, self.artefact["id"], e.name, data, step)
609
+ done += 1
610
+ except ApiError as exc:
611
+ failed.append(
612
+ f"{e.name}: {exc.detail}"
613
+ + (" The old copy was taken off; bring it back from the file history on the "
614
+ "pages." if replacing else "")
615
+ ) # fmt: skip
616
+ self.app.call_from_thread(self._sent, done, failed)
617
+
618
+ def _sent(self, done: int, failed: list[str]) -> None:
619
+ self.chosen.clear()
620
+ if failed:
621
+ self.notify("\n".join(failed), title="Not uploaded", severity="error", timeout=12)
622
+ if done:
623
+ self.notify(f"Uploaded {done} file{'s' if done != 1 else ''}.")
624
+ self.load()
625
+
626
+ def action_browser(self) -> None:
627
+ if self.artefact and self.artefact.get("web_url"):
628
+ self.arctiq.opener(self.artefact["web_url"])
629
+ elif self.slug and self.artefact:
630
+ self.arctiq.open_page(f"artefacts/{self.artefact['id']}")
631
+ elif self.slug:
632
+ self.arctiq.open_page(f"repos/{self.slug}")
633
+
634
+ def commands(self) -> list[tuple[str, str, Callable[[], object]]]:
635
+ out: list[tuple[str, str, Callable[[], object]]] = [
636
+ (
637
+ "Upload changed files",
638
+ "changed files, and the ones picked with a",
639
+ self.action_upload,
640
+ ),
641
+ ]
642
+ for r in self.arctiq.repositories:
643
+ out.append(
644
+ (
645
+ f"Open repository: {r['name']}",
646
+ r["slug"],
647
+ partial(self.arctiq.open_repo, r["slug"]),
648
+ )
649
+ )
650
+ return out
651
+
652
+
653
+ # ====================================================================== 3. checks
654
+ class ChecksScreen(Base):
655
+ TAB = "Checks"
656
+ BINDINGS = [
657
+ Binding("g", "github", "Open on GitHub"),
658
+ Binding("r", "reload", "Reload"),
659
+ ]
660
+
661
+ def __init__(self) -> None:
662
+ super().__init__()
663
+ self.checks: list[JSON] = []
664
+
665
+ def compose(self) -> ComposeResult:
666
+ yield TopBar("Checks")
667
+ yield Static(T((" Pull requests ARCTIQ checked", f"bold {INK}"),
668
+ (" · each shows on GitHub as the ", INK2), ("ARCTIQ", f"bold {INK}"),
669
+ (" check · rows: linked, pinned, commits, licences", INK2)), classes="crumb") # fmt: skip
670
+ with Vertical(classes="body-v"):
671
+ yield panel("Pull requests", DataTable(id="prs", cursor_type="row"), id="prs-panel")
672
+ yield panel("The check", Static(id="detail"), id="detail-panel")
673
+ yield Footer()
674
+
675
+ def on_mount(self) -> None:
676
+ self.query_one("#prs", DataTable).add_columns(
677
+ "Repository",
678
+ "GitHub",
679
+ "PR",
680
+ "Linked",
681
+ "Pinned",
682
+ "Commits",
683
+ "Licences",
684
+ "Result",
685
+ "When",
686
+ )
687
+ super().on_mount()
688
+
689
+ def gather(self) -> list[JSON]:
690
+ return self.source.checks()
691
+
692
+ def show(self, data: list[JSON]) -> None:
693
+ self.checks = data
694
+ table = self.query_one("#prs", DataTable)
695
+ table.clear()
696
+ for c in data:
697
+ marks = {r["key"]: r["status"] for r in c["rows"]}
698
+ cell = [T(("✓", OK)) if marks.get(k) == "pass" else (T(("!", f"bold {AMBER}")) if marks.get(k) == "note"
699
+ else T(("–", MUTE))) for k in ("linked", "pinned", "commits", "licences")] # fmt: skip
700
+ notes = sum(1 for v in marks.values() if v == "note")
701
+ result = T((f"{notes} to look at", AMBER)) if notes else T(("all fine", OK))
702
+ table.add_row(c.get("repository") or "–", c["github"], f"#{c['number']}", *cell, result,
703
+ ago(draw.when(c["checked_at"])), key=c["id"]) # fmt: skip
704
+ if data: # the first one's words, without waiting for the cursor to move
705
+ self.load_one(str(data[0]["id"]))
706
+ else:
707
+ self.query_one("#detail", Static).update(T((
708
+ "No checks yet. Install the ARCTIQ GitHub app and link a repository: every pull request "
709
+ "is checked.", MUTE))) # fmt: skip
710
+
711
+ def on_data_table_row_highlighted(self, event: DataTable.RowHighlighted) -> None:
712
+ if event.row_key is not None and event.row_key.value:
713
+ self.load_one(str(event.row_key.value))
714
+
715
+ @work(thread=True, exclusive=True, group="one")
716
+ def load_one(self, check_id: str) -> None:
717
+ try:
718
+ detail = self.source.check(check_id)
719
+ except ApiError as exc:
720
+ detail = {"error": exc.detail}
721
+ self.app.call_from_thread(self.show_one, detail)
722
+
723
+ def show_one(self, c: JSON) -> None:
724
+ box = self.query_one("#detail-panel", Vertical)
725
+ out = self.query_one("#detail", Static)
726
+ if "error" in c:
727
+ out.update(T((c["error"], RED)))
728
+ return
729
+ box.border_title = (f"PR #{c['number']} · {c.get('title') or 'title on GitHub'} · {c['github']}"
730
+ + (f" · by {c['author']}" if c.get("author") else "")) # fmt: skip
731
+ rows: list[Text | str] = []
732
+ for r in c["rows"]:
733
+ ok = r["status"] == "pass"
734
+ rows.append(
735
+ T(
736
+ ("✓ " if ok else "! ", OK if ok else AMBER),
737
+ (r["title"], f"bold {INK if ok else AMBER}"),
738
+ )
739
+ )
740
+ rows.append(T((" " + (r.get("text") or "(GitHub has the words)"), INK2)))
741
+ rows.append("")
742
+ if not c.get("from_github"):
743
+ rows.append(T((f"Not from GitHub just now: {c.get('why_not') or 'unknown'}", MUTE)))
744
+ rows.append(
745
+ T(("Report only unless .arctiq.yml says otherwise: notes don't block the merge.", MUTE))
746
+ )
747
+ out.update(lines(*rows))
748
+
749
+ def action_github(self) -> None:
750
+ table = self.query_one("#prs", DataTable)
751
+ if not table.row_count:
752
+ return
753
+ key = table.coordinate_to_cell_key(table.cursor_coordinate).row_key.value
754
+ found = next((c for c in self.checks if c["id"] == key), None)
755
+ if found:
756
+ self.arctiq.opener(found["url"])
757
+
758
+
759
+ # ====================================================================== 4. partners
760
+ class PartnersScreen(Base):
761
+ TAB = "Partners"
762
+ BINDINGS = [
763
+ Binding("enter", "open", "Open partnership"),
764
+ Binding("o", "browser", "Open in browser"),
765
+ Binding("r", "reload", "Reload"),
766
+ ]
767
+
768
+ def __init__(self) -> None:
769
+ super().__init__()
770
+ self.data: JSON = {}
771
+
772
+ def compose(self) -> ComposeResult:
773
+ yield TopBar("Partners")
774
+ yield Static(id="tiles", classes="crumb")
775
+ with VerticalScroll(classes="body-v"):
776
+ yield panel(
777
+ "Who you work with, and what moves each way", Static(id="flow"), id="flow-panel"
778
+ )
779
+ with Horizontal(id="lower"):
780
+ yield panel("Agreements · enter to open", DataTable(id="agreements", cursor_type="row"),
781
+ id="agreements-panel") # fmt: skip
782
+ yield panel("Needs you", Static(id="needs"), id="needs-panel")
783
+ yield Horizontal(id="sparks")
784
+ yield Footer()
785
+
786
+ def on_mount(self) -> None:
787
+ self.query_one("#agreements", DataTable).add_columns(
788
+ "Partner", "Agreement", "Level", "Uses", "Ends"
789
+ )
790
+ super().on_mount()
791
+
792
+ def gather(self) -> JSON:
793
+ data = self.source.partners()
794
+ series = []
795
+ for p in [p for p in data.get("partnerships", []) if p["state"] in draw.LIVE][:3]:
796
+ detail = self.source.partnership(p["agreement_id"], limit=500)
797
+ series.append((p, draw.per_day(detail.get("uses", []), self.arctiq.today)))
798
+ data["series"] = series
799
+ return data
800
+
801
+ def show(self, data: JSON) -> None:
802
+ self.data = data
803
+ self.arctiq.partner_cache = data
804
+ t = data.get("tiles", {})
805
+ tiles = T((" Partners", f"bold {INK}"),
806
+ (f" · {t.get('active', 0)} active, {t.get('agreeing', 0)} being agreed · "
807
+ f"{t.get('you_share', 0)} resources out, {t.get('they_share', 0)} in · "
808
+ f"{t.get('uses_month', 0)} uses this month", INK2)) # fmt: skip
809
+ if t.get("ending"):
810
+ tiles.append(f" · {t['ending']} ending within 60 days", style=RED)
811
+ self.query_one("#tiles", Static).update(tiles)
812
+ parts = data.get("partnerships", [])
813
+ self.query_one("#flow", Static).update(draw.flow(parts))
814
+ table = self.query_one("#agreements", DataTable)
815
+ table.clear()
816
+ for p in parts:
817
+ ends = (
818
+ f"{draw.short(draw.day(p['ends_on']), True)}" if p.get("ends_on") else "no end date"
819
+ )
820
+ if p["state"] == "ended":
821
+ ends = f"ended {draw.short(draw.day(p.get('ended_on')), True)}"
822
+ table.add_row(T((p["partner"], f"bold {INK}")), T((p["label"], RED if p["state"] == "ending" else INK2)),
823
+ draw.level(p["step"]) if p["state"] in draw.LIVE else "–", str(p["uses_month"]),
824
+ T((ends, RED if p["state"] == "ending" else INK2)), key=p["agreement_id"]) # fmt: skip
825
+ needs = data.get("needs", [])
826
+ self.query_one("#needs", Static).update(
827
+ lines(
828
+ *[
829
+ T(
830
+ ("▌", TONE.get(n["tone"], INK)),
831
+ (f" {n['title']}", f"bold {RED if n['tone'] == 'red' else INK}"),
832
+ )
833
+ for n in needs
834
+ ]
835
+ ) # fmt: skip
836
+ if needs
837
+ else T(("Nothing waits for you.", MUTE))
838
+ )
839
+ sparks = self.query_one("#sparks", Horizontal)
840
+ sparks.remove_children()
841
+ for p, counts in data.get("series", []):
842
+ box = panel(f"{p['partner']} · questions a day, 30 days",
843
+ Sparkline(counts, summary_function=max),
844
+ Static(T((f"{sum(counts)} questions in 30 days", MUTE))), classes="spark") # fmt: skip
845
+ sparks.mount(box)
846
+
847
+ def on_data_table_row_selected(self, event: DataTable.RowSelected) -> None:
848
+ if event.data_table.id == "agreements" and event.row_key.value:
849
+ self.arctiq.push_screen(PartnershipScreen(str(event.row_key.value)))
850
+
851
+ def action_open(self) -> None:
852
+ table = self.query_one("#agreements", DataTable)
853
+ if table.row_count:
854
+ key = table.coordinate_to_cell_key(table.cursor_coordinate).row_key.value
855
+ self.arctiq.push_screen(PartnershipScreen(str(key)))
856
+
857
+ def action_browser(self) -> None:
858
+ self.arctiq.open_page("partners")
859
+
860
+ def commands(self) -> list[tuple[str, str, Callable[[], object]]]:
861
+ return [(f"Open partner: {p['partner']}", p["label"],
862
+ partial(self.arctiq.open_partnership, p["agreement_id"]))
863
+ for p in self.data.get("partnerships", [])] # fmt: skip
864
+
865
+
866
+ # ====================================================================== 5. one partnership
867
+ class PartnershipScreen(Base):
868
+ TAB = "Partners"
869
+ BINDINGS = [
870
+ Binding("w", "who", "Who can see this"),
871
+ Binding("o", "browser", "Open in browser"),
872
+ Binding("escape", "back", "Back"),
873
+ Binding("r", "reload", "Reload"),
874
+ ]
875
+
876
+ def __init__(self, agreement: str) -> None:
877
+ super().__init__()
878
+ self.agreement = agreement
879
+ self.detail: JSON = {}
880
+
881
+ def compose(self) -> ComposeResult:
882
+ yield TopBar("Partners")
883
+ yield Static(id="crumb", classes="crumb")
884
+ with VerticalScroll(classes="body-v"):
885
+ with Horizontal(id="sides"):
886
+ yield panel("You share → (w: who can see it)", OptionList(id="mine"), id="you")
887
+ yield panel("← They share", Static(id="theirs"), id="they")
888
+ yield panel("How it has gone", Static(id="gantt"), id="gantt-panel")
889
+ yield panel("Every use", DataTable(id="uses", cursor_type="row"), id="uses-panel")
890
+ yield Footer()
891
+
892
+ def on_mount(self) -> None:
893
+ self.query_one("#uses", DataTable).add_columns("When", "Who", "Did", "On", "How")
894
+ super().on_mount()
895
+
896
+ def gather(self) -> JSON:
897
+ return self.source.partnership(self.agreement)
898
+
899
+ @staticmethod
900
+ def _resource(r: JSON) -> Text:
901
+ use = (f"{r['questions']} question{'s' if r['questions'] != 1 else ''}"
902
+ + (f", {r['refused']} refused" if r["refused"] else "") if r["questions"] else
903
+ ("rows not uploaded yet" if r["step"] >= 3 and not r["rows_ready"] else "no questions yet")) # fmt: skip
904
+ return lines(T(("DATASET" + (f" · {r['version']}" if r.get("version") else ""), MUTE)),
905
+ T((r["name"], f"bold {INK}")), draw.ladder(r["step"]) + T((f" {draw.level(r['step'])}", f"bold {INK}")),
906
+ T((r["gets"], INK2)), T((use, ACC if use.startswith("rows") else INK2))) # fmt: skip
907
+
908
+ def show(self, p: JSON) -> None:
909
+ self.detail = p
910
+ state = p["label"].upper()
911
+ sub = (f"· {p['partner_kind']}{', verified' if p['partner_verified'] else ''} · “{p['title']}”"
912
+ + (f" · ends {draw.short(draw.day(p['ends_on']), True)}" if p.get("ends_on") else "")) # fmt: skip
913
+ self.query_one("#crumb", Static).update(T((" Partners ", INK2), ("›", MUTE), (f" {p['partner']} ", f"bold {INK}"),
914
+ (f" {state} ", f"bold {RED if p['state'] == 'ending' else OK}"), (sub, INK2))) # fmt: skip
915
+ mine = self.query_one("#mine", OptionList)
916
+ mine.clear_options()
917
+ for r in p["you_share"]:
918
+ mine.add_option(Option(lines(self._resource(r), ""), id=r["dataset_id"]))
919
+ if not p["you_share"]:
920
+ mine.add_option(
921
+ Option(T(("Nothing of yours is shared in this agreement.", MUTE)), disabled=True)
922
+ )
923
+ self.query_one("#they", Vertical).border_title = f"← {p['partner']} shares"
924
+ theirs = [self._resource(r) for r in p["they_share"]]
925
+ self.query_one("#theirs", Static).update(
926
+ lines(*[piece for t in theirs for piece in (t, "")])
927
+ if theirs
928
+ else T(("Nothing of theirs is shared.", MUTE))
929
+ )
930
+ self.query_one("#gantt", Static).update(draw.gantt(p, self.arctiq.today))
931
+ table = self.query_one("#uses", DataTable)
932
+ table.clear()
933
+ for u in p.get("uses", []):
934
+ who = u["who"] + (f" · {u['whose']}" if u.get("whose") else "")
935
+ did = u["did"] + (f" · {u['detail']}" if u.get("detail") else "")
936
+ table.add_row(ago(draw.when(u["at"])), clip(who, 40), clip(did, 56), clip(u["on"], 30),
937
+ u["how"]) # fmt: skip
938
+
939
+ def action_who(self) -> None:
940
+ mine = self.query_one("#mine", OptionList)
941
+ if not mine.option_count:
942
+ return
943
+ option = mine.get_option_at_index(mine.highlighted or 0)
944
+ r = next(
945
+ (r for r in self.detail.get("you_share", []) if r["dataset_id"] == option.id), None
946
+ )
947
+ if r is None or not r.get("repository"):
948
+ self.notify("Only your own datasets, in repositories you can open.", severity="warning")
949
+ return
950
+ self.arctiq.push_screen(WhoScreen(r["repository"], r["dataset_id"], r["name"]))
951
+
952
+ def action_back(self) -> None:
953
+ self.arctiq.pop_screen()
954
+
955
+ def action_browser(self) -> None:
956
+ if self.detail.get("url"):
957
+ self.arctiq.opener(self.detail["url"])
958
+
959
+
960
+ # ====================================================================== 6. who can see this
961
+ class WhoScreen(ModalScreen):
962
+ BINDINGS = [Binding("escape", "app.pop_screen", "Close")]
963
+
964
+ def __init__(self, repository: str, dataset: str, name: str) -> None:
965
+ super().__init__()
966
+ self.repository, self.dataset, self.name_ = repository, dataset, name
967
+
968
+ def compose(self) -> ComposeResult:
969
+ box = Vertical(Static(T((f"Who can see {self.name_} …", MUTE)), id="who-body"), id="who")
970
+ box.border_title = "Who can see this"
971
+ yield box
972
+ yield Footer()
973
+
974
+ def on_mount(self) -> None:
975
+ self.load()
976
+
977
+ @work(thread=True, exclusive=True)
978
+ def load(self) -> None:
979
+ app = self.app
980
+ assert isinstance(app, ArctiqApp)
981
+ try:
982
+ seen = app.source.access(self.repository, self.dataset)
983
+ except ApiError as exc:
984
+ self.app.call_from_thread(
985
+ self.query_one("#who-body", Static).update, T((exc.detail, RED))
986
+ )
987
+ return
988
+ self.app.call_from_thread(self.show, seen)
989
+
990
+ def show(self, seen: JSON) -> None:
991
+ offered = seen.get("offered") or 0
992
+ rows: list[Text | str] = [
993
+ T(
994
+ (seen["name"], f"bold {INK}"),
995
+ (" you offer it up to ", INK2),
996
+ (draw.level(offered) if offered else "nobody: not offered", f"bold {INK}"),
997
+ ), # fmt: skip
998
+ "",
999
+ ]
1000
+ viewers = list(seen.get("partners", [])) + (
1001
+ [seen["discover"]] if seen.get("discover") else []
1002
+ )
1003
+ for step in range(1, draw.TOP + 1):
1004
+ off = not offered or step > offered
1005
+ here = [v for v in viewers if v.get("step") == step]
1006
+ head = T((f" {step} {draw.LEVEL[step]:<16}", MUTE if off else INK), draw.ladder(step, offered, wide=False),
1007
+ (" ", "")) # fmt: skip
1008
+ if off:
1009
+ rows.append(head + T(("not offered", MUTE)))
1010
+ elif not here:
1011
+ rows.append(head + T(("–", MUTE)))
1012
+ for v in here:
1013
+ until = (
1014
+ f"until {draw.short(draw.day(v['until']), True)}"
1015
+ if v.get("until")
1016
+ else "while listed"
1017
+ )
1018
+ rows.append(head + T((f"{v['who'][:22]:<24}", f"bold {RED if v['soon'] else INK}"),
1019
+ (f"{v['through'][:34]:<36}", INK2), (until, RED if v["soon"] else INK2))) # fmt: skip
1020
+ team = seen.get("team", {})
1021
+ rows += ["", T((" Your team ", INK)) + draw.ladder(draw.TOP, wide=False)
1022
+ + T((" ", ""), (f"{team.get('note', ''):<58}", INK2), ("always", INK2)), ""] # fmt: skip
1023
+ if seen.get("pending"):
1024
+ rows.append(
1025
+ T(
1026
+ (
1027
+ f"{seen['pending']} agreement(s) being agreed would share it too, once both sign.",
1028
+ MUTE,
1029
+ )
1030
+ )
1031
+ )
1032
+ rows.append(T(("Raising a partner's level needs a new agreement, signed by both.", MUTE)))
1033
+ self.query_one("#who-body", Static).update(lines(*rows))
1034
+
1035
+
1036
+ # ====================================================================== the command palette
1037
+ class Commands(Provider):
1038
+ def _all(self) -> list[tuple[str, str, Callable[[], object]]]:
1039
+ app = self.app
1040
+ assert isinstance(app, ArctiqApp)
1041
+ out: list[tuple[str, str, Callable[[], object]]] = [
1042
+ (f"Go to {name}", f"key {key}", partial(app.go, screen)) for key, name, screen in TABS
1043
+ ]
1044
+ screen = self.screen
1045
+ if isinstance(screen, Base):
1046
+ out = screen.commands() + out
1047
+ out.append(("Reload this screen", "key r", screen.action_reload))
1048
+ out.append(
1049
+ ("Open this workspace in the browser", app.source.web(), lambda: app.open_page(""))
1050
+ )
1051
+ return out
1052
+
1053
+ async def search(self, query: str) -> Hits:
1054
+ matcher = self.matcher(query)
1055
+ for name, help_text, action in self._all():
1056
+ score = matcher.match(name)
1057
+ if score > 0:
1058
+ yield Hit(score, matcher.highlight(name), action, help=help_text)
1059
+
1060
+ async def discover(self) -> Hits:
1061
+ for name, help_text, action in self._all():
1062
+ yield DiscoveryHit(name, action, help=help_text)
1063
+
1064
+
1065
+ # ====================================================================== the app
1066
+ class ArctiqApp(App):
1067
+ TITLE = "ARCTIQ"
1068
+ COMMANDS = App.COMMANDS | {Commands}
1069
+ BINDINGS = [
1070
+ Binding("1", "tab('home')", "Home", show=False),
1071
+ Binding("2", "tab('repos')", "Repositories", show=False),
1072
+ Binding("3", "tab('checks')", "Checks", show=False),
1073
+ Binding("4", "tab('partners')", "Partners", show=False),
1074
+ Binding("q", "quit", "Quit"),
1075
+ ]
1076
+ CSS = """
1077
+ Screen { background: #0b0b0b; }
1078
+ .top { height: 1; background: #181818; }
1079
+ #top-left { width: 1fr; }
1080
+ #top-right { width: auto; }
1081
+ .crumb { height: 1; margin: 1 1 0 1; }
1082
+ .body { height: 1fr; }
1083
+ .body-v { height: 1fr; }
1084
+ .main { width: 1fr; }
1085
+ .side { width: 46; }
1086
+ .panel { border: solid #3a3a38; border-title-color: #e6e6e3; border-title-style: bold;
1087
+ padding: 0 1; margin: 1 1 0 1; height: auto; background: #0b0b0b; }
1088
+ #repos-panel { height: auto; max-height: 16; }
1089
+ #repos { height: auto; max-height: 14; }
1090
+ #live-panel { height: 1fr; }
1091
+ #mini-panel { height: 1fr; }
1092
+ DataTable { background: #0b0b0b; }
1093
+ DataTable > .datatable--header { background: #0b0b0b; color: #a3a39f; text-style: bold; }
1094
+ RichLog { background: #0b0b0b; overflow-x: hidden; }
1095
+ #tree-panel { width: 58; height: 1fr; }
1096
+ Tree { background: #0b0b0b; }
1097
+ #artefacts { height: auto; max-height: 6; background: #0b0b0b; }
1098
+ #uploads { height: auto; }
1099
+ #uploads ProgressBar { margin: 0 0 1 0; }
1100
+ #mid { height: auto; }
1101
+ #scores-panel, #readiness-panel { width: 1fr; }
1102
+ #prs-panel { height: auto; max-height: 16; }
1103
+ #detail-panel { height: 1fr; }
1104
+ #lower { height: auto; }
1105
+ #agreements-panel { width: 2fr; }
1106
+ #needs-panel { height: auto; }
1107
+ #lower #needs-panel { width: 1fr; }
1108
+ #sparks { height: 10; }
1109
+ .spark { width: 1fr; height: 1fr; }
1110
+ Sparkline { height: 1fr; margin: 1 0 0 0; }
1111
+ Sparkline > .sparkline--max-color { color: #e6e6e3; }
1112
+ Sparkline > .sparkline--min-color { color: #3a3a38; }
1113
+ #sides { height: auto; }
1114
+ #you, #they { width: 1fr; }
1115
+ #mine { height: auto; max-height: 20; background: #0b0b0b; }
1116
+ #uses-panel { height: auto; max-height: 20; }
1117
+ WhoScreen { align: center middle; background: rgba(0,0,0,0.70); }
1118
+ #who { width: 132; height: auto; border: solid #e6e6e3; border-title-color: #e6e6e3;
1119
+ border-title-style: bold; padding: 1 2; background: #111111; }
1120
+ Footer { background: #181818; }
1121
+ """
1122
+
1123
+ def __init__(
1124
+ self,
1125
+ source: Source,
1126
+ *,
1127
+ linked_repo: str | None = None,
1128
+ folder_path: Path | None = None,
1129
+ today: dt.date | None = None,
1130
+ opener: Callable[[str], object] = webbrowser.open,
1131
+ ) -> None:
1132
+ super().__init__()
1133
+ self.source = source
1134
+ self.linked_repo = linked_repo
1135
+ self.folder = folder_path
1136
+ self.today = today or dt.date.today()
1137
+ self.opener = opener
1138
+ self.org_name = source.org
1139
+ self.org_role = ""
1140
+ self.person = ""
1141
+ self.signed_in = True
1142
+ self.server_host = source.api.server.split("://", 1)[-1].split("/", 1)[0]
1143
+ self.repositories: list[JSON] = []
1144
+ self.partner_cache: JSON = {}
1145
+
1146
+ def on_mount(self) -> None:
1147
+ self.register_theme(THEME)
1148
+ self.theme = "arctiq"
1149
+ self.install_screen(HomeScreen(), "home")
1150
+ self.install_screen(RepoScreen(), "repos")
1151
+ self.install_screen(ChecksScreen(), "checks")
1152
+ self.install_screen(PartnersScreen(), "partners")
1153
+ self.push_screen("repos" if self.linked_repo else "home")
1154
+ self.who()
1155
+
1156
+ @work(thread=True, exclusive=True, group="who")
1157
+ def who(self) -> None:
1158
+ try:
1159
+ me = self.source.me()
1160
+ orgs = self.source.organisations()
1161
+ except ApiError as exc:
1162
+ self.call_from_thread(self.failed, exc)
1163
+ return
1164
+ org = next((o for o in orgs if o.get("slug") == self.source.org), None)
1165
+ self.call_from_thread(self._who, me, org)
1166
+
1167
+ def _who(self, me: JSON, org: JSON | None) -> None:
1168
+ self.person = me.get("display_name", "")
1169
+ if org:
1170
+ self.org_name = org.get("name", self.org_name)
1171
+ self.org_role = {"owner": "Owner", "admin": "Admin", "member": "Member",
1172
+ "viewer": "Viewer"}.get(org.get("role", ""), "") # fmt: skip
1173
+ for bar in self.screen.query(TopBar):
1174
+ bar.refresh_text()
1175
+
1176
+ def failed(self, exc: ApiError) -> None:
1177
+ if exc.status == 401:
1178
+ self.signed_in = False
1179
+ self.notify("Your sign-in has ended or was revoked. Quit and run: arctiq login",
1180
+ severity="error", timeout=30) # fmt: skip
1181
+ else:
1182
+ self.notify(exc.detail, severity="error", timeout=10)
1183
+
1184
+ async def action_tab(self, name: str) -> None:
1185
+ """One of the four tabs: close what was opened over the current one, then switch."""
1186
+ tabs = [self.get_screen(screen) for _, _, screen in TABS]
1187
+ while len(self.screen_stack) > 1 and self.screen not in tabs:
1188
+ await self.pop_screen()
1189
+ if self.screen is not self.get_screen(name):
1190
+ await self.switch_screen(name)
1191
+
1192
+ def go(self, name: str) -> None:
1193
+ self.call_later(self.action_tab, name)
1194
+
1195
+ def open_repo(self, slug: str) -> None:
1196
+ screen = self.get_screen("repos")
1197
+ assert isinstance(screen, RepoScreen)
1198
+ if screen.slug != slug:
1199
+ screen.slug, screen.artefact = slug, None
1200
+ if screen.is_mounted:
1201
+ screen.load()
1202
+ self.go("repos")
1203
+
1204
+ def open_partnership(self, agreement: str) -> None:
1205
+ self.push_screen(PartnershipScreen(agreement))
1206
+
1207
+ def open_page(self, path: str) -> None:
1208
+ self.opener(self.source.web(path))