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,169 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ # SPDX-FileCopyrightText: 2026 The Linux Foundation
3
+ """The store's tables, their version stamp, and read-only inspection.
4
+
5
+ The store is a cache of public data that the tool can always re-read
6
+ from GitHub, so it favours simplicity over migrations: a schema version
7
+ mismatch drops every table and recreates them empty.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import sqlite3
13
+ from dataclasses import dataclass
14
+ from pathlib import Path
15
+
16
+ SCHEMA_VERSION = 1
17
+
18
+ _SCHEMA = (
19
+ """
20
+ CREATE TABLE items (
21
+ repo TEXT NOT NULL,
22
+ number INTEGER NOT NULL,
23
+ node_id TEXT NOT NULL,
24
+ kind TEXT NOT NULL CHECK (kind IN ('issue', 'pr')),
25
+ created_at TEXT NOT NULL,
26
+ closed_at TEXT,
27
+ merged_at TEXT,
28
+ author TEXT,
29
+ author_type TEXT,
30
+ merged_by TEXT,
31
+ merged_by_type TEXT,
32
+ closed_by TEXT,
33
+ closed_by_type TEXT,
34
+ updated_at TEXT NOT NULL,
35
+ reviews_read_at TEXT,
36
+ PRIMARY KEY (repo, number)
37
+ )
38
+ """,
39
+ """
40
+ CREATE TABLE reviews (
41
+ id INTEGER PRIMARY KEY,
42
+ node_id TEXT NOT NULL,
43
+ repo TEXT NOT NULL,
44
+ number INTEGER NOT NULL,
45
+ reviewer TEXT,
46
+ reviewer_type TEXT,
47
+ state TEXT NOT NULL,
48
+ submitted_at TEXT
49
+ )
50
+ """,
51
+ "CREATE INDEX reviews_by_item ON reviews (repo, number)",
52
+ """
53
+ CREATE TABLE runs (
54
+ id INTEGER PRIMARY KEY,
55
+ node_id TEXT NOT NULL,
56
+ repo TEXT NOT NULL,
57
+ workflow_path TEXT NOT NULL,
58
+ event TEXT NOT NULL,
59
+ status TEXT NOT NULL,
60
+ conclusion TEXT,
61
+ created_at TEXT NOT NULL,
62
+ actor TEXT,
63
+ actor_type TEXT,
64
+ attempt INTEGER NOT NULL,
65
+ jobs INTEGER
66
+ )
67
+ """,
68
+ "CREATE INDEX runs_by_repo ON runs (repo, created_at)",
69
+ "CREATE INDEX runs_needing_jobs ON runs (created_at, id) WHERE jobs IS NULL",
70
+ """
71
+ CREATE TABLE members (
72
+ org TEXT NOT NULL,
73
+ login TEXT NOT NULL,
74
+ first_seen TEXT NOT NULL,
75
+ last_seen TEXT NOT NULL,
76
+ PRIMARY KEY (org, login)
77
+ )
78
+ """,
79
+ """
80
+ CREATE TABLE sync_state (
81
+ repo TEXT NOT NULL,
82
+ metric TEXT NOT NULL,
83
+ watermark TEXT,
84
+ etag TEXT,
85
+ oldest TEXT,
86
+ last_sync_at TEXT,
87
+ swept_to TEXT,
88
+ PRIMARY KEY (repo, metric)
89
+ )
90
+ """,
91
+ """
92
+ CREATE TABLE coverage (
93
+ repo TEXT NOT NULL,
94
+ metric TEXT NOT NULL,
95
+ from_day TEXT NOT NULL,
96
+ to_day TEXT NOT NULL,
97
+ PRIMARY KEY (repo, metric, from_day)
98
+ )
99
+ """,
100
+ """
101
+ CREATE TABLE scope (
102
+ repo TEXT NOT NULL,
103
+ from_day TEXT NOT NULL,
104
+ to_day TEXT,
105
+ PRIMARY KEY (repo, from_day)
106
+ )
107
+ """,
108
+ )
109
+
110
+ TABLES = ("items", "reviews", "runs", "members", "sync_state", "coverage", "scope")
111
+ REPOSITORY_TABLES = ("items", "reviews", "runs", "sync_state", "coverage", "scope")
112
+
113
+
114
+ def create_schema(connection: sqlite3.Connection) -> None:
115
+ """Drop every table and create the current schema, stamped with its version.
116
+
117
+ Call inside a transaction. Statements run one at a time;
118
+ ``executescript`` would commit first and could leave a half-built
119
+ schema behind.
120
+ """
121
+ names = [
122
+ row[0]
123
+ for row in connection.execute(
124
+ "SELECT name FROM sqlite_master"
125
+ " WHERE type = 'table' AND name NOT GLOB 'sqlite_*'"
126
+ )
127
+ ]
128
+ for name in names:
129
+ quoted = name.replace('"', '""')
130
+ connection.execute(f'DROP TABLE "{quoted}"')
131
+ for statement in _SCHEMA:
132
+ connection.execute(statement)
133
+ connection.execute(f"PRAGMA user_version = {SCHEMA_VERSION}")
134
+
135
+
136
+ @dataclass(frozen=True)
137
+ class StoreInfo:
138
+ """What `describe` reports about one store file."""
139
+
140
+ path: Path
141
+ size: int
142
+ schema_version: int
143
+ counts: dict[str, int]
144
+
145
+
146
+ def describe(path: Path) -> StoreInfo:
147
+ """Size, schema version and row counts of the store at ``path``, read-only.
148
+
149
+ Unlike opening a `Store`, this never changes the file, so it reports
150
+ a store stamped with another schema version as it stands.
151
+ """
152
+ uri = Path(path).resolve().as_uri() + "?mode=ro"
153
+ connection = sqlite3.connect(uri, uri=True)
154
+ try:
155
+ version = connection.execute("PRAGMA user_version").fetchone()[0]
156
+ present = {
157
+ row[0]
158
+ for row in connection.execute(
159
+ "SELECT name FROM sqlite_master WHERE type = 'table'"
160
+ )
161
+ }
162
+ counts = {
163
+ table: connection.execute(f"SELECT COUNT(*) FROM {table}").fetchone()[0]
164
+ for table in TABLES
165
+ if table in present
166
+ }
167
+ finally:
168
+ connection.close()
169
+ return StoreInfo(Path(path), Path(path).stat().st_size, version, counts)
@@ -0,0 +1,299 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ # SPDX-FileCopyrightText: 2026 The Linux Foundation
3
+ """The SQLite store: one connection, every query (design §6.1)."""
4
+
5
+ from __future__ import annotations
6
+
7
+ from collections.abc import Iterable
8
+ from datetime import date, datetime, timedelta
9
+
10
+ from . import codec
11
+ from .aggregates import AggregateStore
12
+ from .base import assignments, marks
13
+ from .models import DayRange, Item, Member, Run, SyncState
14
+ from .schema import REPOSITORY_TABLES, TABLES
15
+
16
+ _UPSERT_SYNC = (
17
+ f"INSERT INTO sync_state ({', '.join(codec.SYNC_COLUMNS)}) "
18
+ f"VALUES ({marks(len(codec.SYNC_COLUMNS))}) "
19
+ "ON CONFLICT (repo, metric) DO UPDATE SET " + assignments(codec.SYNC_COLUMNS[2:])
20
+ )
21
+
22
+
23
+ class Store(AggregateStore):
24
+ """One SQLite store, used as a context manager.
25
+
26
+ Every write method runs in one transaction, so an exception, or a
27
+ crash, part-way through a write leaves the previous state.
28
+ ``Store(Path(":memory:"))`` gives an in-memory store.
29
+ """
30
+
31
+ # Members
32
+
33
+ def replace_members(self, org: str, logins: Iterable[str], today: date) -> None:
34
+ """Make ``logins`` the public members of ``org`` as seen ``today``.
35
+
36
+ Organisation names match whatever their case, as GitHub's do, so
37
+ the rows of every spelling of ``org`` are replaced and stored
38
+ under ``org``. Logins already stored keep their earliest
39
+ ``first_seen``; logins no longer listed are deleted.
40
+ """
41
+ current = sorted(set(logins))
42
+ seen = codec.day(today)
43
+ with self._transaction() as connection:
44
+ first_seen: dict[str, str] = {}
45
+ for login, first in connection.execute(
46
+ "SELECT login, first_seen FROM members WHERE lower(org) = lower(?)",
47
+ (org,),
48
+ ):
49
+ first_seen[login] = min(first_seen.get(login, first), first)
50
+ connection.execute(
51
+ "DELETE FROM members WHERE lower(org) = lower(?)", (org,)
52
+ )
53
+ connection.executemany(
54
+ "INSERT INTO members (org, login, first_seen, last_seen)"
55
+ " VALUES (?, ?, ?, ?)",
56
+ ((org, login, first_seen.get(login, seen), seen) for login in current),
57
+ )
58
+
59
+ def members(self, org: str) -> list[Member]:
60
+ """The stored public members of ``org``, by login."""
61
+ rows = self._connection.execute(
62
+ "SELECT * FROM members WHERE org = ? ORDER BY login", (org,)
63
+ )
64
+ return [codec.member_from_row(row) for row in rows]
65
+
66
+ # Sync state
67
+
68
+ def sync_state(self, repo: str, metric: str) -> SyncState | None:
69
+ """The sync state of one metric of one repository, if any."""
70
+ row = self._connection.execute(
71
+ "SELECT * FROM sync_state WHERE repo = ? AND metric = ?", (repo, metric)
72
+ ).fetchone()
73
+ return None if row is None else codec.sync_from_row(row)
74
+
75
+ def set_sync_state(self, state: SyncState) -> None:
76
+ """Store ``state``, replacing any earlier state for its repository and metric."""
77
+ with self._transaction() as connection:
78
+ connection.execute(_UPSERT_SYNC, codec.sync_row(state))
79
+
80
+ def store_item_page(self, items: Iterable[Item], state: SyncState) -> None:
81
+ """Upsert one listing page of ``items`` and ``state`` in one transaction.
82
+
83
+ The watermark in ``state`` then never runs ahead of the items it
84
+ describes, nor falls behind them (design §6.5). An item listed
85
+ with ``updated_at`` equal to its ``reviews_read_at`` has that
86
+ marker cleared: both hold whole seconds, so an update in the
87
+ second of the read cannot be told from one before it, and
88
+ enrichment reads the item again (design §6.3).
89
+ """
90
+ page = list(items)
91
+ with self._transaction() as connection:
92
+ self.upsert_items(page)
93
+ connection.executemany(
94
+ "UPDATE items SET reviews_read_at = NULL"
95
+ " WHERE repo = ? AND number = ? AND reviews_read_at = updated_at",
96
+ ((item.repo, item.number) for item in page),
97
+ )
98
+ self.set_sync_state(state)
99
+
100
+ def store_run_page(self, runs: Iterable[Run], state: SyncState) -> None:
101
+ """Upsert ``runs`` and store ``state`` in one transaction.
102
+
103
+ The watermark in ``state`` then never runs ahead of the runs it
104
+ describes, nor falls behind them (design §6.5).
105
+ """
106
+ with self._transaction():
107
+ self.upsert_runs(runs)
108
+ self.set_sync_state(state)
109
+
110
+ def restart_item_sync(
111
+ self, state: SyncState, reread_before: datetime | None = None
112
+ ) -> None:
113
+ """Store a restarted ``state`` and, given ``reread_before``, mark reviews.
114
+
115
+ With ``reread_before``, the pull requests of ``state.repo`` created
116
+ before it lose their ``reviews_read_at``: a prune drops reviews
117
+ submitted before its day but keeps a pull request updated since,
118
+ so a wider window reads the dropped reviews again. Both commit in
119
+ one transaction, before any page is requested, so a retry that
120
+ lists nothing does not mark pull requests already read again.
121
+ """
122
+ with self._transaction() as connection:
123
+ if reread_before is not None:
124
+ connection.execute(
125
+ "UPDATE items SET reviews_read_at = NULL"
126
+ " WHERE repo = ? AND kind = 'pr' AND created_at < ?",
127
+ (state.repo, codec.timestamp(reread_before)),
128
+ )
129
+ self.set_sync_state(state)
130
+
131
+ # Coverage
132
+
133
+ def add_coverage(
134
+ self, repo: str, metric: str, from_day: date, to_day: date
135
+ ) -> None:
136
+ """Mark ``from_day`` to ``to_day`` complete, merging touching ranges."""
137
+ if to_day < from_day:
138
+ raise ValueError(
139
+ f"coverage range ends before it starts: {from_day}..{to_day}"
140
+ )
141
+ one = timedelta(days=1)
142
+ with self._transaction() as connection:
143
+ rows = list(
144
+ connection.execute(
145
+ "SELECT from_day, to_day FROM coverage"
146
+ " WHERE repo = ? AND metric = ? AND from_day <= ? AND to_day >= ?",
147
+ (repo, metric, codec.day(to_day + one), codec.day(from_day - one)),
148
+ )
149
+ )
150
+ start = min([codec.day(from_day), *(row[0] for row in rows)])
151
+ end = max([codec.day(to_day), *(row[1] for row in rows)])
152
+ connection.executemany(
153
+ "DELETE FROM coverage WHERE repo = ? AND metric = ? AND from_day = ?",
154
+ ((repo, metric, row[0]) for row in rows),
155
+ )
156
+ connection.execute(
157
+ "INSERT INTO coverage (repo, metric, from_day, to_day)"
158
+ " VALUES (?, ?, ?, ?)",
159
+ (repo, metric, start, end),
160
+ )
161
+
162
+ def coverage(self, repo: str, metric: str) -> list[DayRange]:
163
+ """The complete day ranges of one metric of one repository, in order."""
164
+ rows = self._connection.execute(
165
+ "SELECT from_day, to_day FROM coverage WHERE repo = ? AND metric = ?"
166
+ " ORDER BY from_day",
167
+ (repo, metric),
168
+ )
169
+ return [DayRange(codec.parse_day(a), codec.parse_day(b)) for a, b in rows]
170
+
171
+ def covered(self, repo: str, metric: str, day: date) -> bool:
172
+ """Whether ``day`` lies in a complete range of the metric."""
173
+ text = codec.day(day)
174
+ row = self._connection.execute(
175
+ "SELECT 1 FROM coverage WHERE repo = ? AND metric = ?"
176
+ " AND from_day <= ? AND to_day >= ? LIMIT 1",
177
+ (repo, metric, text, text),
178
+ ).fetchone()
179
+ return row is not None
180
+
181
+ # Scope
182
+
183
+ def enter_scope(self, repo: str, from_day: date) -> None:
184
+ """Record ``repo`` in scope from ``from_day``; a no-op while already in scope.
185
+
186
+ Re-entering on or before the day a closed interval ended reopens
187
+ that interval rather than starting a new one.
188
+ """
189
+ text = codec.day(from_day)
190
+ with self._transaction() as connection:
191
+ if connection.execute(
192
+ "SELECT 1 FROM scope WHERE repo = ? AND to_day IS NULL", (repo,)
193
+ ).fetchone():
194
+ return
195
+ reopened = connection.execute(
196
+ "UPDATE scope SET to_day = NULL WHERE repo = ?"
197
+ " AND from_day <= ? AND to_day >= ?",
198
+ (repo, text, text),
199
+ )
200
+ if reopened.rowcount == 0:
201
+ connection.execute(
202
+ "INSERT INTO scope (repo, from_day, to_day) VALUES (?, ?, NULL)",
203
+ (repo, text),
204
+ )
205
+
206
+ def leave_scope(self, repo: str, day: date) -> None:
207
+ """Record ``repo`` out of scope from ``day`` on; ``day`` itself is out.
208
+
209
+ An interval that opened on ``day`` closes empty rather than going,
210
+ so the store still records that ``repo`` was seen.
211
+ """
212
+ text = codec.day(day)
213
+ with self._transaction() as connection:
214
+ connection.execute(
215
+ "DELETE FROM scope WHERE repo = ? AND to_day IS NULL AND from_day > ?",
216
+ (repo, text),
217
+ )
218
+ connection.execute(
219
+ "UPDATE scope SET to_day = ? WHERE repo = ? AND to_day IS NULL",
220
+ (text, repo),
221
+ )
222
+
223
+ def in_scope(self, day: date) -> list[str]:
224
+ """The repositories in scope on ``day``, sorted."""
225
+ text = codec.day(day)
226
+ rows = self._connection.execute(
227
+ "SELECT DISTINCT repo FROM scope WHERE from_day <= ?"
228
+ " AND (to_day IS NULL OR to_day > ?) ORDER BY repo",
229
+ (text, text),
230
+ )
231
+ return [row[0] for row in rows]
232
+
233
+ def stored_repositories(self) -> list[str]:
234
+ """Every repository with a row in any per-repository table, sorted."""
235
+ union = " UNION ".join(f"SELECT repo FROM {t}" for t in REPOSITORY_TABLES)
236
+ rows = self._connection.execute(f"{union} ORDER BY repo")
237
+ return [row[0] for row in rows]
238
+
239
+ # Privacy and housekeeping
240
+
241
+ def purge_repository(self, repo: str) -> None:
242
+ """Delete every row for ``repo`` from every table (design §5)."""
243
+ with self._transaction() as connection:
244
+ for table in REPOSITORY_TABLES:
245
+ connection.execute(f"DELETE FROM {table} WHERE repo = ?", (repo,))
246
+
247
+ def prune(self, before_day: date) -> dict[str, int]:
248
+ """Drop history that ended before ``before_day``; return rows deleted per table.
249
+
250
+ Items go once created, closed and last updated before the day, so
251
+ an item still open stays, and so does one updated since, which
252
+ enrichment may still re-read; reviews and runs go by their own timestamps;
253
+ coverage ranges are clipped to start on the day; scope intervals
254
+ that ended by the day go, except each repository's latest, which
255
+ stays so a repository that returns is known to have been seen.
256
+ Each sync has its ``oldest`` raised to the day, since the store no
257
+ longer holds what it read before it.
258
+ """
259
+ low, _ = codec.day_bounds(before_day, before_day)
260
+ text = codec.day(before_day)
261
+ deleted: dict[str, int] = {}
262
+ with self._transaction() as connection:
263
+ deleted["items"] = connection.execute(
264
+ "DELETE FROM items WHERE created_at < ?"
265
+ " AND closed_at IS NOT NULL AND closed_at < ? AND updated_at < ?",
266
+ (low, low, low),
267
+ ).rowcount
268
+ deleted["reviews"] = connection.execute(
269
+ "DELETE FROM reviews WHERE submitted_at < ?", (low,)
270
+ ).rowcount
271
+ deleted["runs"] = connection.execute(
272
+ "DELETE FROM runs WHERE created_at < ?", (low,)
273
+ ).rowcount
274
+ deleted["coverage"] = connection.execute(
275
+ "DELETE FROM coverage WHERE to_day < ?", (text,)
276
+ ).rowcount
277
+ connection.execute(
278
+ "UPDATE coverage SET from_day = ? WHERE from_day < ?", (text, text)
279
+ )
280
+ connection.execute(
281
+ "UPDATE sync_state SET oldest = ? WHERE oldest < ?",
282
+ (low, low),
283
+ )
284
+ deleted["scope"] = connection.execute(
285
+ "DELETE FROM scope WHERE to_day IS NOT NULL AND to_day <= ?"
286
+ " AND from_day < (SELECT MAX(from_day) FROM scope AS latest"
287
+ " WHERE latest.repo = scope.repo)",
288
+ (text,),
289
+ ).rowcount
290
+ return deleted
291
+
292
+ def counts(self) -> dict[str, int]:
293
+ """Row count of each table."""
294
+ return {
295
+ table: self._connection.execute(f"SELECT COUNT(*) FROM {table}").fetchone()[
296
+ 0
297
+ ]
298
+ for table in TABLES
299
+ }