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,70 @@
|
|
|
1
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
# SPDX-FileCopyrightText: 2026 The Linux Foundation
|
|
3
|
+
"""Sweep workflow runs for re-runs (design §6.4).
|
|
4
|
+
|
|
5
|
+
A re-run keeps its ``created_at`` and raises ``run_attempt``, so the
|
|
6
|
+
incremental read never sees one older than the listing's first page.
|
|
7
|
+
GitHub allows a re-run for `RERUN_DAYS` after the first run, so once a
|
|
8
|
+
week the sweep re-reads every run created since then (`_RunSync.sweep`).
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
from dataclasses import dataclass
|
|
14
|
+
from datetime import UTC, datetime
|
|
15
|
+
|
|
16
|
+
from github_statistics.client import Transport
|
|
17
|
+
from github_statistics.store import Store
|
|
18
|
+
|
|
19
|
+
from .runs import SWEEP_EVERY, _RunSync
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
@dataclass(frozen=True)
|
|
23
|
+
class SweepResult:
|
|
24
|
+
"""What one repository's re-run sweep did.
|
|
25
|
+
|
|
26
|
+
``due``: a sweep was due, so one started. ``swept``: it ended, with no
|
|
27
|
+
spent budget or unreadable repository, and moved ``swept_to``.
|
|
28
|
+
``unreadable`` and ``stalled`` are as on `RunSyncResult`.
|
|
29
|
+
"""
|
|
30
|
+
|
|
31
|
+
repo: str
|
|
32
|
+
runs: int
|
|
33
|
+
pages: int
|
|
34
|
+
due: bool
|
|
35
|
+
swept: bool
|
|
36
|
+
unreadable: int | None = None
|
|
37
|
+
stalled: bool = False
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
async def sweep_runs(
|
|
41
|
+
transport: Transport,
|
|
42
|
+
store: Store,
|
|
43
|
+
owner: str,
|
|
44
|
+
repo: str,
|
|
45
|
+
*,
|
|
46
|
+
now: datetime,
|
|
47
|
+
) -> SweepResult:
|
|
48
|
+
"""Sweep the runs of ``owner/repo`` for re-runs, if a sweep is due.
|
|
49
|
+
|
|
50
|
+
A sweep is due when ``swept_to`` is unset or more than `SWEEP_EVERY`
|
|
51
|
+
before ``now``. It reads every run created from `RERUN_DAYS` before
|
|
52
|
+
``swept_to``, or with none the last `RERUN_DAYS` and `SWEEP_EVERY`,
|
|
53
|
+
to ``now``. Run it after `sync_runs` for the repository. One cut
|
|
54
|
+
short by a spent budget or an unreadable repository leaves
|
|
55
|
+
``swept_to`` unchanged, so the next run sweeps again from the same
|
|
56
|
+
start. A first sweep has no ``swept_to`` to hold its start, so each
|
|
57
|
+
retry starts from its own ``now``: a run the cut-short attempt did
|
|
58
|
+
not reach that falls below the retry's start goes unswept. An hour
|
|
59
|
+
over the listing cap is read up to the cap and still moves
|
|
60
|
+
``swept_to``, as in the backfill: no later sweep could read more.
|
|
61
|
+
"""
|
|
62
|
+
# The sweep reads its own window; the sync window start goes unused.
|
|
63
|
+
day = now.astimezone(UTC).date()
|
|
64
|
+
sync = _RunSync(transport, store, f"{owner}/{repo}", window_start=day, now=now)
|
|
65
|
+
swept_to = sync.state.swept_to
|
|
66
|
+
due = swept_to is None or swept_to < now - SWEEP_EVERY
|
|
67
|
+
swept = due and await sync.guarded(sync.sweep)
|
|
68
|
+
return SweepResult(
|
|
69
|
+
sync.key, sync.runs, sync.pages, due, swept, sync.unreadable, sync.stalled
|
|
70
|
+
)
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
# SPDX-FileCopyrightText: 2026 The Linux Foundation
|
|
3
|
+
"""Configuration: the schema, its models, and the loader that finds and resolves it."""
|
|
4
|
+
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
from .loader import (
|
|
8
|
+
Overrides,
|
|
9
|
+
Resolution,
|
|
10
|
+
default_cache_dir,
|
|
11
|
+
default_config_path,
|
|
12
|
+
load_file,
|
|
13
|
+
loads,
|
|
14
|
+
resolve,
|
|
15
|
+
resolve_identities,
|
|
16
|
+
resolve_token,
|
|
17
|
+
)
|
|
18
|
+
from .models import Config, Identities, ResolvedIdentities, Target
|
|
19
|
+
from .schema import ConfigError, NoConfigurationError
|
|
20
|
+
|
|
21
|
+
__all__ = [
|
|
22
|
+
"Config",
|
|
23
|
+
"ConfigError",
|
|
24
|
+
"Identities",
|
|
25
|
+
"NoConfigurationError",
|
|
26
|
+
"Overrides",
|
|
27
|
+
"Resolution",
|
|
28
|
+
"ResolvedIdentities",
|
|
29
|
+
"Target",
|
|
30
|
+
"default_cache_dir",
|
|
31
|
+
"default_config_path",
|
|
32
|
+
"load_file",
|
|
33
|
+
"loads",
|
|
34
|
+
"resolve",
|
|
35
|
+
"resolve_identities",
|
|
36
|
+
"resolve_token",
|
|
37
|
+
]
|
|
@@ -0,0 +1,430 @@
|
|
|
1
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
# SPDX-FileCopyrightText: 2026 The Linux Foundation
|
|
3
|
+
"""Find, read, validate and resolve the configuration (design §7.2, Appendix A).
|
|
4
|
+
|
|
5
|
+
One loader reads every source: a file, a raw JSON value, or base64 of
|
|
6
|
+
JSON, so a plain ``vars.`` value and a base64 ``secrets.`` value both
|
|
7
|
+
work. `resolve` is the single entry point the command line uses; it
|
|
8
|
+
picks the source, applies command line overrides and reports which
|
|
9
|
+
source won. Tokens never come from the configuration, only from the
|
|
10
|
+
environment variable a target names (`resolve_token`).
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import base64
|
|
16
|
+
import binascii
|
|
17
|
+
import copy
|
|
18
|
+
import json
|
|
19
|
+
import logging
|
|
20
|
+
import os
|
|
21
|
+
import re
|
|
22
|
+
from collections.abc import Iterable, Mapping
|
|
23
|
+
from dataclasses import dataclass, field, fields, is_dataclass
|
|
24
|
+
from pathlib import Path
|
|
25
|
+
from types import MappingProxyType
|
|
26
|
+
from typing import Any
|
|
27
|
+
|
|
28
|
+
from .models import (
|
|
29
|
+
BackOnTie,
|
|
30
|
+
Budget,
|
|
31
|
+
Cache,
|
|
32
|
+
Config,
|
|
33
|
+
Contributors,
|
|
34
|
+
Identities,
|
|
35
|
+
Metrics,
|
|
36
|
+
Output,
|
|
37
|
+
Render,
|
|
38
|
+
ResolvedIdentities,
|
|
39
|
+
ResolvedList,
|
|
40
|
+
Target,
|
|
41
|
+
Window,
|
|
42
|
+
)
|
|
43
|
+
from .schema import IDENTITY_KEYS, ConfigError, NoConfigurationError, validate
|
|
44
|
+
|
|
45
|
+
logger = logging.getLogger(__name__)
|
|
46
|
+
|
|
47
|
+
APP_NAME = "github-statistics"
|
|
48
|
+
CONFIG_ENV = "GHS_CONFIG"
|
|
49
|
+
TOKEN_PREFIXES = ("ghp_", "github_pat_", "ghs_", "gho_", "ghu_", "ghr_")
|
|
50
|
+
|
|
51
|
+
_SEPARATORS = re.compile(r"[,\s]+")
|
|
52
|
+
_REPO_NAME = re.compile(r"[A-Za-z0-9._-]+")
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
@dataclass(frozen=True)
|
|
56
|
+
class Overrides:
|
|
57
|
+
"""Command line values that override the configuration.
|
|
58
|
+
|
|
59
|
+
Empty tuples and ``None`` mean "not given". `identities` holds the
|
|
60
|
+
identity flags; they outrank every configuration level (§7.2).
|
|
61
|
+
"""
|
|
62
|
+
|
|
63
|
+
orgs: tuple[str, ...] = ()
|
|
64
|
+
repos: tuple[str, ...] = ()
|
|
65
|
+
include: tuple[str, ...] = ()
|
|
66
|
+
exclude: tuple[str, ...] = ()
|
|
67
|
+
days: int | None = None
|
|
68
|
+
output_dir: str | None = None
|
|
69
|
+
cache_dir: str | None = None
|
|
70
|
+
budget: int | None = None
|
|
71
|
+
token_env: str | None = None
|
|
72
|
+
identities: Identities = field(default_factory=Identities)
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
@dataclass(frozen=True)
|
|
76
|
+
class Resolution:
|
|
77
|
+
"""The configuration in force, where it came from, and the identity flags.
|
|
78
|
+
|
|
79
|
+
``source`` is ``"config-data"``, ``"config"``, ``"env"``,
|
|
80
|
+
``"default"`` or ``"flags"``; ``location`` names the file or
|
|
81
|
+
variable it was read from, where there is one.
|
|
82
|
+
"""
|
|
83
|
+
|
|
84
|
+
config: Config
|
|
85
|
+
source: str
|
|
86
|
+
location: str | None = None
|
|
87
|
+
cli_identities: Identities = field(default_factory=Identities)
|
|
88
|
+
|
|
89
|
+
def identities_for(self, target: Target) -> ResolvedIdentities:
|
|
90
|
+
"""Resolve the identity lists for ``target``, flags included."""
|
|
91
|
+
return resolve_identities(target, self.config, self.cli_identities)
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def looks_like_token(value: str) -> bool:
|
|
95
|
+
"""Whether ``value`` has the shape of a GitHub token rather than a variable name.
|
|
96
|
+
|
|
97
|
+
Surrounding whitespace is ignored, since a pasted token often carries
|
|
98
|
+
some; ``value`` itself is left as configured.
|
|
99
|
+
"""
|
|
100
|
+
return value.strip().startswith(TOKEN_PREFIXES)
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def split_list(values: Iterable[str] | None) -> tuple[str, ...]:
|
|
104
|
+
"""Split flag or input values on commas, spaces and newlines.
|
|
105
|
+
|
|
106
|
+
A flag may repeat, so ``values`` is every occurrence; empty items
|
|
107
|
+
are dropped, so ``--org-bots ""`` yields an empty tuple.
|
|
108
|
+
"""
|
|
109
|
+
items: list[str] = []
|
|
110
|
+
for value in values or ():
|
|
111
|
+
items.extend(item for item in _SEPARATORS.split(value) if item)
|
|
112
|
+
return tuple(items)
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def _env(env: Mapping[str, str] | None) -> Mapping[str, str]:
|
|
116
|
+
"""The environment to read: ``env`` when given, else the process environment."""
|
|
117
|
+
return os.environ if env is None else env
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def _xdg_dir(env: Mapping[str, str], variable: str, fallback: str) -> Path:
|
|
121
|
+
"""An XDG base directory for this tool, falling back under the home directory."""
|
|
122
|
+
base = env.get(variable)
|
|
123
|
+
if base:
|
|
124
|
+
return Path(base) / APP_NAME
|
|
125
|
+
home = Path(env["HOME"]) if env.get("HOME") else Path.home()
|
|
126
|
+
return home / fallback / APP_NAME
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def default_config_path(env: Mapping[str, str] | None = None) -> Path:
|
|
130
|
+
"""``$XDG_CONFIG_HOME/github-statistics/config.json``, else under ``~/.config``."""
|
|
131
|
+
return _xdg_dir(_env(env), "XDG_CONFIG_HOME", ".config") / "config.json"
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def default_cache_dir(env: Mapping[str, str] | None = None) -> Path:
|
|
135
|
+
"""``$XDG_CACHE_HOME/github-statistics``, else ``~/.cache/github-statistics``."""
|
|
136
|
+
return _xdg_dir(_env(env), "XDG_CACHE_HOME", ".cache")
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def _parse(raw: str) -> dict[str, Any]:
|
|
140
|
+
"""Decode raw JSON, or base64 of JSON, into a document (not yet validated)."""
|
|
141
|
+
text = raw.strip()
|
|
142
|
+
if not text:
|
|
143
|
+
raise ConfigError("configuration is empty")
|
|
144
|
+
if not text.startswith(("{", "[")):
|
|
145
|
+
try:
|
|
146
|
+
text = base64.b64decode("".join(text.split()), validate=True).decode()
|
|
147
|
+
except (binascii.Error, ValueError):
|
|
148
|
+
raise ConfigError(
|
|
149
|
+
"configuration is neither JSON nor base64-encoded JSON"
|
|
150
|
+
) from None
|
|
151
|
+
try:
|
|
152
|
+
data = json.loads(text)
|
|
153
|
+
except json.JSONDecodeError as exc:
|
|
154
|
+
raise ConfigError(
|
|
155
|
+
f"configuration is not valid JSON: {exc.msg} "
|
|
156
|
+
f"at line {exc.lineno} column {exc.colno}"
|
|
157
|
+
) from None
|
|
158
|
+
validate(data)
|
|
159
|
+
return data
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def _logins(data: Mapping[str, Any] | None) -> Identities:
|
|
163
|
+
"""Build an `Identities`, keeping absent keys as ``None``."""
|
|
164
|
+
data = data or {}
|
|
165
|
+
return Identities(**{key: tuple(data[key]) for key in IDENTITY_KEYS if key in data})
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def _target(data: Mapping[str, Any]) -> Target:
|
|
169
|
+
"""Build a `Target` from its validated document."""
|
|
170
|
+
values = dict(data)
|
|
171
|
+
for key in ("include", "exclude"):
|
|
172
|
+
if key in values:
|
|
173
|
+
values[key] = tuple(values[key])
|
|
174
|
+
values["identities"] = _logins(data.get("identities"))
|
|
175
|
+
return Target(**values)
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
def _render(data: Mapping[str, Any]) -> Render:
|
|
179
|
+
"""Build `Render` from its validated document."""
|
|
180
|
+
values = dict(data)
|
|
181
|
+
if "derivatives" in values:
|
|
182
|
+
values["derivatives"] = tuple(values["derivatives"])
|
|
183
|
+
values["palette"] = MappingProxyType(dict(data.get("palette", {})))
|
|
184
|
+
values["back_on_tie"] = BackOnTie(**data.get("back_on_tie", {}))
|
|
185
|
+
return Render(**values)
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
def _build(data: Mapping[str, Any]) -> Config:
|
|
189
|
+
"""Build a `Config` from a validated document."""
|
|
190
|
+
contributors = dict(data.get("contributors", {}))
|
|
191
|
+
if "columns" in contributors:
|
|
192
|
+
contributors["columns"] = tuple(contributors["columns"])
|
|
193
|
+
optional: dict[str, Any] = {}
|
|
194
|
+
if "version" in data:
|
|
195
|
+
optional["version"] = data["version"]
|
|
196
|
+
if "classes" in data:
|
|
197
|
+
optional["classes"] = tuple(data["classes"])
|
|
198
|
+
return Config(
|
|
199
|
+
targets=tuple(_target(target) for target in data["targets"]),
|
|
200
|
+
identities=_logins(data.get("identities")),
|
|
201
|
+
window=Window(**data.get("window", {})),
|
|
202
|
+
metrics=Metrics(**data.get("metrics", {})),
|
|
203
|
+
render=_render(data.get("render", {})),
|
|
204
|
+
contributors=Contributors(**contributors),
|
|
205
|
+
budget=Budget(**data.get("budget", {})),
|
|
206
|
+
output=Output(**data.get("output", {})),
|
|
207
|
+
cache=Cache(**data.get("cache", {})),
|
|
208
|
+
**optional,
|
|
209
|
+
)
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
def _finish(data: Mapping[str, Any]) -> Config:
|
|
213
|
+
"""Validate a document, build the models and warn about token-shaped names."""
|
|
214
|
+
validate(data)
|
|
215
|
+
config = _build(data)
|
|
216
|
+
for index, target in enumerate(config.targets):
|
|
217
|
+
if looks_like_token(target.token_env):
|
|
218
|
+
logger.warning(
|
|
219
|
+
"targets[%d].token_env looks like a token value; it must name "
|
|
220
|
+
"the environment variable that holds the token",
|
|
221
|
+
index,
|
|
222
|
+
)
|
|
223
|
+
return config
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
def loads(raw: str) -> Config:
|
|
227
|
+
"""Load a configuration from raw JSON or base64 of JSON; raise `ConfigError`."""
|
|
228
|
+
return _finish(_parse(raw))
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
def _read(path: Path) -> str:
|
|
232
|
+
"""Read a configuration file, turning I/O failures into `ConfigError`."""
|
|
233
|
+
try:
|
|
234
|
+
return path.read_text(encoding="utf-8")
|
|
235
|
+
except (OSError, UnicodeDecodeError) as exc:
|
|
236
|
+
reason = getattr(exc, "strerror", None) or str(exc)
|
|
237
|
+
raise ConfigError(f"cannot read {path}: {reason}") from None
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
def load_file(path: Path | str) -> Config:
|
|
241
|
+
"""Load a configuration file; raise `ConfigError` naming the file on failure."""
|
|
242
|
+
path = Path(path)
|
|
243
|
+
return _finish(_labelled(_read(path), str(path)))
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
def _split_repo(value: str) -> tuple[str, str]:
|
|
247
|
+
"""Split ``OWNER/NAME``; raise `ConfigError` on any other shape.
|
|
248
|
+
|
|
249
|
+
The name becomes an ``include`` entry, which accepts globs, so it is
|
|
250
|
+
held to the characters GitHub allows in a repository name: ``--repo``
|
|
251
|
+
selects exact repositories, never a pattern.
|
|
252
|
+
"""
|
|
253
|
+
owner, _, name = value.partition("/")
|
|
254
|
+
if not owner or not _REPO_NAME.fullmatch(name):
|
|
255
|
+
raise ConfigError(f"--repo {value!r}: expected OWNER/NAME")
|
|
256
|
+
return owner, name
|
|
257
|
+
|
|
258
|
+
|
|
259
|
+
def _select_targets(
|
|
260
|
+
configured: list[dict[str, Any]], overrides: Overrides
|
|
261
|
+
) -> list[dict[str, Any]]:
|
|
262
|
+
"""The targets ``--org`` and ``--repo`` select, built on configured ones."""
|
|
263
|
+
by_owner = {target["owner"].lower(): target for target in configured}
|
|
264
|
+
selected: dict[str, dict[str, Any]] = {}
|
|
265
|
+
for org in overrides.orgs:
|
|
266
|
+
selected.setdefault(
|
|
267
|
+
org.lower(), dict(by_owner.get(org.lower(), {"owner": org}))
|
|
268
|
+
)
|
|
269
|
+
repos: dict[str, tuple[str, list[str]]] = {}
|
|
270
|
+
for value in overrides.repos:
|
|
271
|
+
owner, name = _split_repo(value)
|
|
272
|
+
if owner.lower() in selected:
|
|
273
|
+
raise ConfigError(f"--repo {value!r} overlaps --org {owner!r}")
|
|
274
|
+
repos.setdefault(owner.lower(), (owner, []))[1].append(name)
|
|
275
|
+
for key, (owner, names) in repos.items():
|
|
276
|
+
target = dict(by_owner.get(key, {"owner": owner}))
|
|
277
|
+
target["include"] = list(dict.fromkeys(names))
|
|
278
|
+
target["exclude"] = []
|
|
279
|
+
selected[key] = target
|
|
280
|
+
return list(selected.values())
|
|
281
|
+
|
|
282
|
+
|
|
283
|
+
def _check_overrides(overrides: Overrides) -> None:
|
|
284
|
+
"""Reject the override combinations the command line refuses at parse time.
|
|
285
|
+
|
|
286
|
+
Applying them would erase the conflict before validation sees it:
|
|
287
|
+
``include`` would silently drop ``exclude``, and either would widen
|
|
288
|
+
or narrow the exact repositories ``repos`` names.
|
|
289
|
+
"""
|
|
290
|
+
if overrides.include and overrides.exclude:
|
|
291
|
+
raise ConfigError("--include cannot be combined with --exclude")
|
|
292
|
+
if overrides.repos and (overrides.include or overrides.exclude):
|
|
293
|
+
raise ConfigError("--repo cannot be combined with --include or --exclude")
|
|
294
|
+
|
|
295
|
+
|
|
296
|
+
def _apply(data: Mapping[str, Any], overrides: Overrides) -> dict[str, Any]:
|
|
297
|
+
"""Return a copy of ``data`` with the command line overrides applied."""
|
|
298
|
+
result = copy.deepcopy(dict(data))
|
|
299
|
+
if overrides.orgs or overrides.repos:
|
|
300
|
+
result["targets"] = _select_targets(result.get("targets", []), overrides)
|
|
301
|
+
for target in result.get("targets", []):
|
|
302
|
+
if overrides.include:
|
|
303
|
+
target["include"], target["exclude"] = list(overrides.include), []
|
|
304
|
+
elif overrides.exclude:
|
|
305
|
+
target["include"], target["exclude"] = [], list(overrides.exclude)
|
|
306
|
+
if overrides.token_env:
|
|
307
|
+
target["token_env"] = overrides.token_env
|
|
308
|
+
sections = (
|
|
309
|
+
("window", "days", overrides.days),
|
|
310
|
+
("output", "directory", overrides.output_dir),
|
|
311
|
+
("cache", "directory", overrides.cache_dir),
|
|
312
|
+
("budget", "rest", overrides.budget),
|
|
313
|
+
)
|
|
314
|
+
for section, key, value in sections:
|
|
315
|
+
if value is not None:
|
|
316
|
+
result[section] = {**result.get(section, {}), key: value}
|
|
317
|
+
return result
|
|
318
|
+
|
|
319
|
+
|
|
320
|
+
def _source(
|
|
321
|
+
config_data: str | None,
|
|
322
|
+
config_path: Path | str | None,
|
|
323
|
+
overrides: Overrides,
|
|
324
|
+
env: Mapping[str, str],
|
|
325
|
+
) -> tuple[dict[str, Any], str, str | None]:
|
|
326
|
+
"""Pick the highest-precedence source and parse it."""
|
|
327
|
+
if config_data:
|
|
328
|
+
return _labelled(config_data, "--config-data"), "config-data", None
|
|
329
|
+
if config_path:
|
|
330
|
+
path = Path(config_path)
|
|
331
|
+
return _labelled(_read(path), str(path)), "config", str(path)
|
|
332
|
+
if env.get(CONFIG_ENV):
|
|
333
|
+
return _labelled(env[CONFIG_ENV], f"${CONFIG_ENV}"), "env", f"${CONFIG_ENV}"
|
|
334
|
+
path = default_config_path(env)
|
|
335
|
+
if path.is_file():
|
|
336
|
+
return _labelled(_read(path), str(path)), "default", str(path)
|
|
337
|
+
if overrides.orgs or overrides.repos:
|
|
338
|
+
return {"targets": []}, "flags", None
|
|
339
|
+
raise NoConfigurationError(
|
|
340
|
+
f"no configuration: pass --config or --config-data, set ${CONFIG_ENV}, "
|
|
341
|
+
f"create {path}, or name --org or --repo"
|
|
342
|
+
)
|
|
343
|
+
|
|
344
|
+
|
|
345
|
+
def _labelled(raw: str, label: str) -> dict[str, Any]:
|
|
346
|
+
"""Parse ``raw``, prefixing any error with the source it came from."""
|
|
347
|
+
try:
|
|
348
|
+
return _parse(raw)
|
|
349
|
+
except ConfigError as exc:
|
|
350
|
+
raise ConfigError(f"{label}: {exc}") from None
|
|
351
|
+
|
|
352
|
+
|
|
353
|
+
def resolve(
|
|
354
|
+
*,
|
|
355
|
+
config_data: str | None = None,
|
|
356
|
+
config_path: Path | str | None = None,
|
|
357
|
+
overrides: Overrides | None = None,
|
|
358
|
+
env: Mapping[str, str] | None = None,
|
|
359
|
+
) -> Resolution:
|
|
360
|
+
"""Find the configuration, apply the overrides and report the winning source.
|
|
361
|
+
|
|
362
|
+
Source precedence, highest first: ``config_data`` (``--config-data``);
|
|
363
|
+
``config_path`` (``--config``); ``$GHS_CONFIG``, holding JSON or
|
|
364
|
+
base64 of JSON; the default path; and with none of those,
|
|
365
|
+
``--org``/``--repo`` overrides alone build targets from defaults.
|
|
366
|
+
Overrides that combine ``include`` with ``exclude``, or ``repos``
|
|
367
|
+
with either, raise `ConfigError`; finding no source at all raises
|
|
368
|
+
its subclass `NoConfigurationError`.
|
|
369
|
+
"""
|
|
370
|
+
overrides = overrides or Overrides()
|
|
371
|
+
_check_overrides(overrides)
|
|
372
|
+
data, source, location = _source(config_data, config_path, overrides, _env(env))
|
|
373
|
+
config = _finish(_apply(data, overrides))
|
|
374
|
+
return Resolution(config, source, location, overrides.identities)
|
|
375
|
+
|
|
376
|
+
|
|
377
|
+
def resolve_identities(
|
|
378
|
+
target: Target, config: Config, cli: Identities | None = None
|
|
379
|
+
) -> ResolvedIdentities:
|
|
380
|
+
"""Resolve each identity list for ``target`` (design §7.2).
|
|
381
|
+
|
|
382
|
+
Per key, the highest level that sets it wins and replaces the lists
|
|
383
|
+
below: the command line, the target's ``identities``, the top-level
|
|
384
|
+
``identities``, then the default. Lists default to empty;
|
|
385
|
+
``member_orgs`` defaults to, and when empty means, the target owner.
|
|
386
|
+
"""
|
|
387
|
+
levels = (
|
|
388
|
+
("cli", cli or Identities()),
|
|
389
|
+
("target", target.identities),
|
|
390
|
+
("config", config.identities),
|
|
391
|
+
)
|
|
392
|
+
resolved: dict[str, ResolvedList] = {}
|
|
393
|
+
for key in IDENTITY_KEYS:
|
|
394
|
+
values: tuple[str, ...] = ()
|
|
395
|
+
source = "default"
|
|
396
|
+
for name, identities in levels:
|
|
397
|
+
value = getattr(identities, key)
|
|
398
|
+
if value is not None:
|
|
399
|
+
values, source = value, name
|
|
400
|
+
break
|
|
401
|
+
if key == "member_orgs" and not values:
|
|
402
|
+
values = (target.owner,)
|
|
403
|
+
resolved[key] = ResolvedList(tuple(values), source)
|
|
404
|
+
return ResolvedIdentities(**resolved)
|
|
405
|
+
|
|
406
|
+
|
|
407
|
+
def resolve_token(target: Target, env: Mapping[str, str] | None = None) -> str | None:
|
|
408
|
+
"""The token for ``target`` from the variable it names, or ``None`` if unset."""
|
|
409
|
+
return _env(env).get(target.token_env) or None
|
|
410
|
+
|
|
411
|
+
|
|
412
|
+
def dump(value: Any) -> Any:
|
|
413
|
+
"""Convert a configuration model to plain JSON data.
|
|
414
|
+
|
|
415
|
+
`Identities` keys a level leaves alone are omitted, so the result
|
|
416
|
+
loads back to an equal model.
|
|
417
|
+
"""
|
|
418
|
+
if isinstance(value, Identities):
|
|
419
|
+
return {
|
|
420
|
+
key: list(getattr(value, key))
|
|
421
|
+
for key in IDENTITY_KEYS
|
|
422
|
+
if getattr(value, key) is not None
|
|
423
|
+
}
|
|
424
|
+
if is_dataclass(value) and not isinstance(value, type):
|
|
425
|
+
return {item.name: dump(getattr(value, item.name)) for item in fields(value)}
|
|
426
|
+
if isinstance(value, Mapping):
|
|
427
|
+
return {key: dump(item) for key, item in value.items()}
|
|
428
|
+
if isinstance(value, tuple | list):
|
|
429
|
+
return [dump(item) for item in value]
|
|
430
|
+
return value
|
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
# SPDX-FileCopyrightText: 2026 The Linux Foundation
|
|
3
|
+
"""Frozen dataclasses mirroring the configuration schema.
|
|
4
|
+
|
|
5
|
+
Lists become tuples so a loaded configuration cannot change under the
|
|
6
|
+
code that reads it. The defaults here are the defaults of the
|
|
7
|
+
configuration document (design Appendix A).
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
from collections.abc import Mapping
|
|
13
|
+
from dataclasses import dataclass, field
|
|
14
|
+
from types import MappingProxyType
|
|
15
|
+
|
|
16
|
+
Logins = tuple[str, ...]
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
@dataclass(frozen=True)
|
|
20
|
+
class Identities:
|
|
21
|
+
"""Identity lists set at one level; ``None`` means the level leaves a key alone."""
|
|
22
|
+
|
|
23
|
+
org_bots: Logins | None = None
|
|
24
|
+
external_bots: Logins | None = None
|
|
25
|
+
members: Logins | None = None
|
|
26
|
+
member_orgs: Logins | None = None
|
|
27
|
+
ignore_logins: Logins | None = None
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
@dataclass(frozen=True)
|
|
31
|
+
class Target:
|
|
32
|
+
"""One owner and the rule that selects its repositories."""
|
|
33
|
+
|
|
34
|
+
owner: str
|
|
35
|
+
token_env: str = "GITHUB_TOKEN"
|
|
36
|
+
include: tuple[str, ...] = ()
|
|
37
|
+
exclude: tuple[str, ...] = ()
|
|
38
|
+
scan_archived: bool = False
|
|
39
|
+
scan_forks: bool = False
|
|
40
|
+
scan_templates: bool = True
|
|
41
|
+
identities: Identities = field(default_factory=Identities)
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
@dataclass(frozen=True)
|
|
45
|
+
class Window:
|
|
46
|
+
"""The length of the reporting window in days."""
|
|
47
|
+
|
|
48
|
+
days: int = 365
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
@dataclass(frozen=True)
|
|
52
|
+
class Metrics:
|
|
53
|
+
"""Which metrics a run collects and charts."""
|
|
54
|
+
|
|
55
|
+
pull_requests: bool = True
|
|
56
|
+
issues: bool = True
|
|
57
|
+
workflows: bool = True
|
|
58
|
+
workflow_outcomes: bool = False
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
@dataclass(frozen=True)
|
|
62
|
+
class BackOnTie:
|
|
63
|
+
"""Per metric, the series drawn in the back row when both values are equal."""
|
|
64
|
+
|
|
65
|
+
pull_requests: str = "closed"
|
|
66
|
+
issues: str = "closed"
|
|
67
|
+
workflows: str = "jobs"
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
@dataclass(frozen=True)
|
|
71
|
+
class Render:
|
|
72
|
+
"""Chart size, derivatives and colours."""
|
|
73
|
+
|
|
74
|
+
width: int = 3840
|
|
75
|
+
height: int = 2160
|
|
76
|
+
derivatives: tuple[int, ...] = (1920,)
|
|
77
|
+
svg: bool = False
|
|
78
|
+
palette: Mapping[str, str] = field(default_factory=lambda: MappingProxyType({}))
|
|
79
|
+
back_on_tie: BackOnTie = field(default_factory=BackOnTie)
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
@dataclass(frozen=True)
|
|
83
|
+
class Contributors:
|
|
84
|
+
"""The contributor table: how many rows and which extra columns."""
|
|
85
|
+
|
|
86
|
+
top_n: int = 100
|
|
87
|
+
columns: tuple[str, ...] = ()
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
@dataclass(frozen=True)
|
|
91
|
+
class Budget:
|
|
92
|
+
"""API spending limits for one run.
|
|
93
|
+
|
|
94
|
+
``reserve`` stays ``None`` unless configured, so the transport can
|
|
95
|
+
choose its default: 500 for a token, 10 for anonymous reads.
|
|
96
|
+
"""
|
|
97
|
+
|
|
98
|
+
rest: int = 3000
|
|
99
|
+
graphql_points: int = 1500
|
|
100
|
+
reserve: int | None = None
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
@dataclass(frozen=True)
|
|
104
|
+
class Output:
|
|
105
|
+
"""Where the site is written."""
|
|
106
|
+
|
|
107
|
+
directory: str = "site"
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
@dataclass(frozen=True)
|
|
111
|
+
class Cache:
|
|
112
|
+
"""Where the store lives; ``None`` means the XDG cache directory."""
|
|
113
|
+
|
|
114
|
+
directory: str | None = None
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
DEFAULT_CLASSES = ("all", "member", "external", "org_bot", "external_bot")
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
@dataclass(frozen=True)
|
|
121
|
+
class Config:
|
|
122
|
+
"""A whole, validated configuration document."""
|
|
123
|
+
|
|
124
|
+
targets: tuple[Target, ...]
|
|
125
|
+
version: int = 1
|
|
126
|
+
identities: Identities = field(default_factory=Identities)
|
|
127
|
+
window: Window = field(default_factory=Window)
|
|
128
|
+
metrics: Metrics = field(default_factory=Metrics)
|
|
129
|
+
classes: tuple[str, ...] = DEFAULT_CLASSES
|
|
130
|
+
render: Render = field(default_factory=Render)
|
|
131
|
+
contributors: Contributors = field(default_factory=Contributors)
|
|
132
|
+
budget: Budget = field(default_factory=Budget)
|
|
133
|
+
output: Output = field(default_factory=Output)
|
|
134
|
+
cache: Cache = field(default_factory=Cache)
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
@dataclass(frozen=True)
|
|
138
|
+
class ResolvedList:
|
|
139
|
+
"""One resolved identity list and the level it came from.
|
|
140
|
+
|
|
141
|
+
``source`` is ``"cli"``, ``"target"``, ``"config"`` or ``"default"``.
|
|
142
|
+
"""
|
|
143
|
+
|
|
144
|
+
values: Logins
|
|
145
|
+
source: str
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
@dataclass(frozen=True)
|
|
149
|
+
class ResolvedIdentities:
|
|
150
|
+
"""The identity lists in force for one target, each with its provenance."""
|
|
151
|
+
|
|
152
|
+
org_bots: ResolvedList
|
|
153
|
+
external_bots: ResolvedList
|
|
154
|
+
members: ResolvedList
|
|
155
|
+
member_orgs: ResolvedList
|
|
156
|
+
ignore_logins: ResolvedList
|