dismisstress 0.1.0__tar.gz

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.
@@ -0,0 +1,2 @@
1
+ *.pyc
2
+ .venv
@@ -0,0 +1,7 @@
1
+ Metadata-Version: 2.5
2
+ Name: dismisstress
3
+ Version: 0.1.0
4
+ Summary: TUI manager for GitHub notifications
5
+ Requires-Python: >=3.10
6
+ Requires-Dist: pygithub>=2.2
7
+ Requires-Dist: textual
@@ -0,0 +1,33 @@
1
+ # dismisstress
2
+
3
+ TUI manager for GitHub notifications.
4
+
5
+ uv run dismisstress
6
+
7
+ ## Auth
8
+
9
+ Set `GITHUB_TOKEN` or the app runs `gh auth token` on start.
10
+
11
+ Security alert counts need a token with the `security_events` scope.
12
+
13
+ ## Keymap
14
+
15
+ |key |action |
16
+ |-----------|-----------------------------|
17
+ |`space`/`x`|select |
18
+ |`D` |dismiss selected (or current)|
19
+ |`m` |filter:merged-only |
20
+ |`s` |filter:security-only |
21
+ |`o` |filter:highlighted repo only |
22
+ |`r` |refresh |
23
+ |`j`/`k` |down/up |
24
+ |`<`/`>` |previous/next sort column |
25
+ |`q` |quit |
26
+
27
+ Clicking a column header also sorts by it.
28
+
29
+ ## Arguments
30
+
31
+ `--org ORGNAME,ORGNAME,...` filters the view to specific owners.
32
+
33
+ dismisstress --org python,pypa
@@ -0,0 +1,395 @@
1
+ import argparse
2
+ import contextvars
3
+ import dataclasses
4
+ import enum
5
+ import math
6
+ import os
7
+ import subprocess
8
+ import typing as t
9
+ from concurrent.futures import ThreadPoolExecutor
10
+
11
+ from github import Auth, Github, GithubException
12
+ from github.Notification import Notification
13
+ from github.PaginatedList import PaginatedList
14
+ from rich.console import Group, RenderableType
15
+ from rich.padding import Padding
16
+ from rich.text import Text
17
+ from textual import work
18
+ from textual.app import App, ComposeResult
19
+ from textual.binding import Binding, BindingType
20
+ from textual.containers import VerticalScroll
21
+ from textual.widgets import DataTable, Footer, Header, Link, Static
22
+ from textual.widgets.data_table import ColumnKey
23
+
24
+
25
+ class Filter(enum.Flag):
26
+ MERGED = enum.auto()
27
+ SECURITY = enum.auto()
28
+ REPO = enum.auto()
29
+
30
+
31
+ @dataclasses.dataclass(frozen=True, slots=True)
32
+ class CliArgs:
33
+ owners: tuple[str, ...] | None
34
+
35
+
36
+ Row = tuple[Notification, str, str] # notification, status, url
37
+
38
+ # token is global (simple)
39
+ _GH_TOKEN: str = ""
40
+ # PyGithub clients are not thread-safe, so each thread gets its own
41
+ _gh_client_var: contextvars.ContextVar[Github | None] = contextvars.ContextVar(
42
+ "gh_client"
43
+ )
44
+
45
+
46
+ def _clear_context() -> None:
47
+ _gh_client_var.set(None)
48
+
49
+
50
+ def load_token() -> None:
51
+ global _GH_TOKEN
52
+ _GH_TOKEN = (
53
+ os.environ.get("GITHUB_TOKEN")
54
+ or subprocess.run(
55
+ ["gh", "auth", "token"], capture_output=True, text=True, check=True
56
+ ).stdout.strip()
57
+ )
58
+
59
+
60
+ def gh_client() -> Github:
61
+ ret: Github | None = _gh_client_var.get(None)
62
+ if ret is None:
63
+ ret = Github(auth=Auth.Token(_GH_TOKEN))
64
+ _gh_client_var.set(ret)
65
+ return ret
66
+
67
+
68
+ def gh_api(verb: str, url: str) -> t.Any:
69
+ return gh_client().requester.requestJsonAndCheck(verb, url)[1]
70
+
71
+
72
+ def subject(notification: Notification) -> tuple[str, str]:
73
+ repo = notification.repository.full_name
74
+ is_security = notification.reason == "security_alert"
75
+ dependabot_uri = f"https://github.com/{repo}/security/dependabot"
76
+ ghsa_uri = f"https://github.com/{repo}/security/advisories"
77
+
78
+ if notification.subject.type == "RepositoryAdvisory":
79
+ return "-", ghsa_uri
80
+ if not notification.subject.url and not is_security:
81
+ return "?", ""
82
+ if not notification.subject.url:
83
+ try:
84
+ alerts = gh_api(
85
+ "GET", f"/repos/{repo}/dependabot/alerts?state=open&per_page=100"
86
+ )
87
+ except GithubException:
88
+ return "?", dependabot_uri
89
+ state = f"{len(alerts)}{'+' if len(alerts) == 100 else ''} open"
90
+ return state, dependabot_uri
91
+
92
+ try:
93
+ data = gh_api("GET", notification.subject.url)
94
+ except GithubException:
95
+ return "?", ""
96
+
97
+ if isinstance(data, list): # grouped subject, e.g. a thread of Dependabot alerts
98
+ state = (
99
+ ", ".join(
100
+ sorted({x.get("state", "?") for x in data if isinstance(x, dict)})
101
+ )
102
+ or "-"
103
+ )
104
+ return (state, dependabot_uri if is_security else f"https://github.com/{repo}")
105
+ return (
106
+ ("merged" if data.get("merged") else data.get("state", "-")),
107
+ data.get("html_url", ""),
108
+ )
109
+
110
+
111
+ def latest_comment(notification: Notification) -> str:
112
+ if not notification.subject.latest_comment_url:
113
+ return "(no comments)"
114
+ try:
115
+ comment = gh_api("GET", notification.subject.latest_comment_url)
116
+ except GithubException as e:
117
+ return f"(error: {e.status})"
118
+ user = (comment.get("user") or comment.get("author") or {}).get("login", "?")
119
+ return f"{user}:\n\n{comment.get('body') or ''}"
120
+
121
+
122
+ def renderable_comment_thread(notification: Notification) -> RenderableType:
123
+ """Opening post plus the newest 100 main-thread comments, oldest first."""
124
+ if notification.subject.type not in ("Issue", "PullRequest"):
125
+ return Text(latest_comment(notification))
126
+
127
+ try:
128
+ subject_info = gh_api("GET", notification.subject.url)
129
+ except GithubException as e:
130
+ return Text(f"(error on notification metadata lookup: {e.status})")
131
+
132
+ num_comments = subject_info.get("comments", 0)
133
+ last_page_index = math.ceil(num_comments / 100)
134
+ comments: list[dict[str, t.Any]] = []
135
+
136
+ # get the last two pages of comments, then trim down to 100
137
+ # most typically, there are fewer than 100 comments, so this is *usually* one call
138
+ try:
139
+ if last_page_index > 0:
140
+ comments.extend(
141
+ _fetch_page_comments(
142
+ last_page_index - 1, subject_info["comments_url"]
143
+ )
144
+ )
145
+ comments.extend(
146
+ _fetch_page_comments(last_page_index, subject_info["comments_url"])
147
+ )
148
+ except GithubException as e:
149
+ return Text(f"(error fetching comments: {e.status})")
150
+ comments = comments[-100:]
151
+
152
+ # start with the initial comment and optionally a spacer for hidden old comments
153
+ parts: list[RenderableType] = _format_comment(subject_info)
154
+ if (hidden := num_comments - len(comments)) > 0:
155
+ parts.append(Text(f"...{hidden} older comments not shown...\n", "dim"))
156
+
157
+ for comment in comments:
158
+ parts.extend(_format_comment(comment))
159
+
160
+ return Group(*parts)
161
+
162
+
163
+ def _format_comment(post: dict[str, t.Any]) -> list[RenderableType]:
164
+ parts = []
165
+ user = (post.get("user") or {}).get("login", "ghost")
166
+ parts.append(Text(f"── {user} · {post.get('created_at', '')[:10]}", "bold"))
167
+ parts.append(Padding(Text(post.get("body") or ""), (0, 0, 1, 2)))
168
+ return parts
169
+
170
+
171
+ def _fetch_page_comments(page_index: int, comments_url: str) -> list[dict[str, t.Any]]:
172
+ url = f"{comments_url}?per_page=100&page={page_index}"
173
+ return gh_api("GET", url)
174
+
175
+
176
+ def owner(notification: Notification) -> str:
177
+ return notification.repository.full_name.split("/")[0].lower()
178
+
179
+
180
+ def matches_filter(
181
+ filter: Filter, notification: Notification, status: str, repo: str | None
182
+ ) -> bool:
183
+ return (
184
+ (Filter.MERGED not in filter or status == "merged")
185
+ and (Filter.SECURITY not in filter or notification.reason == "security_alert")
186
+ and (Filter.REPO not in filter or notification.repository.full_name == repo)
187
+ )
188
+
189
+
190
+ class Dismisstress(App[None]):
191
+ CSS = (
192
+ "DataTable { height: 2fr; } VerticalScroll { height: 1fr; border: solid gray; }"
193
+ )
194
+ BINDINGS: t.ClassVar[list[BindingType]] = [
195
+ ("space,x", "select", "Select"),
196
+ ("m", "filter('MERGED')", "Merged only"),
197
+ ("s", "filter('SECURITY')", "Security only"),
198
+ ("o", "filter('REPO')", "This repo only"),
199
+ ("D", "dismiss", "Dismiss"),
200
+ ("r", "refresh", "Refresh"),
201
+ ("q", "quit", "Quit"),
202
+ Binding("j", "simulate_key('down')", "Down"),
203
+ Binding("k", "simulate_key('up')", "Up"),
204
+ Binding("less_than_sign", "sort(-1)", "Sort prev", key_display="<"),
205
+ Binding("greater_than_sign", "sort(1)", "Sort next", key_display=">"),
206
+ ]
207
+
208
+ def __init__(self, args: CliArgs) -> None:
209
+ super().__init__()
210
+ self.owners = args.owners
211
+ self.rows: dict[str, Row] = {}
212
+ self.comments: dict[str, RenderableType] = {}
213
+ self.selected: set[str] = set()
214
+ self.filter = Filter(0)
215
+ self.repo: str | None = None
216
+ self.sort_by: ColumnKey | None = None
217
+
218
+ def compose(self) -> ComposeResult:
219
+ yield Header()
220
+ yield DataTable(cursor_type="row")
221
+ yield Link("", id="link")
222
+ with VerticalScroll():
223
+ yield Static(id="detail")
224
+ yield Static(id="status")
225
+ yield Footer()
226
+
227
+ def on_mount(self) -> None:
228
+ table = self.query_one(DataTable)
229
+ table.add_column("", key="sel")
230
+ table.add_columns("Unread", "Repo", "Type", "Reason", "Status", "Title")
231
+ self.action_refresh()
232
+
233
+ def current(self) -> str | None:
234
+ table = self.query_one(DataTable)
235
+ if table.row_count:
236
+ return table.coordinate_to_cell_key(table.cursor_coordinate).row_key.value
237
+ return None
238
+
239
+ def render_table(self) -> None:
240
+ table = self.query_one(DataTable)
241
+ row = table.cursor_row
242
+ table.clear()
243
+ for id, (notification, status, _) in self.rows.items():
244
+ if matches_filter(self.filter, notification, status, self.repo):
245
+ table.add_row(
246
+ "*" if id in self.selected else " ",
247
+ "●" if notification.unread else " ",
248
+ notification.repository.full_name,
249
+ notification.subject.type,
250
+ notification.reason,
251
+ status,
252
+ notification.subject.title,
253
+ key=id,
254
+ )
255
+ if self.sort_by:
256
+ table.sort(self.sort_by)
257
+ if table.row_count:
258
+ table.move_cursor(row=min(row, table.row_count - 1))
259
+ else:
260
+ self.show_detail("", "")
261
+ self.update_sub_title()
262
+
263
+ def update_sub_title(self) -> None:
264
+ table = self.query_one(DataTable)
265
+ sort = ""
266
+ if self.sort_by:
267
+ sort = (
268
+ f", sorted by {table.columns[self.sort_by].label.plain or 'Selected'}"
269
+ )
270
+ self.sub_title = f"{table.row_count} shown, {len(self.selected)} selected{sort}"
271
+
272
+ @work(thread=True, exclusive=True, group="load")
273
+ def action_refresh(self) -> None:
274
+ self.call_from_thread(setattr, self, "sub_title", "loading...")
275
+ # PyGithub's get_notifications() lacks is_done; this matches the web inbox
276
+ params = {"all": "true", "is_done": "false"}
277
+ ns = list(
278
+ PaginatedList(Notification, gh_client().requester, "/notifications", params)
279
+ )
280
+ if self.owners:
281
+ ns = [n for n in ns if owner(n) in self.owners]
282
+ # reset on init: threads inherit context on free-threaded builds
283
+ with ThreadPoolExecutor(8, initializer=_clear_context) as ex:
284
+ subjects = list(ex.map(subject, ns))
285
+ self.call_from_thread(
286
+ self.loaded, {n.id: (n, *s) for n, s in zip(ns, subjects)}
287
+ )
288
+
289
+ def loaded(self, rows: dict[str, Row]) -> None:
290
+ self.rows = rows
291
+ self.comments = {}
292
+ self.selected &= rows.keys()
293
+ self.render_table()
294
+
295
+ def on_data_table_header_selected(self, event: DataTable.HeaderSelected) -> None:
296
+ self.sort_by = event.column_key
297
+ self.render_table()
298
+
299
+ def action_sort(self, step: int) -> None:
300
+ cols: list[ColumnKey | None] = [None, *self.query_one(DataTable).columns]
301
+ self.sort_by = cols[(cols.index(self.sort_by) + step) % len(cols)]
302
+ self.render_table()
303
+
304
+ def on_data_table_row_highlighted(self, event: DataTable.RowHighlighted) -> None:
305
+ if event.row_key.value is not None:
306
+ self.show(event.row_key.value)
307
+
308
+ @work(thread=True, exclusive=True, group="detail")
309
+ def show(self, id: str) -> None:
310
+ n, s, url = self.rows[id]
311
+ if id not in self.comments:
312
+ self.comments[id] = renderable_comment_thread(n)
313
+ header = Text(f"{n.subject.title}\n{n.subject.type}: {s}\n", "bold")
314
+ if self.current() == id:
315
+ self.call_from_thread(
316
+ self.show_detail, url, Group(header, self.comments[id])
317
+ )
318
+
319
+ def show_detail(self, url: str, text: RenderableType) -> None:
320
+ link = self.query_one(Link)
321
+ link.text = link.url = url
322
+ self.query_one("#detail", Static).update(text)
323
+ self.call_after_refresh(
324
+ self.query_one(VerticalScroll).scroll_end, animate=False
325
+ )
326
+
327
+ def action_select(self) -> None:
328
+ if (id := self.current()) is None:
329
+ return
330
+ self.selected ^= {id}
331
+ self.query_one(DataTable).update_cell(
332
+ id, "sel", "*" if id in self.selected else ""
333
+ )
334
+ self.update_sub_title()
335
+
336
+ def action_filter(self, name: str) -> None:
337
+ kind = Filter[name]
338
+ self.filter ^= kind
339
+ if kind is Filter.REPO and kind in self.filter and (id := self.current()):
340
+ self.repo = self.rows[id][0].repository.full_name
341
+ self.render_table()
342
+
343
+ def action_dismiss(self) -> None:
344
+ ids = set(self.selected) or {id for id in [self.current()] if id is not None}
345
+ if ids:
346
+ self.dismiss(ids)
347
+
348
+ @work(thread=True, group="dismiss")
349
+ def dismiss(self, ids: set[str]) -> None:
350
+ done = set()
351
+ for i, id in enumerate(ids, 1):
352
+ self.call_from_thread(self.set_status, f"dismissing {i}/{len(ids)}...")
353
+ try:
354
+ gh_api("DELETE", self.rows[id][0].url)
355
+ done.add(id)
356
+ except GithubException as e:
357
+ self.call_from_thread(
358
+ self.notify, f"dismiss failed: {e.status}", severity="error"
359
+ )
360
+ self.call_from_thread(self.set_status, f"dismissed {len(done)}/{len(ids)}")
361
+ self.call_from_thread(self.dismissed, done)
362
+
363
+ def set_status(self, text: str) -> None:
364
+ self.query_one("#status", Static).update(text)
365
+
366
+ def dismissed(self, ids: set[str]) -> None:
367
+ for id in ids:
368
+ self.rows.pop(id, None)
369
+ self.selected -= ids
370
+ self.render_table()
371
+
372
+
373
+ def parse_args() -> CliArgs:
374
+ parser = argparse.ArgumentParser(prog="dismisstress")
375
+ parser.add_argument(
376
+ "--owner",
377
+ "--org",
378
+ dest="owners",
379
+ help="only show these owners (comma-separated, or may be used multiple times)",
380
+ action="append",
381
+ default=[],
382
+ )
383
+ args = parser.parse_args()
384
+ owners = {o.strip().lower() for x in args.owners for o in x.split(",")}
385
+ return CliArgs(owners=tuple(owners) if owners else None)
386
+
387
+
388
+ def main() -> None:
389
+ args = parse_args()
390
+ load_token()
391
+ Dismisstress(args).run()
392
+
393
+
394
+ if __name__ == "__main__":
395
+ main()
@@ -0,0 +1,24 @@
1
+ [project]
2
+ name = "dismisstress"
3
+ version = "0.1.0"
4
+ description = "TUI manager for GitHub notifications"
5
+ requires-python = ">=3.10"
6
+ dependencies = ["pygithub>=2.2", "textual"]
7
+
8
+ [project.scripts]
9
+ dismisstress = "dismisstress:main"
10
+
11
+ [build-system]
12
+ requires = ["hatchling"]
13
+ build-backend = "hatchling.build"
14
+
15
+ # used by `hatch check types`
16
+ [tool.hatch.envs.hatch-check-types]
17
+ dependencies = ["mypy"]
18
+
19
+ [tool.hatch.envs.hatch-check-types.scripts]
20
+ check = "mypy {args}"
21
+
22
+ [tool.mypy]
23
+ strict = true
24
+ files = ["dismisstress.py"]