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,128 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ # SPDX-FileCopyrightText: 2026 The Linux Foundation
3
+ """Actor classes, assigned when the series are built, never stored (design §7.1).
4
+
5
+ Changing a bot list and re-rendering so corrects every chart with no
6
+ new requests.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from collections.abc import Collection, Iterable
12
+ from enum import StrEnum
13
+
14
+ from ..config import ResolvedIdentities
15
+ from ..store import Store
16
+
17
+ BOT_SUFFIX = "[bot]"
18
+ BOT_TYPE = "Bot"
19
+
20
+
21
+ class ActorClass(StrEnum):
22
+ """The four classes every counted actor falls into."""
23
+
24
+ MEMBER = "member"
25
+ EXTERNAL = "external"
26
+ ORG_BOT = "org_bot"
27
+ EXTERNAL_BOT = "external_bot"
28
+
29
+
30
+ CLASSES: tuple[ActorClass, ...] = tuple(ActorClass)
31
+ AGGREGATES: dict[str, tuple[ActorClass, ...]] = {
32
+ "humans": (ActorClass.MEMBER, ActorClass.EXTERNAL),
33
+ "bots": (ActorClass.ORG_BOT, ActorClass.EXTERNAL_BOT),
34
+ "all": CLASSES,
35
+ }
36
+
37
+
38
+ def normalise(login: str) -> str:
39
+ """``login`` lower-cased, without a trailing ``[bot]``.
40
+
41
+ REST reports ``dependabot[bot]`` where GraphQL reports ``dependabot``;
42
+ both forms name the same actor.
43
+ """
44
+ folded = login.strip().lower()
45
+ if folded.endswith(BOT_SUFFIX):
46
+ folded = folded[: -len(BOT_SUFFIX)]
47
+ return folded
48
+
49
+
50
+ def _normalised(logins: Iterable[str]) -> frozenset[str]:
51
+ """Each of ``logins``, normalised."""
52
+ return frozenset(normalise(login) for login in logins)
53
+
54
+
55
+ def classify(
56
+ login: str | None,
57
+ account_type: str | None,
58
+ identities: ResolvedIdentities,
59
+ public_members: Collection[str],
60
+ ) -> ActorClass | None:
61
+ """The class of one actor, or ``None`` when its login is ignored.
62
+
63
+ The first matching rule wins: ``ignore_logins``, ``org_bots``,
64
+ ``external_bots``, an unlisted ``Bot`` (external, and unclassified),
65
+ the explicit ``members``, ``public_members``, then external. An
66
+ actor GitHub reports without a login (a deleted account) is
67
+ external. ``public_members`` holds normalised logins, as
68
+ `public_members` returns them.
69
+ """
70
+ if login is None:
71
+ return ActorClass.EXTERNAL
72
+ key = normalise(login)
73
+ if key in _normalised(identities.ignore_logins.values):
74
+ return None
75
+ if key in _normalised(identities.org_bots.values):
76
+ return ActorClass.ORG_BOT
77
+ if key in _normalised(identities.external_bots.values):
78
+ return ActorClass.EXTERNAL_BOT
79
+ if account_type == BOT_TYPE:
80
+ return ActorClass.EXTERNAL_BOT
81
+ if key in _normalised(identities.members.values) or key in public_members:
82
+ return ActorClass.MEMBER
83
+ return ActorClass.EXTERNAL
84
+
85
+
86
+ def is_unclassified(
87
+ login: str, account_type: str | None, identities: ResolvedIdentities
88
+ ) -> bool:
89
+ """Whether `classify` places this actor by its unlisted-``Bot`` rule."""
90
+ if account_type != BOT_TYPE:
91
+ return False
92
+ listed = (
93
+ identities.ignore_logins.values
94
+ + identities.org_bots.values
95
+ + identities.external_bots.values
96
+ )
97
+ return normalise(login) not in _normalised(listed)
98
+
99
+
100
+ def public_members(
101
+ store: Store, identities: ResolvedIdentities, *, owner: str
102
+ ) -> frozenset[str]:
103
+ """The normalised public members of every organisation in ``member_orgs``.
104
+
105
+ ``owner``, the target's owner, and each name in ``member_orgs`` count
106
+ as members too: an organisation never acts on its own, and for a
107
+ target owned by a user the owner, who has no member list, is a
108
+ member whatever ``member_orgs`` holds (design §7.1). Organisation
109
+ names match whatever their case.
110
+ """
111
+ orgs = identities.member_orgs.values
112
+ stored = store.member_logins(orgs)
113
+ return _normalised((owner, *orgs)) | _normalised(stored)
114
+
115
+
116
+ def unclassified_bots(store: Store, identities: ResolvedIdentities) -> list[str]:
117
+ """The logins of stored ``Bot`` actors named in no identity list, sorted.
118
+
119
+ These are the actors `classify` places as external bots by its
120
+ fallback rule, for the end-of-run warning and ``doctor``. A login
121
+ stored in both its REST and GraphQL forms is listed once.
122
+ """
123
+ found: dict[str, str] = {}
124
+ for login, account_type in store.actors():
125
+ if is_unclassified(login, account_type, identities):
126
+ key = normalise(login)
127
+ found[key] = min(found.get(key, login), login)
128
+ return sorted(found.values())
@@ -0,0 +1,86 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ # SPDX-FileCopyrightText: 2026 The Linux Foundation
3
+ """Per-day coverage of each charted metric (design §7.3).
4
+
5
+ A day is ``complete`` when every repository in scope that day has
6
+ coverage over it, ``partial`` when some do and ``none`` when none does
7
+ or no repository is in scope. Workflow days before the owner's runs
8
+ horizon are ``none``, and a workflows day with a concluded run whose
9
+ job count is still unread is at best ``partial``.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ from collections.abc import Sequence
15
+ from datetime import date
16
+
17
+ from ..collect import ISSUES_METRIC, PULL_REQUESTS_METRIC, RUNS_METRIC, runs_horizon
18
+ from ..render.model import Coverage
19
+ from ..store import DayRange, Store
20
+
21
+ PULL_REQUESTS = "pull_requests"
22
+ ISSUES = "issues"
23
+ WORKFLOWS = "workflows"
24
+ WORKFLOW_OUTCOMES = "workflow_outcomes"
25
+
26
+ # The store's coverage metric behind each charted metric.
27
+ COVERAGE_METRIC = {
28
+ PULL_REQUESTS: PULL_REQUESTS_METRIC,
29
+ ISSUES: ISSUES_METRIC,
30
+ WORKFLOWS: RUNS_METRIC,
31
+ WORKFLOW_OUTCOMES: RUNS_METRIC,
32
+ }
33
+ _RUN_METRICS = (WORKFLOWS, WORKFLOW_OUTCOMES)
34
+
35
+
36
+ def _covers(ranges: Sequence[DayRange], day: date) -> bool:
37
+ """Whether ``day`` lies in one of ``ranges``."""
38
+ return any(r.from_day <= day <= r.to_day for r in ranges)
39
+
40
+
41
+ def _grade(covered: int, total: int) -> Coverage:
42
+ """``complete``, ``partial`` or ``none`` for ``covered`` of ``total`` repositories."""
43
+ if total == 0 or covered == 0:
44
+ return Coverage.NONE
45
+ return Coverage.COMPLETE if covered == total else Coverage.PARTIAL
46
+
47
+
48
+ def daily_coverage(
49
+ store: Store,
50
+ owner: str,
51
+ metrics: Sequence[str],
52
+ days: Sequence[date],
53
+ scope: Sequence[Sequence[str]],
54
+ ) -> dict[str, tuple[Coverage, ...]]:
55
+ """The coverage of each of ``metrics`` on each of ``days``.
56
+
57
+ ``scope`` holds, for each day, the repositories in scope that day.
58
+ """
59
+ repos = sorted({repo for day_repos in scope for repo in day_repos})
60
+ ranges = {
61
+ (repo, store_metric): store.coverage(repo, store_metric)
62
+ for repo in repos
63
+ for store_metric in {COVERAGE_METRIC[metric] for metric in metrics}
64
+ }
65
+ horizon = runs_horizon(store, owner) if days else None
66
+ missing_jobs = set(store.days_missing_jobs(days[0], days[-1])) if days else set()
67
+ result: dict[str, tuple[Coverage, ...]] = {}
68
+ for metric in metrics:
69
+ store_metric = COVERAGE_METRIC[metric]
70
+ grades: list[Coverage] = []
71
+ for day, day_repos in zip(days, scope, strict=True):
72
+ covered = sum(
73
+ _covers(ranges[repo, store_metric], day) for repo in day_repos
74
+ )
75
+ grade = _grade(covered, len(day_repos))
76
+ if metric in _RUN_METRICS and horizon is not None and day < horizon:
77
+ grade = Coverage.NONE
78
+ if (
79
+ metric == WORKFLOWS
80
+ and grade is Coverage.COMPLETE
81
+ and any((repo, day) in missing_jobs for repo in day_repos)
82
+ ):
83
+ grade = Coverage.PARTIAL
84
+ grades.append(grade)
85
+ result[metric] = tuple(grades)
86
+ return result
@@ -0,0 +1,229 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ # SPDX-FileCopyrightText: 2026 The Linux Foundation
3
+ """Daily series per metric, series and actor class (design §7.3).
4
+
5
+ Every count goes to the author of the item, or to the triggering actor
6
+ of a workflow run; a scheduled run goes to ``org_bot`` and to no login.
7
+ Pure and deterministic: the window end is passed in, and the store is
8
+ the only input besides the configuration.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ from collections.abc import Mapping
14
+ from dataclasses import dataclass
15
+ from datetime import date, timedelta
16
+ from types import MappingProxyType
17
+
18
+ from ..config import Config, ResolvedIdentities, Target, resolve_identities
19
+ from ..render.model import Coverage
20
+ from ..store import Store
21
+ from .actors import (
22
+ AGGREGATES,
23
+ CLASSES,
24
+ ActorClass,
25
+ classify,
26
+ public_members,
27
+ unclassified_bots,
28
+ )
29
+ from .coverage import (
30
+ ISSUES,
31
+ PULL_REQUESTS,
32
+ WORKFLOW_OUTCOMES,
33
+ WORKFLOWS,
34
+ daily_coverage,
35
+ )
36
+
37
+ OPENED = "opened"
38
+ CLOSED = "closed"
39
+ RUNS = "runs"
40
+ JOBS = "jobs"
41
+ SUCCEEDED = "succeeded"
42
+ FAILED = "failed"
43
+
44
+ SERIES: dict[str, tuple[str, str]] = {
45
+ PULL_REQUESTS: (OPENED, CLOSED),
46
+ ISSUES: (OPENED, CLOSED),
47
+ WORKFLOWS: (RUNS, JOBS),
48
+ WORKFLOW_OUTCOMES: (SUCCEEDED, FAILED),
49
+ }
50
+ SUCCESS_CONCLUSIONS = frozenset({"success"})
51
+ FAILURE_CONCLUSIONS = frozenset({"failure", "startup_failure", "timed_out"})
52
+ _ITEM_KINDS = {PULL_REQUESTS: "pr", ISSUES: "issue"}
53
+ _ITEM_COLUMNS = {OPENED: "created_at", CLOSED: "closed_at"}
54
+
55
+ SeriesKey = tuple[str, str, str]
56
+
57
+
58
+ @dataclass(frozen=True)
59
+ class TargetSeries:
60
+ """Everything the charts of one target draw, one value per day of ``days``.
61
+
62
+ ``counts`` maps ``(metric, series, class)`` to a vector, for each of
63
+ the four classes and the ``humans``, ``bots`` and ``all`` aggregates;
64
+ ``coverage`` maps each metric to its per-day coverage;
65
+ ``repositories`` counts the repositories in scope each day.
66
+ """
67
+
68
+ owner: str
69
+ days: tuple[date, ...]
70
+ counts: Mapping[SeriesKey, tuple[int, ...]]
71
+ coverage: Mapping[str, tuple[Coverage, ...]]
72
+ repositories: tuple[int, ...]
73
+ unclassified_bots: tuple[str, ...]
74
+
75
+ def values(self, metric: str, series: str, actor_class: str) -> tuple[int, ...]:
76
+ """The vector of one metric, series and class or aggregate."""
77
+ return self.counts[metric, series, str(actor_class)]
78
+
79
+
80
+ def window(days: int, until: date) -> tuple[date, ...]:
81
+ """The ``days`` UTC days ending on ``until``, oldest first."""
82
+ return tuple(until - timedelta(days=offset) for offset in range(days - 1, -1, -1))
83
+
84
+
85
+ class _Counter:
86
+ """Per-class vectors over a window, filled one classified count at a time."""
87
+
88
+ def __init__(
89
+ self,
90
+ days: tuple[date, ...],
91
+ identities: ResolvedIdentities,
92
+ members: frozenset[str],
93
+ ) -> None:
94
+ """Start every vector at zero; classes resolve once per ``(login, type)``."""
95
+ self._index = {day: position for position, day in enumerate(days)}
96
+ self._width = len(days)
97
+ self._identities = identities
98
+ self._members = members
99
+ self._classes: dict[tuple[str | None, str | None], ActorClass | None] = {}
100
+ self.vectors: dict[SeriesKey, list[int]] = {}
101
+
102
+ def start(self, metric: str, series: str) -> None:
103
+ """Give ``metric`` and ``series`` a zero vector for every class."""
104
+ for actor_class in CLASSES:
105
+ self.vectors[metric, series, actor_class.value] = [0] * self._width
106
+
107
+ def classify(
108
+ self, login: str | None, account_type: str | None
109
+ ) -> ActorClass | None:
110
+ """The class of one actor, computed once per distinct pair."""
111
+ pair = (login, account_type)
112
+ if pair not in self._classes:
113
+ self._classes[pair] = classify(
114
+ login, account_type, self._identities, self._members
115
+ )
116
+ return self._classes[pair]
117
+
118
+ def add(
119
+ self, metric: str, series: str, actor_class: ActorClass, day: date, count: int
120
+ ) -> None:
121
+ """Add ``count`` on ``day`` to one class's vector."""
122
+ self.vectors[metric, series, actor_class.value][self._index[day]] += count
123
+
124
+ def result(self) -> dict[SeriesKey, tuple[int, ...]]:
125
+ """Every class vector plus the aggregates, as tuples."""
126
+ counts: dict[SeriesKey, tuple[int, ...]] = {
127
+ key: tuple(vector) for key, vector in self.vectors.items()
128
+ }
129
+ pairs = {(metric, series) for metric, series, _ in self.vectors}
130
+ for metric, series in pairs:
131
+ for name, members in AGGREGATES.items():
132
+ columns = [self.vectors[metric, series, c.value] for c in members]
133
+ counts[metric, series, name] = tuple(
134
+ sum(day) for day in zip(*columns, strict=True)
135
+ )
136
+ return counts
137
+
138
+
139
+ def _enabled(config: Config) -> list[str]:
140
+ """The metrics the configuration charts, in a fixed order."""
141
+ flags = config.metrics
142
+ enabled = {
143
+ PULL_REQUESTS: flags.pull_requests,
144
+ ISSUES: flags.issues,
145
+ WORKFLOWS: flags.workflows,
146
+ WORKFLOW_OUTCOMES: flags.workflow_outcomes,
147
+ }
148
+ return [metric for metric, on in enabled.items() if on]
149
+
150
+
151
+ def _count_items(
152
+ store: Store, counter: _Counter, metric: str, days: tuple[date, ...]
153
+ ) -> None:
154
+ """Fill the opened and closed vectors of one item metric."""
155
+ for series in SERIES[metric]:
156
+ counter.start(metric, series)
157
+ rows = store.item_day_counts(
158
+ _ITEM_KINDS[metric], _ITEM_COLUMNS[series], days[0], days[-1]
159
+ )
160
+ for row in rows:
161
+ actor_class = counter.classify(row.login, row.account_type)
162
+ if actor_class is not None:
163
+ counter.add(metric, series, actor_class, row.day, row.count)
164
+
165
+
166
+ def _count_runs(
167
+ store: Store, counter: _Counter, metrics: list[str], days: tuple[date, ...]
168
+ ) -> None:
169
+ """Fill the workflow and workflow outcome vectors the configuration charts."""
170
+ wanted = [metric for metric in (WORKFLOWS, WORKFLOW_OUTCOMES) if metric in metrics]
171
+ if not wanted:
172
+ return
173
+ for metric in wanted:
174
+ for series in SERIES[metric]:
175
+ counter.start(metric, series)
176
+ for row in store.run_day_counts(days[0], days[-1]):
177
+ if row.scheduled:
178
+ actor_class: ActorClass | None = ActorClass.ORG_BOT
179
+ else:
180
+ actor_class = counter.classify(row.login, row.account_type)
181
+ if actor_class is None:
182
+ continue
183
+ if WORKFLOWS in wanted:
184
+ counter.add(WORKFLOWS, RUNS, actor_class, row.day, row.runs)
185
+ counter.add(WORKFLOWS, JOBS, actor_class, row.day, row.jobs)
186
+ if WORKFLOW_OUTCOMES in wanted:
187
+ if row.conclusion in SUCCESS_CONCLUSIONS:
188
+ counter.add(
189
+ WORKFLOW_OUTCOMES, SUCCEEDED, actor_class, row.day, row.runs
190
+ )
191
+ elif row.conclusion in FAILURE_CONCLUSIONS:
192
+ counter.add(WORKFLOW_OUTCOMES, FAILED, actor_class, row.day, row.runs)
193
+
194
+
195
+ def build_series(
196
+ store: Store,
197
+ config: Config,
198
+ target: Target,
199
+ *,
200
+ until: date,
201
+ identities: ResolvedIdentities | None = None,
202
+ ) -> TargetSeries:
203
+ """The daily series, coverage and repository counts of ``target``.
204
+
205
+ The window is ``config.window.days`` days ending on ``until``.
206
+ ``identities`` defaults to the lists `resolve_identities` gives for
207
+ ``target``; pass them to apply command-line overrides.
208
+ """
209
+ if identities is None:
210
+ identities = resolve_identities(target, config)
211
+ days = window(config.window.days, until)
212
+ metrics = _enabled(config)
213
+ members = public_members(store, identities, owner=target.owner)
214
+ counter = _Counter(days, identities, members)
215
+ for metric in (PULL_REQUESTS, ISSUES):
216
+ if metric in metrics:
217
+ _count_items(store, counter, metric, days)
218
+ _count_runs(store, counter, metrics, days)
219
+ scope = [store.in_scope(day) for day in days]
220
+ return TargetSeries(
221
+ owner=target.owner,
222
+ days=days,
223
+ counts=MappingProxyType(counter.result()),
224
+ coverage=MappingProxyType(
225
+ daily_coverage(store, target.owner, metrics, days, scope)
226
+ ),
227
+ repositories=tuple(len(repos) for repos in scope),
228
+ unclassified_bots=tuple(unclassified_bots(store, identities)),
229
+ )
@@ -0,0 +1,221 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ # SPDX-FileCopyrightText: 2026 The Linux Foundation
3
+ """The contributor leaderboard, credited to authors (design §7.4).
4
+
5
+ One row per actor over the window, bots included. Pull requests and
6
+ issues count for whoever authored them, so ``prs_merged`` is the
7
+ author's; the reviewer columns count the reviews each actor submitted.
8
+ The two forms of a bot login, ``name`` and ``name[bot]``, share a row.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ from collections.abc import Iterable, Mapping
14
+ from dataclasses import dataclass
15
+ from datetime import date
16
+ from types import MappingProxyType
17
+
18
+ from ..config import Config, ResolvedIdentities, Target, resolve_identities
19
+ from ..store import Store
20
+ from .actors import BOT_SUFFIX, ActorClass, classify, normalise, public_members
21
+ from .daily import window
22
+
23
+ AUTHORED = (
24
+ "prs_opened",
25
+ "prs_merged",
26
+ "prs_closed_unmerged",
27
+ "issues_opened",
28
+ "issues_closed",
29
+ )
30
+ PRS_REVIEWED = "prs_reviewed"
31
+ REVIEWED = ("reviews", PRS_REVIEWED, "approvals", "changes_requested")
32
+ # The review columns `AggregateStore.review_actor_counts` returns, in order.
33
+ _REVIEW_COUNTS = ("reviews", "approvals", "changes_requested")
34
+ BOT_TYPE = "Bot"
35
+ RUNS_TRIGGERED = "runs_triggered"
36
+ TOTAL = "total"
37
+ # The columns ``total`` sums: every default count but ``total`` itself.
38
+ SUMMED = (*AUTHORED, *REVIEWED, RUNS_TRIGGERED)
39
+ COLUMNS = (*SUMMED, TOTAL)
40
+ # The optional columns, by the ``contributors.columns`` name that enables each.
41
+ OPTIONAL = {"merged_by": "merged_as_merger", "closed_by": "closed_as_closer"}
42
+ # When the two forms of a login classify apart, the first class listed wins.
43
+ _PRECEDENCE = (
44
+ ActorClass.ORG_BOT,
45
+ ActorClass.EXTERNAL_BOT,
46
+ ActorClass.MEMBER,
47
+ ActorClass.EXTERNAL,
48
+ )
49
+
50
+ # The authored columns: item kind, timestamp column and whether only unmerged count.
51
+ _AUTHORED_QUERIES = {
52
+ "prs_opened": ("pr", "created_at", False),
53
+ "prs_merged": ("pr", "merged_at", False),
54
+ "prs_closed_unmerged": ("pr", "closed_at", True),
55
+ "issues_opened": ("issue", "created_at", False),
56
+ "issues_closed": ("issue", "closed_at", False),
57
+ }
58
+ _OPTIONAL_QUERIES = {
59
+ "merged_as_merger": ("pr", "merged_at", "merged_by"),
60
+ "closed_as_closer": (None, "closed_at", "closed_by"),
61
+ }
62
+
63
+
64
+ @dataclass(frozen=True)
65
+ class Contributor:
66
+ """One leaderboard row: the display login, its public class and its counts."""
67
+
68
+ login: str
69
+ actor_class: ActorClass
70
+ counts: Mapping[str, int]
71
+
72
+ def record(self) -> dict[str, str | int]:
73
+ """The row as one flat record: ``login``, ``class`` and each count."""
74
+ return {"login": self.login, "class": self.actor_class.value, **self.counts}
75
+
76
+
77
+ def display_login(
78
+ forms: Iterable[str], identities: ResolvedIdentities, *, bot: bool = False
79
+ ) -> str:
80
+ """The display form of one actor seen under ``forms``.
81
+
82
+ REST gives a bot's login with its ``[bot]`` suffix where GraphQL
83
+ drops it, so a suffixed form wins, whether stored or named in a bot
84
+ list; otherwise the first stored form in sort order, given the
85
+ suffix when ``bot`` says GitHub typed the account ``Bot``.
86
+ """
87
+ stored = sorted(set(forms))
88
+ key = normalise(stored[0])
89
+ listed = [
90
+ login
91
+ for login in (*identities.org_bots.values, *identities.external_bots.values)
92
+ if normalise(login) == key
93
+ ]
94
+ suffixed = [f for f in (*stored, *listed) if f.lower().endswith(BOT_SUFFIX)]
95
+ if suffixed:
96
+ return suffixed[0]
97
+ return f"{stored[0]}{BOT_SUFFIX}" if bot else stored[0]
98
+
99
+
100
+ class _Board:
101
+ """Counts per normalised login, with every form, class and type seen for each."""
102
+
103
+ def __init__(self, identities: ResolvedIdentities, members: frozenset[str]) -> None:
104
+ """Start empty; classes resolve once per ``(login, type)``."""
105
+ self._identities = identities
106
+ self._members = members
107
+ self._classes: dict[tuple[str, str | None], ActorClass | None] = {}
108
+ self.forms: dict[str, set[str]] = {}
109
+ self.seen: dict[str, set[ActorClass]] = {}
110
+ self.bots: set[str] = set()
111
+ self.counts: dict[str, dict[str, int]] = {}
112
+ self.distinct: dict[str, dict[str, set[object]]] = {}
113
+
114
+ def _key(self, login: str | None, account_type: str | None) -> str | None:
115
+ """The row key of one actor, recording its form; ``None`` when left out."""
116
+ if login is None:
117
+ return None
118
+ pair = (login, account_type)
119
+ if pair not in self._classes:
120
+ self._classes[pair] = classify(
121
+ login, account_type, self._identities, self._members
122
+ )
123
+ actor_class = self._classes[pair]
124
+ if actor_class is None:
125
+ return None
126
+ key = normalise(login)
127
+ self.forms.setdefault(key, set()).add(login)
128
+ self.seen.setdefault(key, set()).add(actor_class)
129
+ if account_type == BOT_TYPE:
130
+ self.bots.add(key)
131
+ self.counts.setdefault(key, {})
132
+ return key
133
+
134
+ def add(
135
+ self, login: str | None, account_type: str | None, column: str, count: int
136
+ ) -> None:
137
+ """Credit ``count`` in ``column`` to one actor, unless ignored or unnamed."""
138
+ if not count:
139
+ return
140
+ key = self._key(login, account_type)
141
+ if key is not None:
142
+ row = self.counts[key]
143
+ row[column] = row.get(column, 0) + count
144
+
145
+ def add_distinct(
146
+ self, login: str | None, account_type: str | None, column: str, item: object
147
+ ) -> None:
148
+ """Credit ``item`` in ``column`` to one actor, once whatever its form."""
149
+ key = self._key(login, account_type)
150
+ if key is not None:
151
+ self.distinct.setdefault(key, {}).setdefault(column, set()).add(item)
152
+
153
+ def rows(self, columns: tuple[str, ...]) -> list[Contributor]:
154
+ """Every row, each count column filled and ``total`` summed."""
155
+ rows = []
156
+ for key, row in self.counts.items():
157
+ counted = dict(row)
158
+ for column, items in self.distinct.get(key, {}).items():
159
+ counted[column] = len(items)
160
+ values = {column: counted.get(column, 0) for column in columns}
161
+ values[TOTAL] = sum(counted.get(column, 0) for column in SUMMED)
162
+ actor_class = next(c for c in _PRECEDENCE if c in self.seen[key])
163
+ login = display_login(
164
+ self.forms[key], self._identities, bot=key in self.bots
165
+ )
166
+ rows.append(Contributor(login, actor_class, MappingProxyType(values)))
167
+ return rows
168
+
169
+
170
+ def leaderboard_columns(config: Config) -> tuple[str, ...]:
171
+ """The count columns of the table: the defaults, then any optional ones enabled."""
172
+ extra = tuple(
173
+ OPTIONAL[name] for name in OPTIONAL if name in config.contributors.columns
174
+ )
175
+ return (*COLUMNS, *extra)
176
+
177
+
178
+ def build_leaderboard(
179
+ store: Store,
180
+ config: Config,
181
+ target: Target,
182
+ *,
183
+ until: date,
184
+ identities: ResolvedIdentities | None = None,
185
+ ) -> list[Contributor]:
186
+ """The contributor rows of ``target`` over the window ending on ``until``.
187
+
188
+ Sorted by ``total`` descending, then login; ``contributors.top_n``
189
+ caps the rows, ``0`` keeping them all. Ignored logins, scheduled
190
+ runs and events from repositories out of scope that day are left out.
191
+ """
192
+ if identities is None:
193
+ identities = resolve_identities(target, config)
194
+ days = window(config.window.days, until)
195
+ first, last = days[0], days[-1]
196
+ board = _Board(identities, public_members(store, identities, owner=target.owner))
197
+ for column, (kind, field, unmerged) in _AUTHORED_QUERIES.items():
198
+ for login, account_type, count in store.item_actor_counts(
199
+ kind, field, first, last, unmerged=unmerged
200
+ ):
201
+ board.add(login, account_type, column, count)
202
+ for login, account_type, *counts in store.review_actor_counts(first, last):
203
+ for column, count in zip(_REVIEW_COUNTS, counts, strict=True):
204
+ board.add(login, account_type, column, count)
205
+ for login, account_type, repo, number in store.reviewed_pull_requests(first, last):
206
+ board.add_distinct(login, account_type, PRS_REVIEWED, (repo, number))
207
+ for login, account_type, count in store.run_actor_counts(first, last):
208
+ board.add(login, account_type, RUNS_TRIGGERED, count)
209
+ columns = leaderboard_columns(config)
210
+ for column, (optional_kind, field, actor) in _OPTIONAL_QUERIES.items():
211
+ if column in columns:
212
+ for login, account_type, count in store.item_actor_counts(
213
+ optional_kind, field, first, last, actor=actor
214
+ ):
215
+ board.add(login, account_type, column, count)
216
+ rows = sorted(
217
+ board.rows(columns),
218
+ key=lambda row: (-row.counts[TOTAL], row.login.lower(), row.login),
219
+ )
220
+ top_n = config.contributors.top_n
221
+ return rows[:top_n] if top_n else rows