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,14 @@
|
|
|
1
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
# SPDX-FileCopyrightText: 2026 The Linux Foundation
|
|
3
|
+
"""Daily, visual activity statistics for GitHub organisations and repositories."""
|
|
4
|
+
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
try:
|
|
8
|
+
from ._version import __version__ as _vcs_version
|
|
9
|
+
except ImportError: # pragma: no cover - no _version.py without a git build
|
|
10
|
+
_vcs_version = "0.0.0"
|
|
11
|
+
|
|
12
|
+
__version__: str = _vcs_version
|
|
13
|
+
|
|
14
|
+
__all__ = ["__version__"]
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
# SPDX-FileCopyrightText: 2026 The Linux Foundation
|
|
3
|
+
"""Run the command line with ``python -m github_statistics``."""
|
|
4
|
+
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
from github_statistics.cli import app
|
|
8
|
+
|
|
9
|
+
if __name__ == "__main__":
|
|
10
|
+
app(prog_name="github-statistics")
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
# file generated by vcs-versioning
|
|
2
|
+
# don't change, don't track in version control
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
__all__ = [
|
|
6
|
+
"__version__",
|
|
7
|
+
"__version_tuple__",
|
|
8
|
+
"version",
|
|
9
|
+
"version_tuple",
|
|
10
|
+
"__commit_id__",
|
|
11
|
+
"commit_id",
|
|
12
|
+
]
|
|
13
|
+
|
|
14
|
+
version: str
|
|
15
|
+
__version__: str
|
|
16
|
+
__version_tuple__: tuple[int | str, ...]
|
|
17
|
+
version_tuple: tuple[int | str, ...]
|
|
18
|
+
commit_id: str | None
|
|
19
|
+
__commit_id__: str | None
|
|
20
|
+
|
|
21
|
+
__version__ = version = '0.1.0'
|
|
22
|
+
__version_tuple__ = version_tuple = (0, 1, 0)
|
|
23
|
+
|
|
24
|
+
__commit_id__ = commit_id = None
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
# SPDX-FileCopyrightText: 2026 The Linux Foundation
|
|
3
|
+
"""The Typer application behind the ``github-statistics`` command."""
|
|
4
|
+
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
import time
|
|
8
|
+
from datetime import UTC, date, datetime, timedelta
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
|
|
11
|
+
import typer
|
|
12
|
+
|
|
13
|
+
from github_statistics import __version__
|
|
14
|
+
|
|
15
|
+
from .cache import cache_app
|
|
16
|
+
from .collect import collect_command
|
|
17
|
+
from .config import config_app
|
|
18
|
+
from .doctor import doctor
|
|
19
|
+
from .export import export
|
|
20
|
+
from .render import render
|
|
21
|
+
from .run import run
|
|
22
|
+
from .scope import scope
|
|
23
|
+
from .site import site
|
|
24
|
+
|
|
25
|
+
DERIVATIVE_WIDTH = 1920
|
|
26
|
+
DEMO_MIN_DAYS = 7
|
|
27
|
+
DEMO_MAX_DAYS = 730
|
|
28
|
+
|
|
29
|
+
app = typer.Typer(
|
|
30
|
+
name="github-statistics",
|
|
31
|
+
help="Daily, visual activity statistics for GitHub organisations and repositories.",
|
|
32
|
+
no_args_is_help=True,
|
|
33
|
+
)
|
|
34
|
+
app.add_typer(config_app)
|
|
35
|
+
app.add_typer(cache_app)
|
|
36
|
+
app.command()(doctor)
|
|
37
|
+
app.command()(scope)
|
|
38
|
+
app.command()(export)
|
|
39
|
+
app.command(name="collect")(collect_command)
|
|
40
|
+
app.command()(render)
|
|
41
|
+
app.command()(site)
|
|
42
|
+
app.command()(run)
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _version_callback(value: bool) -> None:
|
|
46
|
+
"""Print the package version and exit when ``--version`` is given."""
|
|
47
|
+
if value:
|
|
48
|
+
typer.echo(f"github-statistics {__version__}")
|
|
49
|
+
raise typer.Exit()
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
@app.callback()
|
|
53
|
+
def main(
|
|
54
|
+
version: bool = typer.Option(
|
|
55
|
+
False,
|
|
56
|
+
"--version",
|
|
57
|
+
"-V",
|
|
58
|
+
help="Show the version and exit.",
|
|
59
|
+
callback=_version_callback,
|
|
60
|
+
is_eager=True,
|
|
61
|
+
),
|
|
62
|
+
) -> None:
|
|
63
|
+
"""Daily, visual activity statistics for GitHub organisations and repositories."""
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def _yesterday() -> date:
|
|
67
|
+
"""The last complete UTC day, the default end of a window."""
|
|
68
|
+
return datetime.now(UTC).date() - timedelta(days=1)
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
@app.command()
|
|
72
|
+
def demo(
|
|
73
|
+
output_dir: Path = typer.Option(
|
|
74
|
+
..., "--output-dir", help="Directory to write the charts to."
|
|
75
|
+
),
|
|
76
|
+
days: int = typer.Option(
|
|
77
|
+
365,
|
|
78
|
+
"--days",
|
|
79
|
+
min=DEMO_MIN_DAYS,
|
|
80
|
+
max=DEMO_MAX_DAYS,
|
|
81
|
+
help="Window length in days.",
|
|
82
|
+
),
|
|
83
|
+
seed: int = typer.Option(7, "--seed", help="Seed for the synthetic data."),
|
|
84
|
+
until: datetime | None = typer.Option(
|
|
85
|
+
None,
|
|
86
|
+
"--until",
|
|
87
|
+
formats=["%Y-%m-%d"],
|
|
88
|
+
help="Last day of the window (default: yesterday, UTC).",
|
|
89
|
+
),
|
|
90
|
+
) -> None:
|
|
91
|
+
"""Render sample charts from synthetic data; needs no token or configuration."""
|
|
92
|
+
# Imported here so other commands start without loading matplotlib.
|
|
93
|
+
from github_statistics.render import render_chart, write_derivatives
|
|
94
|
+
from github_statistics.render.demo import demo_specs
|
|
95
|
+
|
|
96
|
+
end = until.date() if until is not None else _yesterday()
|
|
97
|
+
for name, spec in demo_specs(days, seed, end):
|
|
98
|
+
started = time.perf_counter()
|
|
99
|
+
chart = render_chart(spec, output_dir / f"{name}.png")
|
|
100
|
+
derivatives = write_derivatives(chart.path, [DERIVATIVE_WIDTH])
|
|
101
|
+
elapsed = time.perf_counter() - started
|
|
102
|
+
for path in (chart.path, *derivatives):
|
|
103
|
+
typer.echo(f"{path} {path.stat().st_size / 1024:.0f} KiB")
|
|
104
|
+
typer.echo(f" rendered {name} in {elapsed:.2f} s")
|
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
# SPDX-FileCopyrightText: 2026 The Linux Foundation
|
|
3
|
+
"""The ``cache`` command group: info and clear (design §4.2)."""
|
|
4
|
+
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
import typer
|
|
10
|
+
|
|
11
|
+
from github_statistics.config import (
|
|
12
|
+
ConfigError,
|
|
13
|
+
NoConfigurationError,
|
|
14
|
+
default_cache_dir,
|
|
15
|
+
resolve,
|
|
16
|
+
)
|
|
17
|
+
from github_statistics.store import (
|
|
18
|
+
SCHEMA_VERSION,
|
|
19
|
+
STORE_FILE,
|
|
20
|
+
describe,
|
|
21
|
+
path_component,
|
|
22
|
+
)
|
|
23
|
+
|
|
24
|
+
# SQLite's side files, removed along with the store they belong to.
|
|
25
|
+
_SUFFIXES = ("", "-journal", "-wal", "-shm")
|
|
26
|
+
|
|
27
|
+
cache_app = typer.Typer(
|
|
28
|
+
name="cache",
|
|
29
|
+
help="Inspect or clear the local store.",
|
|
30
|
+
no_args_is_help=True,
|
|
31
|
+
)
|
|
32
|
+
|
|
33
|
+
_CACHE_DIR = typer.Option(
|
|
34
|
+
None,
|
|
35
|
+
"--cache-dir",
|
|
36
|
+
metavar="DIR",
|
|
37
|
+
help=(
|
|
38
|
+
"Store root (default: the configured cache.directory, else"
|
|
39
|
+
" $XDG_CACHE_HOME/github-statistics)."
|
|
40
|
+
),
|
|
41
|
+
)
|
|
42
|
+
_CONFIG = typer.Option(None, "--config", metavar="PATH", help="Configuration file.")
|
|
43
|
+
_CONFIG_DATA = typer.Option(
|
|
44
|
+
None,
|
|
45
|
+
"--config-data",
|
|
46
|
+
metavar="JSON",
|
|
47
|
+
help="Configuration as JSON or base64 of JSON.",
|
|
48
|
+
)
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def _root(cache_dir: str | None, config: str | None, config_data: str | None) -> Path:
|
|
52
|
+
"""The store root: ``--cache-dir``, the configured one, or the XDG default.
|
|
53
|
+
|
|
54
|
+
With no configuration source at all the XDG default applies; a
|
|
55
|
+
configuration that cannot be read or validated exits 1 rather than
|
|
56
|
+
falling back, so ``clear`` never empties a directory nobody chose.
|
|
57
|
+
An explicit empty ``--cache-dir``, ``--config`` or ``--config-data``,
|
|
58
|
+
such as an unset variable substituted into it, exits 1 for the same
|
|
59
|
+
reason.
|
|
60
|
+
"""
|
|
61
|
+
if cache_dir is not None:
|
|
62
|
+
if not cache_dir:
|
|
63
|
+
typer.echo("error: --cache-dir must not be empty", err=True)
|
|
64
|
+
raise typer.Exit(1)
|
|
65
|
+
return Path(cache_dir)
|
|
66
|
+
for flag, value in (("--config", config), ("--config-data", config_data)):
|
|
67
|
+
if value is not None and not value:
|
|
68
|
+
typer.echo(f"error: {flag} must not be empty", err=True)
|
|
69
|
+
raise typer.Exit(1)
|
|
70
|
+
try:
|
|
71
|
+
directory = resolve(
|
|
72
|
+
config_data=config_data, config_path=config
|
|
73
|
+
).config.cache.directory
|
|
74
|
+
except NoConfigurationError:
|
|
75
|
+
directory = None
|
|
76
|
+
except ConfigError as exc:
|
|
77
|
+
typer.echo(f"error: {exc}", err=True)
|
|
78
|
+
raise typer.Exit(1) from None
|
|
79
|
+
return Path(directory) if directory else default_cache_dir()
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def _stores(root: Path, owner: str = "*") -> list[Path]:
|
|
83
|
+
"""Every store file under ``root``, optionally for one sanitised owner.
|
|
84
|
+
|
|
85
|
+
``glob`` follows symbolic links, so a candidate whose host
|
|
86
|
+
directory, owner directory or store file is a link is skipped
|
|
87
|
+
before anything resolves it, a cyclic link included, and so is one
|
|
88
|
+
that is not a regular file: ``clear`` never deletes or removes
|
|
89
|
+
anything outside the cache directory, nor a link inside it.
|
|
90
|
+
"""
|
|
91
|
+
return sorted(
|
|
92
|
+
path
|
|
93
|
+
for path in root.glob(f"*/{owner}/{STORE_FILE}")
|
|
94
|
+
if not any(
|
|
95
|
+
level.is_symlink() for level in (path.parent.parent, path.parent, path)
|
|
96
|
+
)
|
|
97
|
+
and path.is_file()
|
|
98
|
+
)
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
@cache_app.command()
|
|
102
|
+
def info(
|
|
103
|
+
cache_dir: str | None = _CACHE_DIR,
|
|
104
|
+
config: str | None = _CONFIG,
|
|
105
|
+
config_data: str | None = _CONFIG_DATA,
|
|
106
|
+
) -> None:
|
|
107
|
+
"""Print each store's path, size, schema version and row counts."""
|
|
108
|
+
root = _root(cache_dir, config, config_data)
|
|
109
|
+
typer.echo(f"cache: {root}")
|
|
110
|
+
stores = _stores(root)
|
|
111
|
+
if not stores:
|
|
112
|
+
typer.echo("no stores")
|
|
113
|
+
return
|
|
114
|
+
for path in stores:
|
|
115
|
+
found = describe(path)
|
|
116
|
+
stale = "" if found.schema_version == SCHEMA_VERSION else " (stale)"
|
|
117
|
+
typer.echo(str(found.path))
|
|
118
|
+
typer.echo(f" size: {found.size} bytes")
|
|
119
|
+
typer.echo(f" schema version: {found.schema_version}{stale}")
|
|
120
|
+
for table, count in found.counts.items():
|
|
121
|
+
typer.echo(f" {table}: {count}")
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
@cache_app.command()
|
|
125
|
+
def clear(
|
|
126
|
+
cache_dir: str | None = _CACHE_DIR,
|
|
127
|
+
config: str | None = _CONFIG,
|
|
128
|
+
config_data: str | None = _CONFIG_DATA,
|
|
129
|
+
owner: str | None = typer.Option(
|
|
130
|
+
None, "--owner", metavar="OWNER", help="Clear this owner's store alone."
|
|
131
|
+
),
|
|
132
|
+
) -> None:
|
|
133
|
+
"""Delete the stores under the cache directory, or one owner's store.
|
|
134
|
+
|
|
135
|
+
Only store files and their regular side files are removed, never
|
|
136
|
+
a link or anything else under the directory; the next ``collect``
|
|
137
|
+
rebuilds them from GitHub.
|
|
138
|
+
"""
|
|
139
|
+
root = _root(cache_dir, config, config_data)
|
|
140
|
+
try:
|
|
141
|
+
pattern = "*" if owner is None else path_component(owner, "owner")
|
|
142
|
+
except ValueError as exc:
|
|
143
|
+
typer.echo(f"error: {exc}", err=True)
|
|
144
|
+
raise typer.Exit(1) from None
|
|
145
|
+
stores = _stores(root, pattern)
|
|
146
|
+
if not stores:
|
|
147
|
+
typer.echo("nothing to clear")
|
|
148
|
+
return
|
|
149
|
+
for path in stores:
|
|
150
|
+
for suffix in _SUFFIXES:
|
|
151
|
+
side = path.with_name(path.name + suffix)
|
|
152
|
+
if not side.is_symlink() and side.is_file():
|
|
153
|
+
side.unlink()
|
|
154
|
+
for directory in (path.parent, path.parent.parent):
|
|
155
|
+
try:
|
|
156
|
+
directory.rmdir()
|
|
157
|
+
except OSError:
|
|
158
|
+
break
|
|
159
|
+
typer.echo(f"removed {path}")
|
|
@@ -0,0 +1,219 @@
|
|
|
1
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
# SPDX-FileCopyrightText: 2026 The Linux Foundation
|
|
3
|
+
"""The ``collect`` command: sync the store for the resolved scope (design §4.2, §6.5).
|
|
4
|
+
|
|
5
|
+
Each target syncs into its own store under its own budget, and the
|
|
6
|
+
command prints a short table of what each did. A spent budget exits 0:
|
|
7
|
+
a cold start takes several runs. ``--strict`` exits 2 once every target
|
|
8
|
+
is done if any repository was unreadable; a rejected token exits 3 at
|
|
9
|
+
once, naming the variable that holds it, never its value.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import asyncio
|
|
15
|
+
import contextlib
|
|
16
|
+
from collections.abc import Sequence
|
|
17
|
+
from datetime import UTC, date, datetime
|
|
18
|
+
from pathlib import Path
|
|
19
|
+
|
|
20
|
+
import httpx
|
|
21
|
+
import typer
|
|
22
|
+
from rich.console import Console
|
|
23
|
+
from rich.table import Table
|
|
24
|
+
|
|
25
|
+
from github_statistics.client import (
|
|
26
|
+
AuthError,
|
|
27
|
+
Budget,
|
|
28
|
+
BudgetExhaustedError,
|
|
29
|
+
ClientError,
|
|
30
|
+
Transport,
|
|
31
|
+
)
|
|
32
|
+
from github_statistics.collect import CollectResult, collect
|
|
33
|
+
from github_statistics.config import (
|
|
34
|
+
ConfigError,
|
|
35
|
+
Resolution,
|
|
36
|
+
Target,
|
|
37
|
+
default_cache_dir,
|
|
38
|
+
resolve_token,
|
|
39
|
+
)
|
|
40
|
+
from github_statistics.store import Store, store_path
|
|
41
|
+
|
|
42
|
+
from .common import append_summary, fail, write_outputs
|
|
43
|
+
from .options import SharedOptions, shared_options
|
|
44
|
+
|
|
45
|
+
STRICT_EXIT = 2
|
|
46
|
+
AUTH_EXIT = 3
|
|
47
|
+
|
|
48
|
+
_Table = tuple[str, list[str], list[list[str]]]
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
async def _collect_target(
|
|
52
|
+
resolution: Resolution,
|
|
53
|
+
target: Target,
|
|
54
|
+
*,
|
|
55
|
+
now: datetime,
|
|
56
|
+
until: date | None,
|
|
57
|
+
refresh: bool,
|
|
58
|
+
) -> CollectResult:
|
|
59
|
+
"""Collect ``target`` with its own transport, budget and store.
|
|
60
|
+
|
|
61
|
+
``until`` ends the window, by default the day before ``now``.
|
|
62
|
+
"""
|
|
63
|
+
config = resolution.config
|
|
64
|
+
limits = config.budget
|
|
65
|
+
budget = Budget(
|
|
66
|
+
rest=limits.rest, graphql_points=limits.graphql_points, reserve=limits.reserve
|
|
67
|
+
)
|
|
68
|
+
directory = config.cache.directory
|
|
69
|
+
cache = Path(directory) if directory else default_cache_dir()
|
|
70
|
+
async with Transport(resolve_token(target), budget=budget) as transport:
|
|
71
|
+
# A rate limit outlasting the retries has stopped the transport:
|
|
72
|
+
# collect then sends nothing and reports its scope step spent.
|
|
73
|
+
with contextlib.suppress(BudgetExhaustedError):
|
|
74
|
+
await transport.seed_budget()
|
|
75
|
+
host = httpx.URL(transport.api_url).host
|
|
76
|
+
with Store(store_path(cache, host, target.owner)) as store:
|
|
77
|
+
return await collect(
|
|
78
|
+
config,
|
|
79
|
+
target,
|
|
80
|
+
now=now,
|
|
81
|
+
transport=transport,
|
|
82
|
+
store=store,
|
|
83
|
+
identities=resolution.cli_identities,
|
|
84
|
+
refresh=refresh,
|
|
85
|
+
until=until,
|
|
86
|
+
)
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def _tables(results: Sequence[CollectResult]) -> list[_Table]:
|
|
90
|
+
"""The summary of ``results`` as titled tables of plain text."""
|
|
91
|
+
runs = [
|
|
92
|
+
[
|
|
93
|
+
result.owner,
|
|
94
|
+
str(result.requests),
|
|
95
|
+
str(result.graphql_points),
|
|
96
|
+
str(result.not_modified),
|
|
97
|
+
result.exhausted or "no",
|
|
98
|
+
str(result.gap_days),
|
|
99
|
+
]
|
|
100
|
+
for result in results
|
|
101
|
+
]
|
|
102
|
+
coverage = [
|
|
103
|
+
[result.owner, metric, str(days.complete), str(days.partial), str(days.missing)]
|
|
104
|
+
for result in results
|
|
105
|
+
for metric, days in result.coverage.items()
|
|
106
|
+
]
|
|
107
|
+
repositories = [
|
|
108
|
+
[key, reason]
|
|
109
|
+
for result in results
|
|
110
|
+
for group in (result.unreadable, result.dropped)
|
|
111
|
+
for key, reason in group.items()
|
|
112
|
+
]
|
|
113
|
+
repositories += [
|
|
114
|
+
[key, "runs read stalled"] for result in results for key in result.stalled
|
|
115
|
+
]
|
|
116
|
+
tables: list[_Table] = [
|
|
117
|
+
(
|
|
118
|
+
"Collection",
|
|
119
|
+
[
|
|
120
|
+
"Owner",
|
|
121
|
+
"Requests",
|
|
122
|
+
"GraphQL points",
|
|
123
|
+
"304s",
|
|
124
|
+
"Budget spent in",
|
|
125
|
+
"Gap days",
|
|
126
|
+
],
|
|
127
|
+
runs,
|
|
128
|
+
),
|
|
129
|
+
("Coverage", ["Owner", "Metric", "Complete", "Partial", "Missing"], coverage),
|
|
130
|
+
]
|
|
131
|
+
if repositories:
|
|
132
|
+
tables.append(("Repositories", ["Repository", "Status"], repositories))
|
|
133
|
+
return tables
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def _markdown(tables: list[_Table]) -> str:
|
|
137
|
+
"""``tables`` as Markdown, for the job summary."""
|
|
138
|
+
lines: list[str] = []
|
|
139
|
+
for title, headers, rows in tables:
|
|
140
|
+
lines += [f"### {title}", "", "| " + " | ".join(headers) + " |"]
|
|
141
|
+
lines.append("|" + "|".join(" --- " for _ in headers) + "|")
|
|
142
|
+
lines += ["| " + " | ".join(row) + " |" for row in rows]
|
|
143
|
+
lines.append("")
|
|
144
|
+
return "\n".join(lines)
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def collect_target(
|
|
148
|
+
resolution: Resolution,
|
|
149
|
+
target: Target,
|
|
150
|
+
*,
|
|
151
|
+
now: datetime,
|
|
152
|
+
until: date | None,
|
|
153
|
+
refresh: bool,
|
|
154
|
+
) -> CollectResult:
|
|
155
|
+
"""Collect ``target``; a rejected token or a failed read raises the exit to raise.
|
|
156
|
+
|
|
157
|
+
A rejected token exits `AUTH_EXIT`, naming the variable that holds
|
|
158
|
+
it, never its value; any other client failure exits 1.
|
|
159
|
+
"""
|
|
160
|
+
try:
|
|
161
|
+
return asyncio.run(
|
|
162
|
+
_collect_target(resolution, target, now=now, until=until, refresh=refresh)
|
|
163
|
+
)
|
|
164
|
+
except AuthError:
|
|
165
|
+
raise fail(
|
|
166
|
+
f"GitHub rejected the token in ${target.token_env} (HTTP 401)", AUTH_EXIT
|
|
167
|
+
) from None
|
|
168
|
+
except (ClientError, httpx.HTTPError) as exc:
|
|
169
|
+
raise fail(f"cannot collect {target.owner}: {exc}") from None
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
def report(results: Sequence[CollectResult]) -> str:
|
|
173
|
+
"""Print the summary tables of ``results``; the same tables as Markdown."""
|
|
174
|
+
tables = _tables(results)
|
|
175
|
+
console = Console()
|
|
176
|
+
for title, headers, rows in tables:
|
|
177
|
+
table = Table(*headers, title=title)
|
|
178
|
+
for row in rows:
|
|
179
|
+
table.add_row(*row)
|
|
180
|
+
console.print(table)
|
|
181
|
+
return _markdown(tables)
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def collect_outputs(results: Sequence[CollectResult]) -> dict[str, str]:
|
|
185
|
+
"""The step outputs ``results`` give: requests, coverage and gap days."""
|
|
186
|
+
complete = all(result.coverage_complete for result in results)
|
|
187
|
+
return {
|
|
188
|
+
"requests_used": str(sum(result.requests for result in results)),
|
|
189
|
+
"coverage_complete": str(complete).lower(),
|
|
190
|
+
"gap_days": str(sum(result.gap_days for result in results)),
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
@shared_options
|
|
195
|
+
def collect_command(
|
|
196
|
+
options: SharedOptions,
|
|
197
|
+
refresh: bool = typer.Option(
|
|
198
|
+
False, "--refresh", help="Ignore watermarks and coverage; re-read the window."
|
|
199
|
+
),
|
|
200
|
+
strict: bool = typer.Option(
|
|
201
|
+
False, "--strict", help="Exit 2 if any repository was unreadable."
|
|
202
|
+
),
|
|
203
|
+
) -> None:
|
|
204
|
+
"""Sync the store for each target's resolved public repositories."""
|
|
205
|
+
try:
|
|
206
|
+
resolution = options.resolve()
|
|
207
|
+
except ConfigError as exc:
|
|
208
|
+
raise fail(str(exc)) from None
|
|
209
|
+
now = datetime.now(UTC)
|
|
210
|
+
results = [
|
|
211
|
+
collect_target(
|
|
212
|
+
resolution, target, now=now, until=options.until, refresh=refresh
|
|
213
|
+
)
|
|
214
|
+
for target in resolution.config.targets
|
|
215
|
+
]
|
|
216
|
+
append_summary(report(results))
|
|
217
|
+
write_outputs(collect_outputs(results))
|
|
218
|
+
if strict and any(result.unreadable for result in results):
|
|
219
|
+
raise fail("some repositories were unreadable (--strict)", STRICT_EXIT)
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
# SPDX-FileCopyrightText: 2026 The Linux Foundation
|
|
3
|
+
"""Helpers the commands share: the read-only store, failures and GitHub files.
|
|
4
|
+
|
|
5
|
+
A command reports a failure with `fail` and raises the exit it returns.
|
|
6
|
+
Stores open through `ReadOnlyStore` for every command but ``collect``,
|
|
7
|
+
so reading never creates, rebuilds or writes one. `write_outputs` and
|
|
8
|
+
`append_summary` reach the files GitHub Actions names in
|
|
9
|
+
``$GITHUB_OUTPUT`` and ``$GITHUB_STEP_SUMMARY`` and do nothing when
|
|
10
|
+
those are unset.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import os
|
|
16
|
+
import re
|
|
17
|
+
import sqlite3
|
|
18
|
+
import uuid
|
|
19
|
+
from collections.abc import Mapping
|
|
20
|
+
from datetime import date
|
|
21
|
+
from pathlib import Path
|
|
22
|
+
from urllib.parse import urlsplit
|
|
23
|
+
|
|
24
|
+
import typer
|
|
25
|
+
|
|
26
|
+
from github_statistics.client.transport import DEFAULT_API_URL
|
|
27
|
+
from github_statistics.store import SCHEMA_VERSION, Store
|
|
28
|
+
|
|
29
|
+
API_HOST = urlsplit(DEFAULT_API_URL).hostname or "api.github.com"
|
|
30
|
+
|
|
31
|
+
_OUTPUT_KEY = re.compile(r"[A-Za-z0-9_]+")
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class StaleStoreError(Exception):
|
|
35
|
+
"""The store file carries a schema version other than `SCHEMA_VERSION`."""
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class ReadOnlyStore(Store):
|
|
39
|
+
"""A `Store` on a read-only connection: it never creates, rebuilds or writes.
|
|
40
|
+
|
|
41
|
+
One read transaction spans the store's life, from before the schema
|
|
42
|
+
check until `close`, so every query reads the same snapshot and a
|
|
43
|
+
collector committing meanwhile cannot make one document disagree
|
|
44
|
+
with another. A file removed or replaced after the check cannot be
|
|
45
|
+
recreated or rebuilt by this command. While the store is open a
|
|
46
|
+
collector's commit waits on it, up to the collector's busy timeout.
|
|
47
|
+
"""
|
|
48
|
+
|
|
49
|
+
def __init__(self, path: Path) -> None:
|
|
50
|
+
"""Open the store at ``path`` read-only; raise unless it is current.
|
|
51
|
+
|
|
52
|
+
`sqlite3.DatabaseError` when no database can be read there,
|
|
53
|
+
`StaleStoreError` when its schema version is not `SCHEMA_VERSION`.
|
|
54
|
+
"""
|
|
55
|
+
self.path = Path(path)
|
|
56
|
+
self._savepoints = 0
|
|
57
|
+
uri = self.path.resolve().as_uri() + "?mode=ro"
|
|
58
|
+
self._connection = sqlite3.connect(uri, uri=True, isolation_level=None)
|
|
59
|
+
self._connection.row_factory = sqlite3.Row
|
|
60
|
+
try:
|
|
61
|
+
self._connection.execute("BEGIN")
|
|
62
|
+
if self.schema_version() != SCHEMA_VERSION:
|
|
63
|
+
raise StaleStoreError(str(self.path))
|
|
64
|
+
except BaseException:
|
|
65
|
+
self._connection.close()
|
|
66
|
+
raise
|
|
67
|
+
|
|
68
|
+
def close(self) -> None:
|
|
69
|
+
"""End the read transaction and close the connection."""
|
|
70
|
+
if self._connection.in_transaction:
|
|
71
|
+
self._connection.execute("ROLLBACK")
|
|
72
|
+
self._connection.close()
|
|
73
|
+
|
|
74
|
+
def scoped_between(self, first: date, last: date) -> list[str]:
|
|
75
|
+
"""The repositories in scope on any day from ``first`` to ``last``, sorted.
|
|
76
|
+
|
|
77
|
+
An interval that opened and closed on one day holds no day, so it
|
|
78
|
+
does not count.
|
|
79
|
+
"""
|
|
80
|
+
rows = self._connection.execute(
|
|
81
|
+
"SELECT DISTINCT repo FROM scope WHERE from_day <= ?"
|
|
82
|
+
" AND (to_day IS NULL OR (to_day > ? AND to_day > from_day))"
|
|
83
|
+
" ORDER BY repo",
|
|
84
|
+
(last.isoformat(), first.isoformat()),
|
|
85
|
+
)
|
|
86
|
+
return [row[0] for row in rows]
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def fail(message: str, code: int = 1) -> typer.Exit:
|
|
90
|
+
"""Report ``message`` on standard error; the exit with ``code`` to raise."""
|
|
91
|
+
typer.echo(f"error: {message}", err=True)
|
|
92
|
+
return typer.Exit(code)
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def write_outputs(outputs: Mapping[str, str], *, heredoc: bool = False) -> None:
|
|
96
|
+
"""Append ``outputs`` to ``$GITHUB_OUTPUT``, when set.
|
|
97
|
+
|
|
98
|
+
Each output is a ``key=value`` line, or with ``heredoc`` the
|
|
99
|
+
multiline ``key<<DELIMITER`` form under a fresh delimiter no value
|
|
100
|
+
holds. A key outside ``[A-Za-z0-9_]``, or a value holding a line
|
|
101
|
+
break or ``<<``, could start another output or a multiline one, so
|
|
102
|
+
the whole set is refused before anything is written.
|
|
103
|
+
"""
|
|
104
|
+
path = os.environ.get("GITHUB_OUTPUT")
|
|
105
|
+
if not path:
|
|
106
|
+
return
|
|
107
|
+
for key, value in outputs.items():
|
|
108
|
+
if not _OUTPUT_KEY.fullmatch(key):
|
|
109
|
+
raise fail(f"refusing the output name {key!r}")
|
|
110
|
+
if "\n" in value or "\r" in value or "<<" in value:
|
|
111
|
+
raise fail(f"refusing the value of output {key}: it could inject another")
|
|
112
|
+
with open(path, "a", encoding="utf-8") as handle:
|
|
113
|
+
for key, value in outputs.items():
|
|
114
|
+
if not heredoc:
|
|
115
|
+
handle.write(f"{key}={value}\n")
|
|
116
|
+
continue
|
|
117
|
+
delimiter = f"ghadelimiter_{uuid.uuid4()}"
|
|
118
|
+
while delimiter in value:
|
|
119
|
+
delimiter = f"ghadelimiter_{uuid.uuid4()}"
|
|
120
|
+
handle.write(f"{key}<<{delimiter}\n{value}\n{delimiter}\n")
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def append_summary(markdown: str) -> None:
|
|
124
|
+
"""Append ``markdown`` to ``$GITHUB_STEP_SUMMARY``, when set."""
|
|
125
|
+
path = os.environ.get("GITHUB_STEP_SUMMARY")
|
|
126
|
+
if path:
|
|
127
|
+
with open(path, "a", encoding="utf-8") as handle:
|
|
128
|
+
handle.write(markdown)
|