Skip to content

Commit bb33eb8

Browse files
niccokunzmannclaude
andcommitted
Add the page Trends and a robots.txt
Trends (/s/<scope>/trends/): issues on one side, pull requests on the other. Opened, closed (merged as a part), contributions by people and new contributors, each next to the time of the same length just before, with charts per day, week or month (SVG and Chart.js) and the new contributors listed. Every statistics page offers the last 7, 30 and 90 days next to the From/To dates. Documented in explanation/trends, translated to German and Spanish (added with polib: gettext is missing on this machine). The performance test grouped by the old name "class". robots.txt: crawlers read the start page, Explore, About and the badges, not the statistics, which are computed on each request; nginx serves it from the static files. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 0073b69 commit bb33eb8

38 files changed

Lines changed: 1542 additions & 18 deletions

‎Makefile‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -203,15 +203,17 @@ docker-build-all: version ## Build the container for amd64 and arm64, like the
203203
docker buildx build --platform linux/amd64,linux/arm64 -t community-insights .
204204

205205
.PHONY: docker-test
206-
docker-test: docker-build ## Run the container with ALLOWED_HOSTS and check that Docker sees it healthy
206+
docker-test: docker-build ## Run the container with ALLOWED_HOSTS: Docker sees it healthy, nginx serves robots.txt
207207
@docker rm -f community-insights-test >/dev/null 2>&1 || true
208208
@docker run -d --name community-insights-test -p 5099:5000 -e PRODUCTION=false \
209209
-e ALLOWED_HOSTS=community.example.org \
210210
-e DEFAULT_SUPERUSER=admin@example.com:admin community-insights >/dev/null
211211
@# the HEALTHCHECK of the image, as Docker and Sencho see it, with the hosts of a real site
212212
@for i in $$(seq 90); do [ "$$(docker inspect -f '{{.State.Health.Status}}' community-insights-test)" = healthy ] && echo healthy && break; sleep 1; done; \
213213
healthy=$$([ "$$(docker inspect -f '{{.State.Health.Status}}' community-insights-test)" = healthy ] \
214-
&& curl -sf -H "Host: community.example.org" http://localhost:5099/health/ >/dev/null && echo yes); \
214+
&& curl -sf -H "Host: community.example.org" http://localhost:5099/health/ >/dev/null \
215+
&& curl -sfi http://localhost:5099/robots.txt | grep -qi "^Cache-Control: max-age=86400" \
216+
&& curl -sf http://localhost:5099/robots.txt | grep -q "^Disallow: /s/" && echo yes); \
215217
[ "$$healthy" = yes ] || { docker logs community-insights-test; \
216218
docker inspect -f '{{json .State.Health.Log}}' community-insights-test; }; \
217219
docker rm -f community-insights-test >/dev/null; [ "$$healthy" = yes ]

‎community_insights/chart_data.py‎

Lines changed: 50 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,19 @@
1010

1111
from django.utils.translation import gettext
1212

13-
from .charts import BAR, GAP, HEAT_STOPS, HOURS, INK, KIND_COLORS, KINDS, WEEKDAYS, month_span
13+
from .charts import (
14+
BAR,
15+
BAR_LENGTHS,
16+
GAP,
17+
HEAT_STOPS,
18+
HOURS,
19+
INK,
20+
KIND_COLORS,
21+
KINDS,
22+
PAIR_COLORS,
23+
WEEKDAYS,
24+
month_span,
25+
)
1426
from .stats import histogram
1527

1628
# the charts of charts.py that Chart.js can draw, by their names in addresses
@@ -22,6 +34,10 @@
2234
"hours",
2335
"heatmap",
2436
"months",
37+
"trend-pr",
38+
"trend-issue",
39+
"people-pr",
40+
"people-issue",
2541
)
2642

2743

@@ -241,3 +257,36 @@ def month_chart(months, theme: str = "light") -> dict:
241257
y=gettext("activities (number)"),
242258
stacked=True,
243259
)
260+
261+
262+
def pair_chart(
263+
title: str, labels: list[str], series: list[tuple[str, list[int]]], size: str, theme: str
264+
) -> dict:
265+
"""Two series of numbers per day, week or month as bars side by side (page Trends).
266+
267+
Args:
268+
title: What the chart shows.
269+
labels: The days, weeks or months.
270+
series: The name and the numbers of each series, at most two.
271+
size: ``day``, ``week`` or ``month``: the title of the time axis.
272+
theme: ``light`` or ``dark``: the colours of the page the chart is on.
273+
274+
Returns:
275+
The chart for Chart.js.
276+
277+
Examples:
278+
>>> chart = pair_chart("t", ["2026-11"], [("a", [1]), ("b", [2])], "month", "light")
279+
>>> [d["data"] for d in chart["datasets"]], chart["x"]
280+
([[1], [2]], 'month')
281+
"""
282+
return config(
283+
"bar",
284+
labels,
285+
[
286+
{"label": name, "data": list(values), "backgroundColor": color}
287+
for (name, values), color in zip(series, PAIR_COLORS[theme], strict=False)
288+
],
289+
theme,
290+
x=str(BAR_LENGTHS.get(size, size)),
291+
title=title,
292+
)

‎community_insights/charts.py‎

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -451,3 +451,55 @@ def month_chart(months, theme: str = "light") -> bytes:
451451
axes.set_ylabel(gettext("activities (number)"))
452452
style(axes, theme, legend=True)
453453
return svg(figure)
454+
455+
456+
# two series side by side, as the first two kinds of activity
457+
PAIR_COLORS = {
458+
theme: [colors["pull request"], colors["issue"]] for theme, colors in KIND_COLORS.items()
459+
}
460+
# the time axis of the charts of the page Trends, by the length of a bar
461+
BAR_LENGTHS = {
462+
"day": gettext_lazy("day"),
463+
"week": gettext_lazy("week, from Monday"),
464+
"month": gettext_lazy("month"),
465+
}
466+
467+
468+
def pair_chart(
469+
title: str, labels: list[str], series: list[tuple[str, list[int]]], size: str, theme: str
470+
) -> bytes:
471+
"""Two series of numbers per day, week or month as bars side by side (page Trends).
472+
473+
Args:
474+
title: What the chart shows.
475+
labels: The days, weeks or months.
476+
series: The name and the numbers of each series, at most two.
477+
size: ``day``, ``week`` or ``month``: the title of the time axis.
478+
theme: ``light`` or ``dark``: the colours of the page the chart is on.
479+
480+
Returns:
481+
The SVG; a chart that says so without anything in the time range.
482+
"""
483+
plt = pyplot()
484+
if not any(any(values) for _, values in series):
485+
return empty(gettext("nothing in this time"), theme)
486+
figure, axes = plt.subplots(figsize=(7, 2.8))
487+
width = 0.8 / len(series)
488+
for index, ((name, values), color) in enumerate(zip(series, PAIR_COLORS[theme], strict=False)):
489+
axes.bar(
490+
[i + (index - (len(series) - 1) / 2) * width for i in range(len(labels))],
491+
values,
492+
width=width,
493+
color=color,
494+
label=name,
495+
)
496+
step = max(1, len(labels) // 12)
497+
axes.set_xticks(range(0, len(labels), step), labels[::step], rotation=45, ha="right")
498+
axes.set_xlabel(str(BAR_LENGTHS.get(size, size)))
499+
axes.set_title(title, fontsize=10)
500+
with LOCK: # see heavy.py
501+
from matplotlib.ticker import MaxNLocator
502+
503+
axes.yaxis.set_major_locator(MaxNLocator(integer=True)) # no half contributions
504+
style(axes, theme, legend=True)
505+
return svg(figure)

‎community_insights/stats/__init__.py‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,12 +2,15 @@
22

33
from .activity import activity_of, by_hour_and_weekday, by_month_and_kind, responses_by_month
44
from .bot_suggestions import BotSuggestion, bot_suggestions
5+
from .change import Change
56
from .contributor import Contributor
67
from .contributor_replies import ContributorReplies
78
from .contributors import contributors
89
from .counts import counts
910
from .fit import FitRow, best_fit, summary
1011
from .format import format_duration
12+
from .kind_series import kind_series
13+
from .kind_trend import KindTrend, kind_trend
1114
from .models import MODELS, model_percentile, times_of
1215
from .pull_reply import PullReply
1316
from .replies import (
@@ -43,6 +46,10 @@
4346
from .trend import Trend, trend
4447

4548
__all__ = [
49+
"Change",
50+
"KindTrend",
51+
"kind_series",
52+
"kind_trend",
4653
"FIRST",
4754
"Response",
4855
"bot_test",

‎community_insights/stats/change.py‎

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
"""A number of a time range next to the same number of the period before it."""
2+
3+
from dataclasses import dataclass
4+
5+
6+
@dataclass(frozen=True)
7+
class Change:
8+
"""A number of a time range and the same number of the period of the same length before.
9+
10+
Attributes:
11+
now: The number in the time range.
12+
before: The number in the period before; None when there is nothing to compare with,
13+
such as for all time.
14+
15+
Examples:
16+
>>> Change(15, 10).percent, Change(15, 10).difference
17+
(50.0, 5)
18+
>>> Change(3, 0).percent is None, Change(3, None).difference is None
19+
(True, True)
20+
"""
21+
22+
now: int
23+
before: int | None = None
24+
25+
@property
26+
def difference(self) -> int | None:
27+
"""How many more (positive) or fewer (negative) than before; None without before."""
28+
return None if self.before is None else self.now - self.before
29+
30+
@property
31+
def percent(self) -> float | None:
32+
"""The change in percent of before; None without before or when it was 0."""
33+
if not self.before:
34+
return None
35+
return (self.now - self.before) / self.before * 100
Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
"""Pull requests or issues per day, week or month: for the charts of the page Trends."""
2+
3+
from datetime import datetime, tzinfo
4+
5+
from django.db.models import Min
6+
7+
from ..models import Item
8+
from .kind_trend import contribution_events, first_contributions, in_range
9+
from .periods import buckets, count_by, label, size_of
10+
11+
# the numbers per bar, by their keys in what kind_series returns
12+
SERIES = ("opened", "closed", "contributions", "newcomers")
13+
14+
15+
def kind_series(
16+
repositories,
17+
kind: str,
18+
since: datetime | None,
19+
until: datetime | None,
20+
now: datetime,
21+
tz: tzinfo,
22+
) -> dict:
23+
"""Opened, closed, contributions and new contributors per day, week or month.
24+
25+
For pull requests or for issues, in each day, week or month of the time range.
26+
27+
Args:
28+
repositories: The repositories.
29+
kind: ``pr`` or ``issue``.
30+
since: The start of the time range, None for the first item or contribution.
31+
until: The end of the time range, excluded; None for now.
32+
now: The time now: the end of a range without one.
33+
tz: The time zone of the days.
34+
35+
Returns:
36+
``size`` (``day``, ``week`` or ``month``), ``labels`` of the bars, and for each bar
37+
``opened``, ``closed``, ``contributions`` and ``newcomers``; no labels without data.
38+
"""
39+
items = Item.objects.filter(repository__in=repositories, kind=kind)
40+
events = contribution_events(repositories, kind)
41+
end = until or now
42+
start = since or min(
43+
(
44+
found
45+
for found in (
46+
items.aggregate(first=Min("created_at"))["first"],
47+
events.aggregate(first=Min("at"))["first"],
48+
)
49+
if found is not None
50+
),
51+
default=None,
52+
)
53+
if start is None or start >= end:
54+
return {"size": "", "labels": []} | {name: [] for name in SERIES}
55+
size = size_of(start, end)
56+
57+
def per_bar(query, field: str) -> list[int]:
58+
times = in_range(query, field, start, end).values_list(field, flat=True)
59+
return count_by(times.iterator(), start, end, size, tz)
60+
61+
return {
62+
"size": size,
63+
"labels": [label(day, size) for day in buckets(start, end, size, tz)],
64+
"opened": per_bar(items, "created_at"),
65+
"closed": per_bar(items.filter(closed_at__isnull=False), "closed_at"),
66+
"contributions": per_bar(events, "at"),
67+
"newcomers": count_by(
68+
(at for _, at in first_contributions(repositories, kind)), start, end, size, tz
69+
),
70+
}

0 commit comments

Comments
 (0)