github-statistics 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 (86) hide show
  1. github_statistics/__init__.py +14 -0
  2. github_statistics/__main__.py +10 -0
  3. github_statistics/_version.py +24 -0
  4. github_statistics/cli/__init__.py +9 -0
  5. github_statistics/cli/app.py +104 -0
  6. github_statistics/cli/cache.py +159 -0
  7. github_statistics/cli/collect.py +219 -0
  8. github_statistics/cli/common.py +128 -0
  9. github_statistics/cli/config.py +80 -0
  10. github_statistics/cli/doctor.py +214 -0
  11. github_statistics/cli/export.py +111 -0
  12. github_statistics/cli/options.py +175 -0
  13. github_statistics/cli/render.py +126 -0
  14. github_statistics/cli/run.py +137 -0
  15. github_statistics/cli/scope.py +96 -0
  16. github_statistics/cli/site.py +150 -0
  17. github_statistics/client/__init__.py +40 -0
  18. github_statistics/client/accounting.py +99 -0
  19. github_statistics/client/budget.py +125 -0
  20. github_statistics/client/cooldown.py +113 -0
  21. github_statistics/client/errors.py +60 -0
  22. github_statistics/client/graphql.py +281 -0
  23. github_statistics/client/paging.py +92 -0
  24. github_statistics/client/policy.py +243 -0
  25. github_statistics/client/transport.py +437 -0
  26. github_statistics/collect/__init__.py +44 -0
  27. github_statistics/collect/common.py +69 -0
  28. github_statistics/collect/enrich_items.py +423 -0
  29. github_statistics/collect/items.py +238 -0
  30. github_statistics/collect/jobs.py +194 -0
  31. github_statistics/collect/listed.py +42 -0
  32. github_statistics/collect/members.py +70 -0
  33. github_statistics/collect/reader.py +124 -0
  34. github_statistics/collect/run.py +354 -0
  35. github_statistics/collect/runs.py +436 -0
  36. github_statistics/collect/slices.py +55 -0
  37. github_statistics/collect/steps.py +154 -0
  38. github_statistics/collect/sweep.py +70 -0
  39. github_statistics/config/__init__.py +37 -0
  40. github_statistics/config/loader.py +430 -0
  41. github_statistics/config/models.py +156 -0
  42. github_statistics/config/schema.py +245 -0
  43. github_statistics/export/__init__.py +11 -0
  44. github_statistics/export/csv.py +93 -0
  45. github_statistics/export/documents.py +189 -0
  46. github_statistics/export/json.py +33 -0
  47. github_statistics/py.typed +2 -0
  48. github_statistics/render/__init__.py +44 -0
  49. github_statistics/render/bars3d.py +420 -0
  50. github_statistics/render/charts.py +214 -0
  51. github_statistics/render/demo.py +133 -0
  52. github_statistics/render/images.py +31 -0
  53. github_statistics/render/layout.py +341 -0
  54. github_statistics/render/model.py +260 -0
  55. github_statistics/render/palette.py +41 -0
  56. github_statistics/scope/__init__.py +17 -0
  57. github_statistics/scope/apply.py +95 -0
  58. github_statistics/scope/resolver.py +228 -0
  59. github_statistics/series/__init__.py +22 -0
  60. github_statistics/series/actors.py +128 -0
  61. github_statistics/series/coverage.py +86 -0
  62. github_statistics/series/daily.py +229 -0
  63. github_statistics/series/leaderboard.py +221 -0
  64. github_statistics/series/repositories.py +154 -0
  65. github_statistics/site/__init__.py +9 -0
  66. github_statistics/site/assets/site.css +281 -0
  67. github_statistics/site/build.py +392 -0
  68. github_statistics/site/templates/base.html.j2 +25 -0
  69. github_statistics/site/templates/index.html.j2 +30 -0
  70. github_statistics/site/templates/macros.html.j2 +5 -0
  71. github_statistics/site/templates/site.js.j2 +66 -0
  72. github_statistics/site/templates/target.html.j2 +95 -0
  73. github_statistics/store/__init__.py +40 -0
  74. github_statistics/store/activity.py +311 -0
  75. github_statistics/store/aggregates.py +294 -0
  76. github_statistics/store/base.py +163 -0
  77. github_statistics/store/codec.py +263 -0
  78. github_statistics/store/models.py +136 -0
  79. github_statistics/store/paths.py +36 -0
  80. github_statistics/store/schema.py +169 -0
  81. github_statistics/store/sqlite.py +299 -0
  82. github_statistics-0.1.0.dist-info/METADATA +308 -0
  83. github_statistics-0.1.0.dist-info/RECORD +86 -0
  84. github_statistics-0.1.0.dist-info/WHEEL +4 -0
  85. github_statistics-0.1.0.dist-info/entry_points.txt +2 -0
  86. github_statistics-0.1.0.dist-info/licenses/LICENSE +201 -0
@@ -0,0 +1,311 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ # SPDX-FileCopyrightText: 2026 The Linux Foundation
3
+ """Store methods for issues, pull requests, reviews and workflow runs."""
4
+
5
+ from __future__ import annotations
6
+
7
+ import sqlite3
8
+ from collections.abc import Iterable, Mapping, Sequence
9
+ from datetime import date, timedelta
10
+
11
+ from . import codec
12
+ from .base import StoreBase, assignments, chunks, marks
13
+ from .models import Enrichment, Item, Review, Run
14
+
15
+ _ITEM_LISTING = (
16
+ "node_id",
17
+ "kind",
18
+ "created_at",
19
+ "closed_at",
20
+ "merged_at",
21
+ "author",
22
+ "author_type",
23
+ "updated_at",
24
+ )
25
+ _ITEM_ENRICHED = (
26
+ "merged_by",
27
+ "merged_by_type",
28
+ "closed_by",
29
+ "closed_by_type",
30
+ "reviews_read_at",
31
+ )
32
+ _UPSERT_ITEM = (
33
+ f"INSERT INTO items ({', '.join(codec.ITEM_COLUMNS)}) "
34
+ f"VALUES ({marks(len(codec.ITEM_COLUMNS))}) "
35
+ "ON CONFLICT (repo, number) DO UPDATE SET "
36
+ + assignments(_ITEM_LISTING)
37
+ + ", "
38
+ + ", ".join(
39
+ f"{column} = COALESCE(excluded.{column}, items.{column})"
40
+ for column in _ITEM_ENRICHED
41
+ )
42
+ )
43
+ _UPSERT_RUN = (
44
+ f"INSERT INTO runs ({', '.join(codec.RUN_COLUMNS)}) "
45
+ f"VALUES ({marks(len(codec.RUN_COLUMNS))}) "
46
+ "ON CONFLICT (id) DO UPDATE SET "
47
+ + assignments(c for c in codec.RUN_COLUMNS if c not in ("id", "jobs"))
48
+ + ", jobs = CASE WHEN runs.status IS NOT excluded.status"
49
+ " OR runs.conclusion IS NOT excluded.conclusion"
50
+ " OR runs.attempt IS NOT excluded.attempt"
51
+ " THEN NULL ELSE COALESCE(excluded.jobs, runs.jobs) END"
52
+ )
53
+ # The coverage metric a run's job count completes (design §6.4).
54
+ JOBS_METRIC = "jobs"
55
+ # The coverage metric of the runs listing, which bounds jobs coverage.
56
+ RUNS_METRIC = "runs"
57
+
58
+ _INSERT_REVIEW = (
59
+ f"INSERT OR REPLACE INTO reviews ({', '.join(codec.REVIEW_COLUMNS)}) "
60
+ f"VALUES ({marks(len(codec.REVIEW_COLUMNS))})"
61
+ )
62
+
63
+
64
+ class ActivityStore(StoreBase):
65
+ """Items, reviews and runs: the facts the charts count."""
66
+
67
+ # Items
68
+
69
+ def upsert_items(self, items: Iterable[Item]) -> None:
70
+ """Insert or update items from a listing.
71
+
72
+ Listing fields are overwritten; enrichment fields keep their
73
+ stored values unless the record carries new ones.
74
+ """
75
+ with self._transaction() as connection:
76
+ connection.executemany(_UPSERT_ITEM, (codec.item_row(i) for i in items))
77
+
78
+ def items_needing_enrichment(self, repo: str, limit: int) -> list[Item]:
79
+ """Up to ``limit`` items of ``repo`` never read, or updated since last read."""
80
+ rows = self._connection.execute(
81
+ "SELECT * FROM items WHERE repo = ?"
82
+ " AND (reviews_read_at IS NULL OR updated_at > reviews_read_at)"
83
+ " ORDER BY number LIMIT ?",
84
+ (repo, limit),
85
+ )
86
+ return [codec.item_from_row(row) for row in rows]
87
+
88
+ def mark_enriched(self, enrichments: Iterable[Enrichment]) -> None:
89
+ """Record mergers, closers and the read time for each item."""
90
+ with self._transaction() as connection:
91
+ connection.executemany(
92
+ "UPDATE items SET merged_by = ?, merged_by_type = ?,"
93
+ " closed_by = ?, closed_by_type = ?, reviews_read_at = ?"
94
+ " WHERE repo = ? AND number = ?",
95
+ (
96
+ (
97
+ e.merged_by,
98
+ e.merged_by_type,
99
+ e.closed_by,
100
+ e.closed_by_type,
101
+ codec.timestamp(e.read_at),
102
+ e.repo,
103
+ e.number,
104
+ )
105
+ for e in enrichments
106
+ ),
107
+ )
108
+
109
+ def store_enrichments(
110
+ self,
111
+ enrichments: Iterable[Enrichment],
112
+ reviews: Mapping[tuple[str, int], Iterable[Review]],
113
+ ) -> None:
114
+ """Replace reviews by ``(repo, number)`` and mark items enriched, together.
115
+
116
+ One transaction, so an item is never marked read without the
117
+ reviews it was read with (design §6.3).
118
+ """
119
+ with self._transaction():
120
+ for (repo, number), item_reviews in reviews.items():
121
+ self.replace_reviews(repo, number, item_reviews)
122
+ self.mark_enriched(enrichments)
123
+
124
+ def items_between(
125
+ self, from_day: date, to_day: date, repos: Sequence[str] | None = None
126
+ ) -> list[Item]:
127
+ """Items created, closed or merged on a day from ``from_day`` to ``to_day``."""
128
+ low, high = codec.day_bounds(from_day, to_day)
129
+ sql = (
130
+ "SELECT * FROM items WHERE ("
131
+ "(created_at >= ? AND created_at < ?)"
132
+ " OR (closed_at >= ? AND closed_at < ?)"
133
+ " OR (merged_at >= ? AND merged_at < ?))"
134
+ )
135
+ rows = self._select_in(sql, (low, high) * 3, "repo", repos, "repo, number")
136
+ return [codec.item_from_row(row) for row in rows]
137
+
138
+ # Reviews
139
+
140
+ def replace_reviews(
141
+ self, repo: str, number: int, reviews: Iterable[Review]
142
+ ) -> None:
143
+ """Replace the stored reviews of one pull request with ``reviews``."""
144
+ with self._transaction() as connection:
145
+ connection.execute(
146
+ "DELETE FROM reviews WHERE repo = ? AND number = ?", (repo, number)
147
+ )
148
+ connection.executemany(
149
+ _INSERT_REVIEW, (codec.review_row(r) for r in reviews)
150
+ )
151
+
152
+ def reviews_for(self, repo: str, number: int) -> list[Review]:
153
+ """The stored reviews of one pull request."""
154
+ rows = self._connection.execute(
155
+ "SELECT * FROM reviews WHERE repo = ? AND number = ? ORDER BY id",
156
+ (repo, number),
157
+ )
158
+ return [codec.review_from_row(row) for row in rows]
159
+
160
+ def reviews_between(
161
+ self, from_day: date, to_day: date, repos: Sequence[str] | None = None
162
+ ) -> list[Review]:
163
+ """Reviews submitted on a day from ``from_day`` to ``to_day``."""
164
+ low, high = codec.day_bounds(from_day, to_day)
165
+ sql = "SELECT * FROM reviews WHERE submitted_at >= ? AND submitted_at < ?"
166
+ rows = self._select_in(sql, (low, high), "repo", repos, "submitted_at, id")
167
+ return [codec.review_from_row(row) for row in rows]
168
+
169
+ # Runs
170
+
171
+ def upsert_runs(self, runs: Iterable[Run]) -> None:
172
+ """Insert or update runs; a changed status, conclusion or attempt clears ``jobs``.
173
+
174
+ Each run left without a job count takes its creation day out of
175
+ the jobs coverage of its repository, so the day stays incomplete
176
+ until the count is read again and coverage is added back.
177
+ """
178
+ rows = [codec.run_row(r) for r in runs]
179
+ ids = sorted({run_id for run_id, *_ in rows})
180
+ with self._transaction() as connection:
181
+ connection.executemany(_UPSERT_RUN, rows)
182
+ days: set[tuple[str, str]] = set()
183
+ for chunk in chunks(ids):
184
+ days.update(
185
+ (repo, day)
186
+ for repo, day in connection.execute(
187
+ "SELECT repo, substr(created_at, 1, 10) FROM runs"
188
+ f" WHERE jobs IS NULL AND id IN ({marks(len(chunk))})",
189
+ chunk,
190
+ )
191
+ )
192
+ for repo, day in sorted(days):
193
+ _uncover(connection, repo, JOBS_METRIC, day)
194
+
195
+ def runs_needing_jobs(self, limit: int) -> list[Run]:
196
+ """Up to ``limit`` runs, oldest first, whose job count is not yet read."""
197
+ rows = self._connection.execute(
198
+ "SELECT * FROM runs WHERE jobs IS NULL ORDER BY created_at, id LIMIT ?",
199
+ (limit,),
200
+ )
201
+ return [codec.run_from_row(row) for row in rows]
202
+
203
+ def pending_runs(self, repo: str) -> list[Run]:
204
+ """Runs of ``repo`` that have not completed, to re-read on the next sync."""
205
+ rows = self._connection.execute(
206
+ "SELECT * FROM runs WHERE repo = ? AND status != 'completed'"
207
+ " ORDER BY created_at, id",
208
+ (repo,),
209
+ )
210
+ return [codec.run_from_row(row) for row in rows]
211
+
212
+ def set_job_counts(self, counts: Mapping[int, int]) -> None:
213
+ """Record the job count of each run id in ``counts``."""
214
+ with self._transaction() as connection:
215
+ connection.executemany(
216
+ "UPDATE runs SET jobs = ? WHERE id = ?",
217
+ ((jobs, run_id) for run_id, jobs in counts.items()),
218
+ )
219
+
220
+ def restore_jobs_coverage(self) -> None:
221
+ """Set each repository's jobs coverage to the days whose runs all have counts.
222
+
223
+ That is its runs coverage less every day holding a run with no
224
+ job count; a covered day without runs has nothing to count and
225
+ is covered too. Recomputed whole, so a step that stopped early
226
+ loses nothing the next one cannot restore.
227
+ """
228
+ with self._transaction() as connection:
229
+ uncounted: dict[str, set[str]] = {}
230
+ for repo, day in connection.execute(
231
+ "SELECT DISTINCT repo, substr(created_at, 1, 10) FROM runs"
232
+ " WHERE jobs IS NULL"
233
+ ):
234
+ uncounted.setdefault(repo, set()).add(day)
235
+ pieces = [
236
+ (repo, JOBS_METRIC, low, high)
237
+ for repo, start, end in connection.execute(
238
+ "SELECT repo, from_day, to_day FROM coverage WHERE metric = ?",
239
+ (RUNS_METRIC,),
240
+ ).fetchall()
241
+ for low, high in _without(start, end, uncounted.get(repo, set()))
242
+ ]
243
+ connection.execute("DELETE FROM coverage WHERE metric = ?", (JOBS_METRIC,))
244
+ connection.executemany(
245
+ "INSERT INTO coverage (repo, metric, from_day, to_day)"
246
+ " VALUES (?, ?, ?, ?)",
247
+ pieces,
248
+ )
249
+
250
+ def runs_between(
251
+ self, from_day: date, to_day: date, repos: Sequence[str] | None = None
252
+ ) -> list[Run]:
253
+ """Runs created on a day from ``from_day`` to ``to_day``."""
254
+ low, high = codec.day_bounds(from_day, to_day)
255
+ sql = "SELECT * FROM runs WHERE created_at >= ? AND created_at < ?"
256
+ rows = self._select_in(sql, (low, high), "repo", repos, "created_at, id")
257
+ return [codec.run_from_row(row) for row in rows]
258
+
259
+ def earliest_run_day(self, owner: str) -> date | None:
260
+ """The creation day of the oldest run held for any repository of ``owner``.
261
+
262
+ Owners compare without case, as GitHub's do; ``None`` when no run
263
+ of ``owner`` is held.
264
+ """
265
+ escaped = owner.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_")
266
+ row = self._connection.execute(
267
+ "SELECT MIN(substr(created_at, 1, 10)) FROM runs"
268
+ " WHERE repo LIKE ? ESCAPE '\\'",
269
+ (f"{escaped}/%",),
270
+ ).fetchone()
271
+ return None if row[0] is None else codec.parse_day(row[0])
272
+
273
+
274
+ def _uncover(connection: sqlite3.Connection, repo: str, metric: str, day: str) -> None:
275
+ """Take ``day`` out of the coverage of ``metric``, splitting its range."""
276
+ row = connection.execute(
277
+ "SELECT from_day, to_day FROM coverage"
278
+ " WHERE repo = ? AND metric = ? AND from_day <= ? AND to_day >= ?",
279
+ (repo, metric, day, day),
280
+ ).fetchone()
281
+ if row is None:
282
+ return
283
+ start, end = row
284
+ one = timedelta(days=1)
285
+ pieces = []
286
+ if start < day:
287
+ pieces.append((start, codec.day(codec.parse_day(day) - one)))
288
+ if day < end:
289
+ pieces.append((codec.day(codec.parse_day(day) + one), end))
290
+ connection.execute(
291
+ "DELETE FROM coverage WHERE repo = ? AND metric = ? AND from_day = ?",
292
+ (repo, metric, start),
293
+ )
294
+ connection.executemany(
295
+ "INSERT INTO coverage (repo, metric, from_day, to_day) VALUES (?, ?, ?, ?)",
296
+ ((repo, metric, low, high) for low, high in pieces),
297
+ )
298
+
299
+
300
+ def _without(start: str, end: str, days: set[str]) -> list[tuple[str, str]]:
301
+ """The ranges left of ``start`` to ``end`` once ``days`` are taken out."""
302
+ one = timedelta(days=1)
303
+ pieces = []
304
+ low = start
305
+ for day in sorted(d for d in days if start <= d <= end):
306
+ if low < day:
307
+ pieces.append((low, codec.day(codec.parse_day(day) - one)))
308
+ low = codec.day(codec.parse_day(day) + one)
309
+ if low <= end:
310
+ pieces.append((low, end))
311
+ return pieces
@@ -0,0 +1,294 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ # SPDX-FileCopyrightText: 2026 The Linux Foundation
3
+ """Read-only aggregate queries the series builder counts from (design §7.3).
4
+
5
+ Each query groups in SQL, by day and actor, so the caller classifies
6
+ the distinct ``(login, type)`` pairs rather than every row; an event
7
+ counts only on a day its repository was in scope.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ from collections.abc import Iterable
13
+ from datetime import date
14
+
15
+ from . import codec
16
+ from .activity import ActivityStore
17
+ from .base import marks
18
+ from .models import ActorDayCount, RunDayCount
19
+
20
+ _ITEM_KINDS = ("issue", "pr")
21
+ _ITEM_DAY_COLUMNS = ("created_at", "closed_at")
22
+ _ITEM_EVENT_COLUMNS = ("created_at", "closed_at", "merged_at")
23
+ _ITEM_ACTORS = {
24
+ "author": "author_type",
25
+ "merged_by": "merged_by_type",
26
+ "closed_by": "closed_by_type",
27
+ }
28
+ SCHEDULE_EVENT = "schedule"
29
+
30
+ # One actor's count: ``(login, type, count)``.
31
+ ActorCount = tuple[str | None, str | None, int]
32
+
33
+
34
+ def _in_scope(table: str, column: str) -> str:
35
+ """SQL true when the row's repository was in scope on the day of ``column``."""
36
+ return (
37
+ "EXISTS (SELECT 1 FROM scope WHERE scope.repo = "
38
+ f"{table}.repo AND scope.from_day <= substr({table}.{column}, 1, 10)"
39
+ f" AND (scope.to_day IS NULL OR scope.to_day > substr({table}.{column}, 1, 10)))"
40
+ )
41
+
42
+
43
+ class AggregateStore(ActivityStore):
44
+ """Grouped, read-only counts over items and runs."""
45
+
46
+ def item_day_counts(
47
+ self, kind: str, column: str, from_day: date, to_day: date
48
+ ) -> list[ActorDayCount]:
49
+ """Items of ``kind`` per day of ``column`` and author, in scope that day.
50
+
51
+ ``kind`` is ``"issue"`` or ``"pr"``; ``column`` is ``"created_at"``
52
+ or ``"closed_at"``. Days run from ``from_day`` to ``to_day``.
53
+ """
54
+ if kind not in _ITEM_KINDS:
55
+ raise ValueError(f"unknown item kind {kind!r}")
56
+ if column not in _ITEM_DAY_COLUMNS:
57
+ raise ValueError(f"cannot count items by {column!r}")
58
+ low, high = codec.day_bounds(from_day, to_day)
59
+ rows = self._connection.execute(
60
+ f"SELECT substr({column}, 1, 10) AS day, author, author_type, COUNT(*)"
61
+ f" FROM items WHERE kind = ? AND {column} >= ? AND {column} < ?"
62
+ f" AND {_in_scope('items', column)}"
63
+ " GROUP BY day, author, author_type ORDER BY day, author, author_type",
64
+ (kind, low, high),
65
+ )
66
+ return [
67
+ ActorDayCount(codec.parse_day(day), login, account_type, count)
68
+ for day, login, account_type, count in rows
69
+ ]
70
+
71
+ def run_day_counts(self, from_day: date, to_day: date) -> list[RunDayCount]:
72
+ """Runs and summed jobs per creation day, actor and conclusion, in scope.
73
+
74
+ A scheduled run is grouped with no actor, since GitHub names
75
+ whoever last edited the schedule. A run without a job count adds
76
+ nothing to ``jobs``.
77
+ """
78
+ low, high = codec.day_bounds(from_day, to_day)
79
+ scheduled = "event = ?"
80
+ rows = self._connection.execute(
81
+ "SELECT substr(created_at, 1, 10) AS day,"
82
+ f" CASE WHEN {scheduled} THEN NULL ELSE actor END AS login,"
83
+ f" CASE WHEN {scheduled} THEN NULL ELSE actor_type END AS login_type,"
84
+ f" {scheduled} AS is_scheduled, conclusion,"
85
+ " COUNT(*), COALESCE(SUM(jobs), 0)"
86
+ " FROM runs WHERE created_at >= ? AND created_at < ?"
87
+ f" AND {_in_scope('runs', 'created_at')}"
88
+ " GROUP BY day, login, login_type, is_scheduled, conclusion"
89
+ " ORDER BY day, login, login_type, is_scheduled, conclusion",
90
+ (SCHEDULE_EVENT, SCHEDULE_EVENT, SCHEDULE_EVENT, low, high),
91
+ )
92
+ return [
93
+ RunDayCount(
94
+ codec.parse_day(day),
95
+ login,
96
+ account_type,
97
+ bool(is_scheduled),
98
+ conclusion,
99
+ runs,
100
+ jobs,
101
+ )
102
+ for day, login, account_type, is_scheduled, conclusion, runs, jobs in rows
103
+ ]
104
+
105
+ def days_missing_jobs(self, from_day: date, to_day: date) -> list[tuple[str, date]]:
106
+ """``(repo, day)`` pairs with a concluded run whose job count is unread."""
107
+ low, high = codec.day_bounds(from_day, to_day)
108
+ rows = self._connection.execute(
109
+ "SELECT DISTINCT repo, substr(created_at, 1, 10) AS day FROM runs"
110
+ " WHERE jobs IS NULL AND conclusion IS NOT NULL"
111
+ " AND created_at >= ? AND created_at < ? ORDER BY repo, day",
112
+ (low, high),
113
+ )
114
+ return [(repo, codec.parse_day(day)) for repo, day in rows]
115
+
116
+ def actors(self) -> list[tuple[str, str | None]]:
117
+ """Every distinct ``(login, type)`` the store credits anything to, sorted.
118
+
119
+ Authors, mergers, closers, reviewers and the actors of runs that
120
+ were not scheduled; logins GitHub reported as missing are left out.
121
+ """
122
+ rows = self._connection.execute(
123
+ "SELECT author, author_type FROM items"
124
+ " UNION SELECT merged_by, merged_by_type FROM items"
125
+ " UNION SELECT closed_by, closed_by_type FROM items"
126
+ " UNION SELECT reviewer, reviewer_type FROM reviews"
127
+ " UNION SELECT actor, actor_type FROM runs WHERE event != ?",
128
+ (SCHEDULE_EVENT,),
129
+ )
130
+ pairs = {(login, kind) for login, kind in rows if login is not None}
131
+ return sorted(pairs, key=lambda pair: (pair[0], pair[1] or ""))
132
+
133
+ def item_actor_counts(
134
+ self,
135
+ kind: str | None,
136
+ column: str,
137
+ from_day: date,
138
+ to_day: date,
139
+ *,
140
+ actor: str = "author",
141
+ unmerged: bool = False,
142
+ ) -> list[ActorCount]:
143
+ """Items per ``actor`` whose ``column`` falls in the days, in scope that day.
144
+
145
+ ``kind`` is ``"issue"``, ``"pr"`` or ``None`` for both; ``column``
146
+ is ``created_at``, ``closed_at`` or ``merged_at``; ``actor`` is
147
+ ``author``, ``merged_by`` or ``closed_by``. With ``unmerged`` only
148
+ items never merged count. Rows are sorted by login and type.
149
+ """
150
+ if kind is not None and kind not in _ITEM_KINDS:
151
+ raise ValueError(f"unknown item kind {kind!r}")
152
+ if column not in _ITEM_EVENT_COLUMNS:
153
+ raise ValueError(f"cannot count items by {column!r}")
154
+ if actor not in _ITEM_ACTORS:
155
+ raise ValueError(f"unknown item actor {actor!r}")
156
+ actor_type = _ITEM_ACTORS[actor]
157
+ low, high = codec.day_bounds(from_day, to_day)
158
+ where = [f"{column} >= ?", f"{column} < ?", _in_scope("items", column)]
159
+ params: list[str] = [low, high]
160
+ if kind is not None:
161
+ where.append("kind = ?")
162
+ params.append(kind)
163
+ if unmerged:
164
+ where.append("merged_at IS NULL")
165
+ rows = self._connection.execute(
166
+ f"SELECT {actor}, {actor_type}, COUNT(*) FROM items"
167
+ f" WHERE {' AND '.join(where)}"
168
+ f" GROUP BY {actor}, {actor_type} ORDER BY {actor}, {actor_type}",
169
+ params,
170
+ )
171
+ return [(login, account_type, count) for login, account_type, count in rows]
172
+
173
+ def review_actor_counts(
174
+ self, from_day: date, to_day: date
175
+ ) -> list[tuple[str | None, str | None, int, int, int]]:
176
+ """Per reviewer: reviews, approvals and changes requested.
177
+
178
+ Reviews submitted from ``from_day`` to ``to_day`` on a day their
179
+ repository was in scope; rows are ``(login, type, reviews,
180
+ approved, changes_requested)``, sorted by login.
181
+ """
182
+ low, high = codec.day_bounds(from_day, to_day)
183
+ rows = self._connection.execute(
184
+ "SELECT reviewer, reviewer_type, COUNT(*),"
185
+ " SUM(state = 'APPROVED'), SUM(state = 'CHANGES_REQUESTED')"
186
+ " FROM reviews WHERE submitted_at >= ? AND submitted_at < ?"
187
+ f" AND {_in_scope('reviews', 'submitted_at')}"
188
+ " GROUP BY reviewer, reviewer_type ORDER BY reviewer, reviewer_type",
189
+ (low, high),
190
+ )
191
+ return [
192
+ (login, account_type, reviews, approved, changes)
193
+ for login, account_type, reviews, approved, changes in rows
194
+ ]
195
+
196
+ def reviewed_pull_requests(
197
+ self, from_day: date, to_day: date
198
+ ) -> list[tuple[str | None, str | None, str, int]]:
199
+ """The distinct pull requests each reviewer reviewed, in scope.
200
+
201
+ Rows are ``(login, type, repo, number)``, sorted, so the caller
202
+ can count distinct pull requests across the forms of one login.
203
+ """
204
+ low, high = codec.day_bounds(from_day, to_day)
205
+ rows = self._connection.execute(
206
+ "SELECT DISTINCT reviewer, reviewer_type, repo, number FROM reviews"
207
+ " WHERE submitted_at >= ? AND submitted_at < ?"
208
+ f" AND {_in_scope('reviews', 'submitted_at')}"
209
+ " ORDER BY reviewer, reviewer_type, repo, number",
210
+ (low, high),
211
+ )
212
+ return [
213
+ (login, account_type, repo, number)
214
+ for login, account_type, repo, number in rows
215
+ ]
216
+
217
+ def run_actor_counts(self, from_day: date, to_day: date) -> list[ActorCount]:
218
+ """Runs per triggering actor in the days, in scope, scheduled runs left out."""
219
+ low, high = codec.day_bounds(from_day, to_day)
220
+ rows = self._connection.execute(
221
+ "SELECT actor, actor_type, COUNT(*) FROM runs"
222
+ " WHERE created_at >= ? AND created_at < ? AND event != ?"
223
+ f" AND {_in_scope('runs', 'created_at')}"
224
+ " GROUP BY actor, actor_type ORDER BY actor, actor_type",
225
+ (low, high, SCHEDULE_EVENT),
226
+ )
227
+ return [(login, account_type, count) for login, account_type, count in rows]
228
+
229
+ def item_repository_counts(
230
+ self, kind: str, column: str, from_day: date, to_day: date
231
+ ) -> list[tuple[str, str | None, str | None, int]]:
232
+ """Items of ``kind`` per repository and author by ``column``, in scope.
233
+
234
+ Rows are ``(repo, login, type, count)``, sorted, so the caller can
235
+ leave out ignored logins as the series do.
236
+ """
237
+ if kind not in _ITEM_KINDS:
238
+ raise ValueError(f"unknown item kind {kind!r}")
239
+ if column not in _ITEM_DAY_COLUMNS:
240
+ raise ValueError(f"cannot count items by {column!r}")
241
+ low, high = codec.day_bounds(from_day, to_day)
242
+ rows = self._connection.execute(
243
+ "SELECT repo, author, author_type, COUNT(*) FROM items"
244
+ f" WHERE kind = ? AND {column} >= ? AND {column} < ?"
245
+ f" AND {_in_scope('items', column)}"
246
+ " GROUP BY repo, author, author_type ORDER BY repo, author, author_type",
247
+ (kind, low, high),
248
+ )
249
+ return [
250
+ (repo, login, account_type, count)
251
+ for repo, login, account_type, count in rows
252
+ ]
253
+
254
+ def run_repository_counts(
255
+ self, from_day: date, to_day: date
256
+ ) -> list[tuple[str, str | None, str | None, bool, int, int]]:
257
+ """Runs and summed jobs per repository and actor, in scope.
258
+
259
+ Rows are ``(repo, login, type, scheduled, runs, jobs)``; a
260
+ scheduled run carries no login, as in `run_day_counts`.
261
+ """
262
+ low, high = codec.day_bounds(from_day, to_day)
263
+ scheduled = "event = ?"
264
+ rows = self._connection.execute(
265
+ "SELECT repo,"
266
+ f" CASE WHEN {scheduled} THEN NULL ELSE actor END AS login,"
267
+ f" CASE WHEN {scheduled} THEN NULL ELSE actor_type END AS login_type,"
268
+ f" {scheduled} AS is_scheduled, COUNT(*), COALESCE(SUM(jobs), 0)"
269
+ " FROM runs WHERE created_at >= ? AND created_at < ?"
270
+ f" AND {_in_scope('runs', 'created_at')}"
271
+ " GROUP BY repo, login, login_type, is_scheduled"
272
+ " ORDER BY repo, login, login_type, is_scheduled",
273
+ (SCHEDULE_EVENT, SCHEDULE_EVENT, SCHEDULE_EVENT, low, high),
274
+ )
275
+ return [
276
+ (repo, login, account_type, bool(is_scheduled), runs, jobs)
277
+ for repo, login, account_type, is_scheduled, runs, jobs in rows
278
+ ]
279
+
280
+ def member_logins(self, orgs: Iterable[str]) -> list[str]:
281
+ """The distinct stored public members of any of ``orgs``, sorted.
282
+
283
+ Organisation names match whatever their case, as GitHub's do, so
284
+ a configured ``ACME`` finds the members stored under ``acme``.
285
+ """
286
+ folded = sorted({org.lower() for org in orgs})
287
+ if not folded:
288
+ return []
289
+ rows = self._connection.execute(
290
+ "SELECT DISTINCT login FROM members"
291
+ f" WHERE lower(org) IN ({marks(len(folded))}) ORDER BY login",
292
+ folded,
293
+ )
294
+ return [login for (login,) in rows]