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,163 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ # SPDX-FileCopyrightText: 2026 The Linux Foundation
3
+ """The connection, transaction and chunked-query plumbing every store shares."""
4
+
5
+ from __future__ import annotations
6
+
7
+ import sqlite3
8
+ from collections.abc import Iterable, Iterator, Sequence
9
+ from contextlib import contextmanager
10
+ from pathlib import Path
11
+ from types import TracebackType
12
+ from typing import Any, Self
13
+
14
+ from .schema import SCHEMA_VERSION, create_schema
15
+
16
+ # Older SQLite builds bind at most 999 parameters in one statement; 500
17
+ # leaves room for the other parameters of a query.
18
+ CHUNK = 500
19
+
20
+
21
+ def chunks(values: Sequence[Any]) -> Iterator[Sequence[Any]]:
22
+ """``values`` in slices of at most `CHUNK`."""
23
+ for start in range(0, len(values), CHUNK):
24
+ yield values[start : start + CHUNK]
25
+
26
+
27
+ def marks(count: int) -> str:
28
+ """``?, ?, ...`` with ``count`` placeholders."""
29
+ return ", ".join("?" * count)
30
+
31
+
32
+ def assignments(columns: Iterable[str]) -> str:
33
+ """``column = excluded.column`` for each of ``columns``."""
34
+ return ", ".join(f"{column} = excluded.{column}" for column in columns)
35
+
36
+
37
+ class StoreBase:
38
+ """The connection and transaction handling under `Store`."""
39
+
40
+ def __init__(self, path: Path) -> None:
41
+ """Open, creating it and its directory if needed, the store at ``path``."""
42
+ self.path = Path(path)
43
+ self._savepoints = 0
44
+ if str(path) == ":memory:":
45
+ target = ":memory:"
46
+ else:
47
+ self.path.parent.mkdir(parents=True, exist_ok=True)
48
+ target = str(self.path)
49
+ self._connection = sqlite3.connect(target, isolation_level=None)
50
+ self._connection.row_factory = sqlite3.Row
51
+ try:
52
+ self._ensure_schema()
53
+ except BaseException:
54
+ self._connection.close()
55
+ raise
56
+
57
+ def __enter__(self) -> Self:
58
+ """Return the store itself."""
59
+ return self
60
+
61
+ def __exit__(
62
+ self,
63
+ exc_type: type[BaseException] | None,
64
+ exc: BaseException | None,
65
+ traceback: TracebackType | None,
66
+ ) -> None:
67
+ """Close the connection."""
68
+ self.close()
69
+
70
+ def close(self) -> None:
71
+ """Close the connection."""
72
+ self._connection.close()
73
+
74
+ @property
75
+ def connection(self) -> sqlite3.Connection:
76
+ """The underlying connection, for inspection."""
77
+ return self._connection
78
+
79
+ @contextmanager
80
+ def _transaction(self, mode: str = "") -> Iterator[sqlite3.Connection]:
81
+ """Run the block in one transaction; roll back on any exception.
82
+
83
+ ``mode`` is ``""`` or ``"IMMEDIATE"``, which takes the write lock
84
+ at once. A failed ``COMMIT`` rolls back too, so no transaction is
85
+ left open for a later write to join and never commit. Inside an
86
+ open transaction the block runs under a savepoint instead, so a
87
+ failure undoes that block alone and the caller may carry on.
88
+ """
89
+ connection = self._connection
90
+ if connection.in_transaction:
91
+ with self._savepoint(connection):
92
+ yield connection
93
+ return
94
+ connection.execute(f"BEGIN {mode}".strip())
95
+ try:
96
+ yield connection
97
+ connection.execute("COMMIT")
98
+ except BaseException:
99
+ if connection.in_transaction:
100
+ connection.execute("ROLLBACK")
101
+ raise
102
+
103
+ @contextmanager
104
+ def _savepoint(self, connection: sqlite3.Connection) -> Iterator[None]:
105
+ """Run the block under a savepoint; roll back to it on any exception."""
106
+ self._savepoints += 1
107
+ name = f"write_{self._savepoints}"
108
+ connection.execute(f"SAVEPOINT {name}")
109
+ try:
110
+ yield
111
+ except BaseException:
112
+ # SQLite may already have rolled back the whole transaction.
113
+ if connection.in_transaction:
114
+ connection.execute(f"ROLLBACK TO {name}")
115
+ connection.execute(f"RELEASE {name}")
116
+ raise
117
+ else:
118
+ connection.execute(f"RELEASE {name}")
119
+ finally:
120
+ self._savepoints -= 1
121
+
122
+ def schema_version(self) -> int:
123
+ """The schema version stamped in the file."""
124
+ return int(self._connection.execute("PRAGMA user_version").fetchone()[0])
125
+
126
+ def _ensure_schema(self) -> None:
127
+ """Drop and recreate every table unless the file carries `SCHEMA_VERSION`."""
128
+ if self.schema_version() == SCHEMA_VERSION:
129
+ return
130
+ # Another process may rebuild the store between the check above and
131
+ # taking the write lock; check again under the lock so its rows stay.
132
+ with self._transaction("IMMEDIATE") as connection:
133
+ if self.schema_version() != SCHEMA_VERSION:
134
+ create_schema(connection)
135
+
136
+ def _select_in(
137
+ self,
138
+ sql: str,
139
+ params: Sequence[Any],
140
+ column: str,
141
+ values: Sequence[Any] | None,
142
+ order: str,
143
+ ) -> list[sqlite3.Row]:
144
+ """Rows of ``sql``, restricted to ``column IN values`` when given.
145
+
146
+ The IN list is chunked at `CHUNK` parameters; ``order`` sorts the
147
+ combined result.
148
+ """
149
+ if values is None:
150
+ return list(self._connection.execute(f"{sql} ORDER BY {order}", params))
151
+ rows: list[sqlite3.Row] = []
152
+ unique = sorted(set(values))
153
+ for chunk in chunks(unique):
154
+ query = f"{sql} AND {column} IN ({marks(len(chunk))})"
155
+ rows.extend(self._connection.execute(query, [*params, *chunk]))
156
+ keys = [part.strip() for part in order.split(",")]
157
+ rows.sort(key=lambda row: tuple(_sortable(row[key]) for key in keys))
158
+ return rows
159
+
160
+
161
+ def _sortable(value: Any) -> tuple[bool, Any]:
162
+ """A sort key that places ``None`` first and compares the rest."""
163
+ return (value is not None, value)
@@ -0,0 +1,263 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ # SPDX-FileCopyrightText: 2026 The Linux Foundation
3
+ """Conversion between the store's records and SQLite rows.
4
+
5
+ Timestamps are stored as ISO-8601 UTC text (``2026-03-01T12:00:00Z``)
6
+ and days as ``YYYY-MM-DD``, so text comparison in SQL orders them
7
+ correctly.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import sqlite3
13
+ from datetime import UTC, date, datetime, timedelta
14
+ from typing import Any
15
+
16
+ from .models import Item, Member, Review, Run, SyncState
17
+
18
+ _FORMAT = "%Y-%m-%dT%H:%M:%SZ"
19
+
20
+
21
+ def timestamp(value: datetime | None) -> str | None:
22
+ """``value`` as ISO-8601 UTC text; a naive or non-datetime value is an error."""
23
+ if value is None:
24
+ return None
25
+ if not isinstance(value, datetime):
26
+ raise TypeError(f"expected a datetime, got {type(value).__name__}")
27
+ if value.tzinfo is None:
28
+ raise ValueError("timestamps must be timezone-aware")
29
+ return value.astimezone(UTC).strftime(_FORMAT)
30
+
31
+
32
+ def parse_timestamp(text: str | None) -> datetime | None:
33
+ """The UTC `datetime` that `timestamp` wrote as ``text``."""
34
+ if text is None:
35
+ return None
36
+ return datetime.strptime(text, _FORMAT).replace(tzinfo=UTC)
37
+
38
+
39
+ def _required(text: str) -> datetime:
40
+ """`parse_timestamp` for a column that is never ``NULL``."""
41
+ return datetime.strptime(text, _FORMAT).replace(tzinfo=UTC)
42
+
43
+
44
+ def day(value: date) -> str:
45
+ """``value`` as ``YYYY-MM-DD``; a `datetime` is not a day."""
46
+ if isinstance(value, datetime) or not isinstance(value, date):
47
+ raise TypeError(f"expected a date, got {type(value).__name__}")
48
+ return value.isoformat()
49
+
50
+
51
+ def parse_day(text: str) -> date:
52
+ """The `date` that `day` wrote as ``text``."""
53
+ return date.fromisoformat(text)
54
+
55
+
56
+ def day_bounds(from_day: date, to_day: date) -> tuple[str, str]:
57
+ """Timestamp text bounding the days ``from_day`` to ``to_day`` inclusive.
58
+
59
+ A timestamp ``t`` falls in the range when ``low <= t < high``.
60
+ """
61
+ low = f"{day(from_day)}T00:00:00Z"
62
+ high = f"{day(to_day + timedelta(days=1))}T00:00:00Z"
63
+ return low, high
64
+
65
+
66
+ ITEM_COLUMNS = (
67
+ "repo",
68
+ "number",
69
+ "node_id",
70
+ "kind",
71
+ "created_at",
72
+ "closed_at",
73
+ "merged_at",
74
+ "author",
75
+ "author_type",
76
+ "merged_by",
77
+ "merged_by_type",
78
+ "closed_by",
79
+ "closed_by_type",
80
+ "updated_at",
81
+ "reviews_read_at",
82
+ )
83
+
84
+
85
+ def item_row(item: Item) -> tuple[Any, ...]:
86
+ """``item`` as a row in `ITEM_COLUMNS` order."""
87
+ return (
88
+ item.repo,
89
+ item.number,
90
+ item.node_id,
91
+ item.kind,
92
+ timestamp(item.created_at),
93
+ timestamp(item.closed_at),
94
+ timestamp(item.merged_at),
95
+ item.author,
96
+ item.author_type,
97
+ item.merged_by,
98
+ item.merged_by_type,
99
+ item.closed_by,
100
+ item.closed_by_type,
101
+ timestamp(item.updated_at),
102
+ timestamp(item.reviews_read_at),
103
+ )
104
+
105
+
106
+ def item_from_row(row: sqlite3.Row) -> Item:
107
+ """The `Item` stored in ``row``."""
108
+ return Item(
109
+ repo=row["repo"],
110
+ number=row["number"],
111
+ node_id=row["node_id"],
112
+ kind=row["kind"],
113
+ created_at=_required(row["created_at"]),
114
+ closed_at=parse_timestamp(row["closed_at"]),
115
+ merged_at=parse_timestamp(row["merged_at"]),
116
+ author=row["author"],
117
+ author_type=row["author_type"],
118
+ updated_at=_required(row["updated_at"]),
119
+ merged_by=row["merged_by"],
120
+ merged_by_type=row["merged_by_type"],
121
+ closed_by=row["closed_by"],
122
+ closed_by_type=row["closed_by_type"],
123
+ reviews_read_at=parse_timestamp(row["reviews_read_at"]),
124
+ )
125
+
126
+
127
+ REVIEW_COLUMNS = (
128
+ "id",
129
+ "node_id",
130
+ "repo",
131
+ "number",
132
+ "reviewer",
133
+ "reviewer_type",
134
+ "state",
135
+ "submitted_at",
136
+ )
137
+
138
+
139
+ def review_row(review: Review) -> tuple[Any, ...]:
140
+ """``review`` as a row in `REVIEW_COLUMNS` order."""
141
+ return (
142
+ review.id,
143
+ review.node_id,
144
+ review.repo,
145
+ review.number,
146
+ review.reviewer,
147
+ review.reviewer_type,
148
+ review.state,
149
+ timestamp(review.submitted_at),
150
+ )
151
+
152
+
153
+ def review_from_row(row: sqlite3.Row) -> Review:
154
+ """The `Review` stored in ``row``."""
155
+ return Review(
156
+ id=row["id"],
157
+ node_id=row["node_id"],
158
+ repo=row["repo"],
159
+ number=row["number"],
160
+ reviewer=row["reviewer"],
161
+ reviewer_type=row["reviewer_type"],
162
+ state=row["state"],
163
+ submitted_at=parse_timestamp(row["submitted_at"]),
164
+ )
165
+
166
+
167
+ RUN_COLUMNS = (
168
+ "id",
169
+ "node_id",
170
+ "repo",
171
+ "workflow_path",
172
+ "event",
173
+ "status",
174
+ "conclusion",
175
+ "created_at",
176
+ "actor",
177
+ "actor_type",
178
+ "attempt",
179
+ "jobs",
180
+ )
181
+
182
+
183
+ def run_row(run: Run) -> tuple[Any, ...]:
184
+ """``run`` as a row in `RUN_COLUMNS` order."""
185
+ return (
186
+ run.id,
187
+ run.node_id,
188
+ run.repo,
189
+ run.workflow_path,
190
+ run.event,
191
+ run.status,
192
+ run.conclusion,
193
+ timestamp(run.created_at),
194
+ run.actor,
195
+ run.actor_type,
196
+ run.attempt,
197
+ run.jobs,
198
+ )
199
+
200
+
201
+ def run_from_row(row: sqlite3.Row) -> Run:
202
+ """The `Run` stored in ``row``."""
203
+ return Run(
204
+ id=row["id"],
205
+ node_id=row["node_id"],
206
+ repo=row["repo"],
207
+ workflow_path=row["workflow_path"],
208
+ event=row["event"],
209
+ status=row["status"],
210
+ conclusion=row["conclusion"],
211
+ created_at=_required(row["created_at"]),
212
+ actor=row["actor"],
213
+ actor_type=row["actor_type"],
214
+ attempt=row["attempt"],
215
+ jobs=row["jobs"],
216
+ )
217
+
218
+
219
+ def member_from_row(row: sqlite3.Row) -> Member:
220
+ """The `Member` stored in ``row``."""
221
+ return Member(
222
+ org=row["org"],
223
+ login=row["login"],
224
+ first_seen=parse_day(row["first_seen"]),
225
+ last_seen=parse_day(row["last_seen"]),
226
+ )
227
+
228
+
229
+ SYNC_COLUMNS = (
230
+ "repo",
231
+ "metric",
232
+ "watermark",
233
+ "etag",
234
+ "oldest",
235
+ "last_sync_at",
236
+ "swept_to",
237
+ )
238
+
239
+
240
+ def sync_row(state: SyncState) -> tuple[Any, ...]:
241
+ """``state`` as a row in `SYNC_COLUMNS` order."""
242
+ return (
243
+ state.repo,
244
+ state.metric,
245
+ timestamp(state.watermark),
246
+ state.etag,
247
+ timestamp(state.oldest),
248
+ timestamp(state.last_sync_at),
249
+ timestamp(state.swept_to),
250
+ )
251
+
252
+
253
+ def sync_from_row(row: sqlite3.Row) -> SyncState:
254
+ """The `SyncState` stored in ``row``."""
255
+ return SyncState(
256
+ repo=row["repo"],
257
+ metric=row["metric"],
258
+ watermark=parse_timestamp(row["watermark"]),
259
+ etag=row["etag"],
260
+ oldest=parse_timestamp(row["oldest"]),
261
+ last_sync_at=parse_timestamp(row["last_sync_at"]),
262
+ swept_to=parse_timestamp(row["swept_to"]),
263
+ )
@@ -0,0 +1,136 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ # SPDX-FileCopyrightText: 2026 The Linux Foundation
3
+ """Typed records the store reads and writes (design §6.1).
4
+
5
+ Timestamps are timezone-aware `datetime` values and days are `date`
6
+ values; the codec module turns both into ISO-8601 UTC text for SQLite.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from dataclasses import dataclass
12
+ from datetime import date, datetime
13
+
14
+
15
+ @dataclass(frozen=True)
16
+ class Item:
17
+ """One issue or pull request; the ``*_by`` fields stay ``None`` until enriched."""
18
+
19
+ repo: str
20
+ number: int
21
+ node_id: str
22
+ kind: str
23
+ created_at: datetime
24
+ closed_at: datetime | None
25
+ merged_at: datetime | None
26
+ author: str | None
27
+ author_type: str | None
28
+ updated_at: datetime
29
+ merged_by: str | None = None
30
+ merged_by_type: str | None = None
31
+ closed_by: str | None = None
32
+ closed_by_type: str | None = None
33
+ reviews_read_at: datetime | None = None
34
+
35
+
36
+ @dataclass(frozen=True)
37
+ class Enrichment:
38
+ """What one GraphQL read adds to a stored item (design §6.3)."""
39
+
40
+ repo: str
41
+ number: int
42
+ merged_by: str | None
43
+ merged_by_type: str | None
44
+ closed_by: str | None
45
+ closed_by_type: str | None
46
+ read_at: datetime
47
+
48
+
49
+ @dataclass(frozen=True)
50
+ class Review:
51
+ """One submitted pull request review."""
52
+
53
+ id: int
54
+ node_id: str
55
+ repo: str
56
+ number: int
57
+ reviewer: str | None
58
+ reviewer_type: str | None
59
+ state: str
60
+ submitted_at: datetime | None
61
+
62
+
63
+ @dataclass(frozen=True)
64
+ class Run:
65
+ """One workflow run; ``jobs`` stays ``None`` until enriched (design §6.4)."""
66
+
67
+ id: int
68
+ node_id: str
69
+ repo: str
70
+ workflow_path: str
71
+ event: str
72
+ status: str
73
+ conclusion: str | None
74
+ created_at: datetime
75
+ actor: str | None
76
+ actor_type: str | None
77
+ attempt: int
78
+ jobs: int | None = None
79
+
80
+
81
+ @dataclass(frozen=True)
82
+ class Member:
83
+ """One public member of an organisation, and when the tool saw them."""
84
+
85
+ org: str
86
+ login: str
87
+ first_seen: date
88
+ last_seen: date
89
+
90
+
91
+ @dataclass(frozen=True)
92
+ class SyncState:
93
+ """How far the sync of one metric of one repository got (design §6.5)."""
94
+
95
+ repo: str
96
+ metric: str
97
+ watermark: datetime | None = None
98
+ etag: str | None = None
99
+ oldest: datetime | None = None
100
+ last_sync_at: datetime | None = None
101
+ swept_to: datetime | None = None
102
+
103
+
104
+ @dataclass(frozen=True)
105
+ class DayRange:
106
+ """A closed range of days, both ends included."""
107
+
108
+ from_day: date
109
+ to_day: date
110
+
111
+
112
+ @dataclass(frozen=True)
113
+ class ActorDayCount:
114
+ """How many events one actor made on one day, from an aggregate query."""
115
+
116
+ day: date
117
+ login: str | None
118
+ account_type: str | None
119
+ count: int
120
+
121
+
122
+ @dataclass(frozen=True)
123
+ class RunDayCount:
124
+ """Runs and their jobs on one day, for one actor, event kind and conclusion.
125
+
126
+ A scheduled run carries no ``login`` or ``account_type``: it is
127
+ credited to no one (design §7.3).
128
+ """
129
+
130
+ day: date
131
+ login: str | None
132
+ account_type: str | None
133
+ scheduled: bool
134
+ conclusion: str | None
135
+ runs: int
136
+ jobs: int
@@ -0,0 +1,36 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ # SPDX-FileCopyrightText: 2026 The Linux Foundation
3
+ """Where a store lives under the cache directory."""
4
+
5
+ from __future__ import annotations
6
+
7
+ import re
8
+ from pathlib import Path
9
+
10
+ STORE_FILE = "stats.sqlite"
11
+
12
+ _UNSAFE = re.compile(r"[^A-Za-z0-9_.-]")
13
+
14
+
15
+ def path_component(text: str, what: str = "name") -> str:
16
+ """``text`` reduced to a safe, lower-case path component; ``what`` names it in errors."""
17
+ safe = _UNSAFE.sub("_", text.lower()).lstrip(".-")
18
+ if not safe:
19
+ raise ValueError(f"{what} {text!r} leaves no usable path component")
20
+ return safe
21
+
22
+
23
+ def store_path(cache_dir: Path, api_host: str, owner: str) -> Path:
24
+ """``<cache_dir>/<api_host>/<owner>/stats.sqlite``, both components sanitised.
25
+
26
+ Each component keeps only ``[A-Za-z0-9_.-]``, lower-cased, with
27
+ leading dots and dashes stripped, so no owner name can climb out of
28
+ the cache directory; owners compare case-insensitively on GitHub, so
29
+ ``Acme`` and ``acme`` share a store.
30
+ """
31
+ return (
32
+ Path(cache_dir)
33
+ / path_component(api_host, "API host")
34
+ / path_component(owner, "owner")
35
+ / STORE_FILE
36
+ )