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.
- github_statistics/__init__.py +14 -0
- github_statistics/__main__.py +10 -0
- github_statistics/_version.py +24 -0
- github_statistics/cli/__init__.py +9 -0
- github_statistics/cli/app.py +104 -0
- github_statistics/cli/cache.py +159 -0
- github_statistics/cli/collect.py +219 -0
- github_statistics/cli/common.py +128 -0
- github_statistics/cli/config.py +80 -0
- github_statistics/cli/doctor.py +214 -0
- github_statistics/cli/export.py +111 -0
- github_statistics/cli/options.py +175 -0
- github_statistics/cli/render.py +126 -0
- github_statistics/cli/run.py +137 -0
- github_statistics/cli/scope.py +96 -0
- github_statistics/cli/site.py +150 -0
- github_statistics/client/__init__.py +40 -0
- github_statistics/client/accounting.py +99 -0
- github_statistics/client/budget.py +125 -0
- github_statistics/client/cooldown.py +113 -0
- github_statistics/client/errors.py +60 -0
- github_statistics/client/graphql.py +281 -0
- github_statistics/client/paging.py +92 -0
- github_statistics/client/policy.py +243 -0
- github_statistics/client/transport.py +437 -0
- github_statistics/collect/__init__.py +44 -0
- github_statistics/collect/common.py +69 -0
- github_statistics/collect/enrich_items.py +423 -0
- github_statistics/collect/items.py +238 -0
- github_statistics/collect/jobs.py +194 -0
- github_statistics/collect/listed.py +42 -0
- github_statistics/collect/members.py +70 -0
- github_statistics/collect/reader.py +124 -0
- github_statistics/collect/run.py +354 -0
- github_statistics/collect/runs.py +436 -0
- github_statistics/collect/slices.py +55 -0
- github_statistics/collect/steps.py +154 -0
- github_statistics/collect/sweep.py +70 -0
- github_statistics/config/__init__.py +37 -0
- github_statistics/config/loader.py +430 -0
- github_statistics/config/models.py +156 -0
- github_statistics/config/schema.py +245 -0
- github_statistics/export/__init__.py +11 -0
- github_statistics/export/csv.py +93 -0
- github_statistics/export/documents.py +189 -0
- github_statistics/export/json.py +33 -0
- github_statistics/py.typed +2 -0
- github_statistics/render/__init__.py +44 -0
- github_statistics/render/bars3d.py +420 -0
- github_statistics/render/charts.py +214 -0
- github_statistics/render/demo.py +133 -0
- github_statistics/render/images.py +31 -0
- github_statistics/render/layout.py +341 -0
- github_statistics/render/model.py +260 -0
- github_statistics/render/palette.py +41 -0
- github_statistics/scope/__init__.py +17 -0
- github_statistics/scope/apply.py +95 -0
- github_statistics/scope/resolver.py +228 -0
- github_statistics/series/__init__.py +22 -0
- github_statistics/series/actors.py +128 -0
- github_statistics/series/coverage.py +86 -0
- github_statistics/series/daily.py +229 -0
- github_statistics/series/leaderboard.py +221 -0
- github_statistics/series/repositories.py +154 -0
- github_statistics/site/__init__.py +9 -0
- github_statistics/site/assets/site.css +281 -0
- github_statistics/site/build.py +392 -0
- github_statistics/site/templates/base.html.j2 +25 -0
- github_statistics/site/templates/index.html.j2 +30 -0
- github_statistics/site/templates/macros.html.j2 +5 -0
- github_statistics/site/templates/site.js.j2 +66 -0
- github_statistics/site/templates/target.html.j2 +95 -0
- github_statistics/store/__init__.py +40 -0
- github_statistics/store/activity.py +311 -0
- github_statistics/store/aggregates.py +294 -0
- github_statistics/store/base.py +163 -0
- github_statistics/store/codec.py +263 -0
- github_statistics/store/models.py +136 -0
- github_statistics/store/paths.py +36 -0
- github_statistics/store/schema.py +169 -0
- github_statistics/store/sqlite.py +299 -0
- github_statistics-0.1.0.dist-info/METADATA +308 -0
- github_statistics-0.1.0.dist-info/RECORD +86 -0
- github_statistics-0.1.0.dist-info/WHEEL +4 -0
- github_statistics-0.1.0.dist-info/entry_points.txt +2 -0
- github_statistics-0.1.0.dist-info/licenses/LICENSE +201 -0
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
# SPDX-FileCopyrightText: 2026 The Linux Foundation
|
|
3
|
+
"""The ``config`` command group: show, check and path."""
|
|
4
|
+
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
import json
|
|
8
|
+
from typing import Any
|
|
9
|
+
|
|
10
|
+
import typer
|
|
11
|
+
|
|
12
|
+
from github_statistics.config import ConfigError, Resolution, default_config_path
|
|
13
|
+
from github_statistics.config.loader import dump, looks_like_token
|
|
14
|
+
|
|
15
|
+
from .options import SharedOptions, shared_options
|
|
16
|
+
|
|
17
|
+
REDACTED = "<redacted: looks like a token>"
|
|
18
|
+
|
|
19
|
+
config_app = typer.Typer(
|
|
20
|
+
name="config",
|
|
21
|
+
help="Show, check or locate the configuration.",
|
|
22
|
+
no_args_is_help=True,
|
|
23
|
+
)
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _resolve(options: SharedOptions) -> Resolution:
|
|
27
|
+
"""Resolve the configuration, or exit 1 with a one-line reason."""
|
|
28
|
+
try:
|
|
29
|
+
return options.resolve()
|
|
30
|
+
except ConfigError as exc:
|
|
31
|
+
typer.echo(f"error: {exc}", err=True)
|
|
32
|
+
raise typer.Exit(1) from None
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _redact(value: Any) -> Any:
|
|
36
|
+
"""``value`` with every token-shaped string, at any depth, redacted."""
|
|
37
|
+
if isinstance(value, str):
|
|
38
|
+
return REDACTED if looks_like_token(value) else value
|
|
39
|
+
if isinstance(value, dict):
|
|
40
|
+
return {key: _redact(item) for key, item in value.items()}
|
|
41
|
+
if isinstance(value, list):
|
|
42
|
+
return [_redact(item) for item in value]
|
|
43
|
+
return value
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _report(resolution: Resolution) -> dict[str, Any]:
|
|
47
|
+
"""The resolved configuration and identity provenance, tokens redacted."""
|
|
48
|
+
identities = []
|
|
49
|
+
for target in resolution.config.targets:
|
|
50
|
+
resolved = dump(resolution.identities_for(target))
|
|
51
|
+
identities.append({"owner": target.owner, **resolved})
|
|
52
|
+
report = {
|
|
53
|
+
"source": resolution.source,
|
|
54
|
+
"location": resolution.location,
|
|
55
|
+
"config": dump(resolution.config),
|
|
56
|
+
"identities": identities,
|
|
57
|
+
}
|
|
58
|
+
return _redact(report)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
@config_app.command()
|
|
62
|
+
@shared_options
|
|
63
|
+
def show(options: SharedOptions) -> None:
|
|
64
|
+
"""Print the resolved configuration and where each identity list came from."""
|
|
65
|
+
typer.echo(json.dumps(_report(_resolve(options)), indent=2))
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
@config_app.command()
|
|
69
|
+
@shared_options
|
|
70
|
+
def check(options: SharedOptions) -> None:
|
|
71
|
+
"""Validate the configuration; exit non-zero with a one-line reason on failure."""
|
|
72
|
+
resolution = _resolve(options)
|
|
73
|
+
where = f" ({resolution.location})" if resolution.location else ""
|
|
74
|
+
typer.echo(f"ok: configuration from {resolution.source}{where}")
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
@config_app.command()
|
|
78
|
+
def path() -> None:
|
|
79
|
+
"""Print the default configuration file path."""
|
|
80
|
+
typer.echo(str(default_config_path()))
|
|
@@ -0,0 +1,214 @@
|
|
|
1
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
# SPDX-FileCopyrightText: 2026 The Linux Foundation
|
|
3
|
+
"""The ``doctor`` command: whether a setup is sound (design §4.2).
|
|
4
|
+
|
|
5
|
+
It composes what the other commands already compute and writes
|
|
6
|
+
nothing. Only an invalid configuration (exit 4) or a rejected token
|
|
7
|
+
(exit 3) fails it; a missing store, an empty scope and unclassified
|
|
8
|
+
bots are reported.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import asyncio
|
|
14
|
+
import dataclasses
|
|
15
|
+
import sqlite3
|
|
16
|
+
from datetime import UTC, date, datetime, timedelta
|
|
17
|
+
from pathlib import Path
|
|
18
|
+
|
|
19
|
+
import httpx
|
|
20
|
+
import typer
|
|
21
|
+
|
|
22
|
+
from github_statistics.client import (
|
|
23
|
+
AuthError,
|
|
24
|
+
Budget,
|
|
25
|
+
BudgetExhaustedError,
|
|
26
|
+
ClientError,
|
|
27
|
+
Transport,
|
|
28
|
+
)
|
|
29
|
+
from github_statistics.collect import runs_horizon
|
|
30
|
+
from github_statistics.collect.run import window_coverage
|
|
31
|
+
from github_statistics.config import (
|
|
32
|
+
Config,
|
|
33
|
+
ConfigError,
|
|
34
|
+
Resolution,
|
|
35
|
+
Target,
|
|
36
|
+
default_cache_dir,
|
|
37
|
+
resolve_token,
|
|
38
|
+
)
|
|
39
|
+
from github_statistics.scope import resolve_scope
|
|
40
|
+
from github_statistics.store import store_path
|
|
41
|
+
|
|
42
|
+
from .cache import info as cache_info
|
|
43
|
+
from .collect import AUTH_EXIT
|
|
44
|
+
from .common import API_HOST, ReadOnlyStore, StaleStoreError, fail
|
|
45
|
+
from .config import _redact
|
|
46
|
+
from .options import SharedOptions, shared_options
|
|
47
|
+
|
|
48
|
+
CONFIG_EXIT = 4
|
|
49
|
+
IDENTITY_KEYS = ("org_bots", "external_bots", "members", "member_orgs", "ignore_logins")
|
|
50
|
+
BOT_KEYS = "identities.org_bots or identities.external_bots"
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def _configuration(resolution: Resolution) -> None:
|
|
54
|
+
"""The winning source and each target's identity lists with their provenance."""
|
|
55
|
+
where = f" ({resolution.location})" if resolution.location else ""
|
|
56
|
+
typer.echo(f"configuration: {resolution.source}{where}")
|
|
57
|
+
for target in resolution.config.targets:
|
|
58
|
+
identities = resolution.identities_for(target)
|
|
59
|
+
typer.echo(f"identities for {target.owner}:")
|
|
60
|
+
for key in IDENTITY_KEYS:
|
|
61
|
+
found = getattr(identities, key)
|
|
62
|
+
values = ", ".join(_redact(list(found.values))) or "none"
|
|
63
|
+
typer.echo(f" {key}: {values} ({found.source})")
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
async def _network(target: Target, config: Config, known: list[str]) -> None:
|
|
67
|
+
"""Print the rate limit left and the resolved scope; `AuthError` propagates.
|
|
68
|
+
|
|
69
|
+
The scope reads spend ``config``'s budget, seeded from the rate
|
|
70
|
+
limit, so they keep the configured reserve, and are skipped when
|
|
71
|
+
no count was observed; ``known`` are the repositories the store
|
|
72
|
+
holds, so one turned private is reported.
|
|
73
|
+
"""
|
|
74
|
+
limits = config.budget
|
|
75
|
+
budget = Budget(
|
|
76
|
+
rest=limits.rest, graphql_points=limits.graphql_points, reserve=limits.reserve
|
|
77
|
+
)
|
|
78
|
+
async with Transport(resolve_token(target), budget=budget) as transport:
|
|
79
|
+
try:
|
|
80
|
+
response = await transport.request("GET", "/rate_limit", charge=False)
|
|
81
|
+
response.raise_for_status()
|
|
82
|
+
core = response.json()["resources"]["core"]
|
|
83
|
+
remaining = int(core["remaining"])
|
|
84
|
+
budget.observe(remaining, core.get("reset"))
|
|
85
|
+
left = f"{remaining} of {core['limit']} left"
|
|
86
|
+
except AuthError:
|
|
87
|
+
raise
|
|
88
|
+
except (ClientError, httpx.HTTPError, KeyError, TypeError, ValueError) as exc:
|
|
89
|
+
left = f"unknown ({exc})"
|
|
90
|
+
typer.echo(f" rate limit: {left}")
|
|
91
|
+
if budget.remaining is None:
|
|
92
|
+
# Without a count the budget cannot hold the reserve back.
|
|
93
|
+
typer.echo(f"scope of {target.owner}: skipped (no rate limit count)")
|
|
94
|
+
return
|
|
95
|
+
try:
|
|
96
|
+
scope = await resolve_scope(transport, target, known=known)
|
|
97
|
+
except AuthError:
|
|
98
|
+
raise
|
|
99
|
+
except BudgetExhaustedError as exc:
|
|
100
|
+
typer.echo(f"scope of {target.owner}: budget spent ({exc})")
|
|
101
|
+
return
|
|
102
|
+
except (ClientError, httpx.HTTPError) as exc:
|
|
103
|
+
typer.echo(f"scope of {target.owner}: cannot resolve ({exc})")
|
|
104
|
+
return
|
|
105
|
+
typer.echo(f"scope of {scope.owner}: {len(scope.repositories)} repositories")
|
|
106
|
+
for repository in scope.repositories:
|
|
107
|
+
typer.echo(f" selected {scope.owner}/{repository.name}")
|
|
108
|
+
for drop in scope.dropped:
|
|
109
|
+
typer.echo(f" dropped {scope.owner}/{drop.name}: {drop.reason}")
|
|
110
|
+
for name in scope.unresolved:
|
|
111
|
+
typer.echo(f" could not read {scope.owner}/{name}")
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def _stored(path: Path) -> list[str]:
|
|
115
|
+
"""The repositories the store at ``path`` holds; none when it cannot be read."""
|
|
116
|
+
if not path.is_file():
|
|
117
|
+
return []
|
|
118
|
+
try:
|
|
119
|
+
with ReadOnlyStore(path) as store:
|
|
120
|
+
return store.stored_repositories()
|
|
121
|
+
except (StaleStoreError, sqlite3.DatabaseError):
|
|
122
|
+
return []
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def _open(path: Path, owner: str) -> ReadOnlyStore | None:
|
|
126
|
+
"""``owner``'s store read-only, or ``None`` after saying why it cannot be read."""
|
|
127
|
+
reason = f"no store for {owner} at {path}; run collect first"
|
|
128
|
+
if path.is_file():
|
|
129
|
+
try:
|
|
130
|
+
return ReadOnlyStore(path)
|
|
131
|
+
except StaleStoreError:
|
|
132
|
+
reason = f"the store for {owner} at {path} is stale; run collect"
|
|
133
|
+
except sqlite3.DatabaseError as exc:
|
|
134
|
+
reason = f"cannot read the store for {owner} at {path}: {exc}"
|
|
135
|
+
typer.echo(reason)
|
|
136
|
+
return None
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def _health(
|
|
140
|
+
resolution: Resolution, target: Target, store: ReadOnlyStore, until: date
|
|
141
|
+
) -> None:
|
|
142
|
+
"""Coverage over the window, public members and unclassified bots."""
|
|
143
|
+
# Imported here so other commands start without loading matplotlib.
|
|
144
|
+
from github_statistics.series import unclassified_bots
|
|
145
|
+
|
|
146
|
+
config = resolution.config
|
|
147
|
+
start = until - timedelta(days=config.window.days - 1)
|
|
148
|
+
metrics = config.metrics
|
|
149
|
+
enabled = [f.name for f in dataclasses.fields(metrics) if getattr(metrics, f.name)]
|
|
150
|
+
coverage, _gaps = window_coverage(store, target.owner, enabled, start, until)
|
|
151
|
+
typer.echo(f"coverage of {target.owner}, {start} to {until}:")
|
|
152
|
+
for metric, days in coverage.items():
|
|
153
|
+
typer.echo(
|
|
154
|
+
f" {metric}: {days.complete} complete, {days.partial} partial,"
|
|
155
|
+
f" {days.missing} missing"
|
|
156
|
+
)
|
|
157
|
+
horizon = runs_horizon(store, target.owner)
|
|
158
|
+
typer.echo(f" workflow runs horizon: {horizon or 'no runs held'}")
|
|
159
|
+
identities = resolution.identities_for(target)
|
|
160
|
+
typer.echo(f"public members of {target.owner}'s member organisations:")
|
|
161
|
+
for org in identities.member_orgs.values:
|
|
162
|
+
typer.echo(f" {_redact(org)}: {len(store.member_logins([org]))}")
|
|
163
|
+
bots = unclassified_bots(store, identities)
|
|
164
|
+
typer.echo(f"unclassified bots of {target.owner}: {len(bots)}")
|
|
165
|
+
for login in bots:
|
|
166
|
+
typer.echo(f" {login}: add to {BOT_KEYS}")
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
@shared_options
|
|
170
|
+
def doctor(
|
|
171
|
+
options: SharedOptions,
|
|
172
|
+
offline: bool = typer.Option(
|
|
173
|
+
False, "--offline", help="Skip the rate limit and scope checks."
|
|
174
|
+
),
|
|
175
|
+
) -> None:
|
|
176
|
+
"""Report the configuration, token, scope, store, coverage and bots; no writes."""
|
|
177
|
+
try:
|
|
178
|
+
resolution = options.resolve()
|
|
179
|
+
except ConfigError as exc:
|
|
180
|
+
raise fail(str(exc), CONFIG_EXIT) from None
|
|
181
|
+
config = resolution.config
|
|
182
|
+
_configuration(resolution)
|
|
183
|
+
cache = Path(config.cache.directory or default_cache_dir())
|
|
184
|
+
for target in config.targets:
|
|
185
|
+
# Shown redacted; the original still names the variable to read.
|
|
186
|
+
variable = _redact(target.token_env)
|
|
187
|
+
state = "is set" if resolve_token(target) else "is not set"
|
|
188
|
+
typer.echo(f"token for {target.owner}: ${variable} {state}")
|
|
189
|
+
if offline:
|
|
190
|
+
typer.echo(" rate limit: skipped (--offline)")
|
|
191
|
+
typer.echo(f"scope of {target.owner}: skipped (--offline)")
|
|
192
|
+
continue
|
|
193
|
+
try:
|
|
194
|
+
known = _stored(store_path(cache, API_HOST, target.owner))
|
|
195
|
+
asyncio.run(_network(target, config, known))
|
|
196
|
+
except AuthError:
|
|
197
|
+
message = f"GitHub rejected the token in ${variable} (HTTP 401)"
|
|
198
|
+
raise fail(message, AUTH_EXIT) from None
|
|
199
|
+
try:
|
|
200
|
+
cache_info(cache_dir=str(cache), config=None, config_data=None)
|
|
201
|
+
except sqlite3.DatabaseError as exc:
|
|
202
|
+
# One unreadable store must not hide the per-target report below.
|
|
203
|
+
typer.echo(f"cannot inspect the stores under {cache}: {exc}")
|
|
204
|
+
until = options.until or datetime.now(UTC).date() - timedelta(days=1)
|
|
205
|
+
for target in config.targets:
|
|
206
|
+
path = store_path(cache, API_HOST, target.owner)
|
|
207
|
+
store = _open(path, target.owner)
|
|
208
|
+
if store is None:
|
|
209
|
+
continue
|
|
210
|
+
try:
|
|
211
|
+
with store:
|
|
212
|
+
_health(resolution, target, store, until)
|
|
213
|
+
except sqlite3.DatabaseError as exc:
|
|
214
|
+
typer.echo(f"cannot read the store for {target.owner} at {path}: {exc}")
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
# SPDX-FileCopyrightText: 2026 The Linux Foundation
|
|
3
|
+
"""The ``export`` command: the dataset as JSON or CSV (design §4.2, §8.6).
|
|
4
|
+
|
|
5
|
+
It reads each target's store and nothing else: it needs no token,
|
|
6
|
+
makes no request, and never creates or rebuilds a store. Files go to
|
|
7
|
+
``<output>/<owner>/data/``.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import sqlite3
|
|
13
|
+
from collections.abc import Sequence
|
|
14
|
+
from datetime import UTC, date, datetime, timedelta
|
|
15
|
+
from enum import StrEnum
|
|
16
|
+
from pathlib import Path
|
|
17
|
+
|
|
18
|
+
import typer
|
|
19
|
+
|
|
20
|
+
from github_statistics import __version__
|
|
21
|
+
from github_statistics.config import ConfigError, Resolution, Target, default_cache_dir
|
|
22
|
+
from github_statistics.store import path_component, store_path
|
|
23
|
+
|
|
24
|
+
from .common import API_HOST, ReadOnlyStore, StaleStoreError, fail
|
|
25
|
+
from .options import SharedOptions, shared_options
|
|
26
|
+
|
|
27
|
+
DATA_DIR = "data"
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class Format(StrEnum):
|
|
31
|
+
"""Which files ``export`` writes."""
|
|
32
|
+
|
|
33
|
+
JSON = "json"
|
|
34
|
+
CSV = "csv"
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def export_targets(
|
|
38
|
+
resolution: Resolution,
|
|
39
|
+
targets: Sequence[Target],
|
|
40
|
+
*,
|
|
41
|
+
until: date,
|
|
42
|
+
generated: date,
|
|
43
|
+
output_format: Format = Format.JSON,
|
|
44
|
+
) -> list[Path]:
|
|
45
|
+
"""Write each of ``targets``' documents under ``<output>/<owner>/data/``.
|
|
46
|
+
|
|
47
|
+
``until`` ends the window and ``generated`` dates the documents. The
|
|
48
|
+
files written come back in order; a missing, stale or unreadable
|
|
49
|
+
store raises the exit `fail` builds.
|
|
50
|
+
"""
|
|
51
|
+
# Imported here so other commands start without loading matplotlib.
|
|
52
|
+
from github_statistics.export import build_documents, write_csv, write_json
|
|
53
|
+
|
|
54
|
+
config = resolution.config
|
|
55
|
+
cache = (
|
|
56
|
+
Path(config.cache.directory) if config.cache.directory else default_cache_dir()
|
|
57
|
+
)
|
|
58
|
+
write = write_csv if output_format is Format.CSV else write_json
|
|
59
|
+
written: list[Path] = []
|
|
60
|
+
for target in targets:
|
|
61
|
+
path = store_path(cache, API_HOST, target.owner)
|
|
62
|
+
if not path.is_file():
|
|
63
|
+
raise fail(f"no store for {target.owner} at {path}; run collect first")
|
|
64
|
+
try:
|
|
65
|
+
store = ReadOnlyStore(path)
|
|
66
|
+
except sqlite3.DatabaseError as exc:
|
|
67
|
+
raise fail(f"cannot read the store at {path}: {exc}") from None
|
|
68
|
+
except StaleStoreError:
|
|
69
|
+
raise fail(f"the store at {path} is stale; run collect first") from None
|
|
70
|
+
with store:
|
|
71
|
+
documents = build_documents(
|
|
72
|
+
store,
|
|
73
|
+
config,
|
|
74
|
+
target,
|
|
75
|
+
until=until,
|
|
76
|
+
generated=generated,
|
|
77
|
+
version=__version__,
|
|
78
|
+
identities=resolution.identities_for(target),
|
|
79
|
+
)
|
|
80
|
+
directory = (
|
|
81
|
+
Path(config.output.directory)
|
|
82
|
+
/ path_component(target.owner, "owner")
|
|
83
|
+
/ DATA_DIR
|
|
84
|
+
)
|
|
85
|
+
written += write(documents, directory)
|
|
86
|
+
return written
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
@shared_options
|
|
90
|
+
def export(
|
|
91
|
+
options: SharedOptions,
|
|
92
|
+
output_format: Format = typer.Option(
|
|
93
|
+
Format.JSON, "--format", help="Write JSON documents or CSV tables."
|
|
94
|
+
),
|
|
95
|
+
) -> None:
|
|
96
|
+
"""Write each target's series, tables and coverage from the store; no network."""
|
|
97
|
+
try:
|
|
98
|
+
resolution = options.resolve()
|
|
99
|
+
except ConfigError as exc:
|
|
100
|
+
raise fail(str(exc)) from None
|
|
101
|
+
now = datetime.now(UTC).date()
|
|
102
|
+
until = options.until or now - timedelta(days=1)
|
|
103
|
+
for target in resolution.config.targets:
|
|
104
|
+
for written in export_targets(
|
|
105
|
+
resolution,
|
|
106
|
+
[target],
|
|
107
|
+
until=until,
|
|
108
|
+
generated=now,
|
|
109
|
+
output_format=output_format,
|
|
110
|
+
):
|
|
111
|
+
typer.echo(str(written))
|
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
# SPDX-FileCopyrightText: 2026 The Linux Foundation
|
|
3
|
+
"""Options every command that reads the configuration shares (design §4.2).
|
|
4
|
+
|
|
5
|
+
Decorate a command with `shared_options` and give it an ``options``
|
|
6
|
+
parameter: the decorator adds the shared flags to the command's
|
|
7
|
+
signature and passes them in as one `SharedOptions`.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import inspect
|
|
13
|
+
from collections.abc import Callable
|
|
14
|
+
from dataclasses import dataclass, field
|
|
15
|
+
from datetime import date, datetime
|
|
16
|
+
from typing import Any, TypeVar
|
|
17
|
+
|
|
18
|
+
import typer
|
|
19
|
+
|
|
20
|
+
from github_statistics.config import Identities, Overrides, Resolution, resolve
|
|
21
|
+
from github_statistics.config.loader import split_list
|
|
22
|
+
|
|
23
|
+
F = TypeVar("F", bound=Callable[..., Any])
|
|
24
|
+
|
|
25
|
+
_LIST = "comma-, space- or newline-separated; repeatable"
|
|
26
|
+
_IDENTITY_HELP = f"replaces the configured list ({_LIST}; §7.2)"
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
@dataclass(frozen=True)
|
|
30
|
+
class SharedOptions:
|
|
31
|
+
"""The shared command line options, normalised.
|
|
32
|
+
|
|
33
|
+
Empty strings count as not given, since the action passes an empty
|
|
34
|
+
string for every input left unset.
|
|
35
|
+
"""
|
|
36
|
+
|
|
37
|
+
config: str | None = None
|
|
38
|
+
config_data: str | None = None
|
|
39
|
+
until: date | None = None
|
|
40
|
+
overrides: Overrides = field(default_factory=Overrides)
|
|
41
|
+
|
|
42
|
+
def resolve(self) -> Resolution:
|
|
43
|
+
"""Resolve the configuration these options select."""
|
|
44
|
+
return resolve(
|
|
45
|
+
config_data=self.config_data,
|
|
46
|
+
config_path=self.config,
|
|
47
|
+
overrides=self.overrides,
|
|
48
|
+
)
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def _identity(values: list[str] | None) -> tuple[str, ...] | None:
|
|
52
|
+
"""An identity flag's list, or ``None`` when absent or empty."""
|
|
53
|
+
return split_list(values) or None
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _build(**values: Any) -> SharedOptions:
|
|
57
|
+
"""Normalise the raw flag values and enforce the exclusivity rules."""
|
|
58
|
+
include = split_list(values["include"])
|
|
59
|
+
exclude = split_list(values["exclude"])
|
|
60
|
+
repos = split_list(values["repo"])
|
|
61
|
+
if include and exclude:
|
|
62
|
+
raise typer.BadParameter(
|
|
63
|
+
"cannot be combined with --exclude", param_hint="--include"
|
|
64
|
+
)
|
|
65
|
+
if repos and (include or exclude):
|
|
66
|
+
raise typer.BadParameter(
|
|
67
|
+
"cannot be combined with --include or --exclude", param_hint="--repo"
|
|
68
|
+
)
|
|
69
|
+
until = values["until"]
|
|
70
|
+
overrides = Overrides(
|
|
71
|
+
orgs=split_list(values["org"]),
|
|
72
|
+
repos=repos,
|
|
73
|
+
include=include,
|
|
74
|
+
exclude=exclude,
|
|
75
|
+
days=values["days"],
|
|
76
|
+
output_dir=values["output_dir"] or None,
|
|
77
|
+
cache_dir=values["cache_dir"] or None,
|
|
78
|
+
budget=values["budget"],
|
|
79
|
+
token_env=values["token_env"] or None,
|
|
80
|
+
identities=Identities(
|
|
81
|
+
org_bots=_identity(values["org_bots"]),
|
|
82
|
+
external_bots=_identity(values["external_bots"]),
|
|
83
|
+
members=_identity(values["members"]),
|
|
84
|
+
member_orgs=_identity(values["member_orgs"]),
|
|
85
|
+
ignore_logins=_identity(values["ignore_logins"]),
|
|
86
|
+
),
|
|
87
|
+
)
|
|
88
|
+
return SharedOptions(
|
|
89
|
+
config=values["config"] or None,
|
|
90
|
+
config_data=values["config_data"] or None,
|
|
91
|
+
until=until.date() if until is not None else None,
|
|
92
|
+
overrides=overrides,
|
|
93
|
+
)
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def _option(
|
|
97
|
+
name: str, annotation: Any, metavar: str, text: str, **extra: Any
|
|
98
|
+
) -> inspect.Parameter:
|
|
99
|
+
"""A keyword-only parameter carrying the Typer option ``--name``."""
|
|
100
|
+
flag = "--" + name.replace("_", "-")
|
|
101
|
+
info = typer.Option(None, flag, metavar=metavar, help=text, **extra)
|
|
102
|
+
return inspect.Parameter(
|
|
103
|
+
name, inspect.Parameter.KEYWORD_ONLY, default=info, annotation=annotation
|
|
104
|
+
)
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def _parameters() -> list[inspect.Parameter]:
|
|
108
|
+
"""The shared options as parameters Typer reads from a signature."""
|
|
109
|
+
text, lists, number = str | None, list[str] | None, int | None
|
|
110
|
+
return [
|
|
111
|
+
_option("config", text, "PATH", "Configuration file."),
|
|
112
|
+
_option(
|
|
113
|
+
"config_data", text, "JSON", "Configuration as JSON or base64 of JSON."
|
|
114
|
+
),
|
|
115
|
+
_option("org", lists, "OWNER", f"Owner to report on ({_LIST})."),
|
|
116
|
+
_option("repo", lists, "OWNER/NAME", f"Repository to report on ({_LIST})."),
|
|
117
|
+
_option(
|
|
118
|
+
"include", lists, "NAMES", f"Repository names or globs to keep ({_LIST})."
|
|
119
|
+
),
|
|
120
|
+
_option(
|
|
121
|
+
"exclude", lists, "NAMES", f"Repository names or globs to drop ({_LIST})."
|
|
122
|
+
),
|
|
123
|
+
_option("days", number, "N", "Window length in days."),
|
|
124
|
+
_option(
|
|
125
|
+
"until",
|
|
126
|
+
datetime | None,
|
|
127
|
+
"YYYY-MM-DD",
|
|
128
|
+
"Last day of the window (default: yesterday, UTC).",
|
|
129
|
+
formats=["%Y-%m-%d"],
|
|
130
|
+
),
|
|
131
|
+
_option("output_dir", text, "DIR", "Site root."),
|
|
132
|
+
_option("cache_dir", text, "DIR", "Store root."),
|
|
133
|
+
_option("budget", number, "N", "REST requests this run may spend."),
|
|
134
|
+
_option("token_env", text, "NAME", "Environment variable holding the token."),
|
|
135
|
+
_option(
|
|
136
|
+
"org_bots", lists, "LOGINS", f"The organisation's bots; {_IDENTITY_HELP}."
|
|
137
|
+
),
|
|
138
|
+
_option("external_bots", lists, "LOGINS", f"Outside bots; {_IDENTITY_HELP}."),
|
|
139
|
+
_option(
|
|
140
|
+
"members", lists, "LOGINS", f"Humans counted as members; {_IDENTITY_HELP}."
|
|
141
|
+
),
|
|
142
|
+
_option(
|
|
143
|
+
"member_orgs",
|
|
144
|
+
lists,
|
|
145
|
+
"OWNERS",
|
|
146
|
+
f"Organisations whose public members count; {_IDENTITY_HELP}.",
|
|
147
|
+
),
|
|
148
|
+
_option(
|
|
149
|
+
"ignore_logins", lists, "LOGINS", f"Accounts left out; {_IDENTITY_HELP}."
|
|
150
|
+
),
|
|
151
|
+
]
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def shared_options(command: F) -> F:
|
|
155
|
+
"""Add the shared options to ``command``, passed in as ``options: SharedOptions``."""
|
|
156
|
+
extra = _parameters()
|
|
157
|
+
names = [parameter.name for parameter in extra]
|
|
158
|
+
own = [
|
|
159
|
+
parameter
|
|
160
|
+
for parameter in inspect.signature(command, eval_str=True).parameters.values()
|
|
161
|
+
if parameter.name != "options"
|
|
162
|
+
]
|
|
163
|
+
|
|
164
|
+
def wrapper(**kwargs: Any) -> Any:
|
|
165
|
+
shared = {name: kwargs.pop(name) for name in names}
|
|
166
|
+
return command(options=_build(**shared), **kwargs)
|
|
167
|
+
|
|
168
|
+
wrapper.__name__ = command.__name__
|
|
169
|
+
wrapper.__qualname__ = command.__qualname__
|
|
170
|
+
wrapper.__doc__ = command.__doc__
|
|
171
|
+
wrapper.__module__ = command.__module__
|
|
172
|
+
parameters = own + extra
|
|
173
|
+
wrapper.__signature__ = inspect.Signature(parameters) # type: ignore[attr-defined]
|
|
174
|
+
wrapper.__annotations__ = {p.name: p.annotation for p in parameters}
|
|
175
|
+
return wrapper # type: ignore[return-value]
|