Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 5 additions & 4 deletions .github/workflows/update-contributors.yml
Original file line number Diff line number Diff line change
Expand Up @@ -75,11 +75,12 @@ jobs:
# GitHub computes `/stats/contributors` asynchronously and caches it. Merging invalidates
# that cache, so this run gets either a 202 it waits out or a cached 200 from before the
# merge - and the second looks exactly like success: no diff, no pull request, green tick.
# Naming who this run was fired for turns that into a failed run somebody can see.
# Naming who this run was fired for turns that into a warning on the run somebody can see.
#
# It is not a gate on anything, and a red run here means only "the weekly schedule will
# credit them instead". Failing loudly is the point; it is the difference between knowing
# this trigger works and assuming it does.
# A warning and not a failure, because neither cause is fixed by a rerun. The usual one is a
# contributor whose commit email is not on their GitHub account: GitHub links none of their
# commits, so they are absent from every run, and failing turned each of their merges into a
# red run while also skipping the pull request below. The warning says which cause it was.
# **The login goes through `env:`, never interpolated into the command line.** It is a
# value an outside person chooses, this job runs with a write token, and `${{ }}` inside
# `run:` is textual substitution into the shell - which is the standard injection route
Expand Down
65 changes: 53 additions & 12 deletions scripts/fetch_contributors.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@
import sys
import time
import urllib.error
import urllib.parse
import urllib.request
from pathlib import Path

Expand Down Expand Up @@ -203,12 +204,11 @@ def missing_from(contributors: list[dict], expected: str | None) -> bool:
cached 200 from before the merge, and the second is indistinguishable from success. Nothing
changes, no pull request opens, and the run is green.

So the merge-triggered run says who it expected to find. Absent means the weekly schedule is
what will actually credit them, and that is worth a failed run on the Actions tab rather than
a green one that did nothing.
So the merge-triggered run says who it expected to find, and an absence is reported as a
warning on the run rather than passing unremarked. See why_missing() for what it says.

An excluded login is not missing - it was never going to be there. Without this, merging a
pull request authored by one of the tool accounts in EXCLUDED_LOGINS would fail every time,
pull request authored by one of the tool accounts in EXCLUDED_LOGINS would warn every time,
correctly by the letter and uselessly in practice.
"""
if not expected or expected.lower() in EXCLUDED_LOGINS:
Expand All @@ -217,6 +217,50 @@ def missing_from(contributors: list[dict], expected: str | None) -> bool:
return not any(c["login"].lower() == expected.lower() for c in contributors)


def linked_commits(login: str) -> int | None:
"""
How many of this person's commits on the default branch GitHub links to their account,
leaving out merge commits, or None if GitHub could not be asked.

Merges are left out because `/stats/contributors` leaves them out. Somebody who merged a pull
request through the web interface has a linked merge commit, and that is enough for GitHub's
own contributor sidebar, but not for this list.
"""
url = (f"https://api.github.com/repos/{REPO}/commits"
f"?author={urllib.parse.quote(login)}&per_page=100")
try:
with _request(url) as response:
commits = json.loads(response.read())
except Exception: # noqa: BLE001 - only used to word a warning
return None
return sum(1 for commit in commits if len(commit.get("parents", [])) == 1)


def why_missing(login: str, linked: int | None) -> str:
"""
One line saying why `login` is absent, for the run's warning.

<b>Usually it is the commit email, not the cache.</b> `/stats/contributors` credits a commit
to an account only when its author email is on that account. A contributor committing from
an address they never added to GitHub is absent from every run, the weekly one included, so
a rerun cannot fix it and failing the run over it only produced a red run per merge. That
happened for every pull request one contributor merged, over three days.
"""
if linked == 0:
return (f"{login} is not in the contributor list: none of their commits on the default "
"branch are linked to their GitHub account, which usually means the commit email "
"is not on it. Adding that address under GitHub Settings > Emails links the "
"existing commits too, and the next run credits them.")
if linked is None:
return (f"{login} is not in the contributor list, and GitHub could not be asked whether "
"their commits are linked to their account. Either the commit email is not on "
"their GitHub account, or the stats were cached from before the merge and the "
"weekly run will add them.")
return (f"{login} is not in the contributor list although {linked} of their commits are "
"linked to their account, so GitHub's contributor stats were probably cached from "
"before the merge. The weekly run will add them.")


def _keep_what_we_have(error: Exception) -> int:
"""
What to do when the stats never arrived: nothing, and say so.
Expand Down Expand Up @@ -245,7 +289,7 @@ def main(argv: list[str] | None = None) -> int:
parser.add_argument(
"--expect-contributor",
metavar="LOGIN",
help="fail if this login is absent from the generated list - see missing_from()")
help="warn if this login is absent from the generated list - see missing_from()")
args = parser.parse_args(sys.argv[1:] if argv is None else argv)

print(f"Fetching contributors for {REPO} ...")
Expand Down Expand Up @@ -302,14 +346,11 @@ def main(argv: list[str] | None = None) -> int:
print(f"\nWrote {len(contributors)} contributor(s) to "
f"{MANIFEST.relative_to(REPO_ROOT)}")

# A warning, not a failure: neither cause is fixed by rerunning this job, and a failed run
# also skipped opening the pull request for whatever else this run found.
if missing_from(contributors, args.expect_contributor):
print(f"\n{args.expect_contributor} is not in the list this run generated.",
file=sys.stderr)
print("GitHub's contributor stats are computed asynchronously and cached, so a run "
"fired by a merge can be answered from before it. The weekly schedule will pick "
"them up; this is a failed run rather than a green one that credited nobody.",
file=sys.stderr)
return 1
login = args.expect_contributor
print(f"::warning title=Not credited::{why_missing(login, linked_commits(login))}")

return 0

Expand Down
70 changes: 69 additions & 1 deletion scripts/test/test_fetch_contributors.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@
200 from before the merge. The second is indistinguishable from success - nothing changes, no
pull request opens, and the workflow is green having credited nobody.

`--expect-contributor` is what makes that visible, and this is the predicate behind it.
`--expect-contributor` is what makes that visible, as a warning naming the cause, and these are
the predicates behind it.
"""

from __future__ import annotations
Expand Down Expand Up @@ -174,3 +175,70 @@ def __exit__(self, *_):

with pytest.raises(RuntimeError):
fc.fetch_stats()


def test_unlinked_commits_are_named_as_the_cause():
"""The case that actually happened: every commit from an address not on the account."""
message = fc.why_missing("someone", 0)
assert "linked to their GitHub account" in message
assert "Settings > Emails" in message
assert "cached" not in message


def test_linked_commits_point_at_a_stale_cache():
message = fc.why_missing("someone", 4)
assert "cached from before the merge" in message
assert "Settings > Emails" not in message


def test_not_being_able_to_ask_names_both_causes():
message = fc.why_missing("someone", None)
assert "email" in message and "cached" in message


def test_merge_commits_do_not_count_as_linked(monkeypatch):
"""
A merge through the web interface is linked, but `/stats/contributors` ignores merges, so it
must not make an unlinked contributor read as a stale cache.
"""
class Response:
def read(self):
return (b'[{"sha": "a", "parents": [{"sha": "p"}, {"sha": "q"}]},'
b' {"sha": "b", "parents": [{"sha": "p"}]}]')

def __enter__(self):
return self

def __exit__(self, *_):
return False

monkeypatch.setattr(fc, "_request", lambda *_args, **_kwargs: Response())
assert fc.linked_commits("someone") == 1


def test_a_lookup_that_fails_says_so_rather_than_raising(monkeypatch):
def refuse(*_args, **_kwargs):
raise OSError("no network")

monkeypatch.setattr(fc, "_request", refuse)
assert fc.linked_commits("someone") is None


def test_a_missing_contributor_warns_and_does_not_fail(monkeypatch, tmp_path, capsys):
"""
The run that failed over this was red three times for one contributor whose commits GitHub
never links. It warns now, with the cause, and exits 0 so the pull request step still runs.
"""
monkeypatch.setattr(fc, "fetch_stats", lambda: [
{"author": {"login": "parawanderer", "type": "User"}, "total": 9, "weeks": []}])
monkeypatch.setattr(fc, "download_avatar", lambda *_args: None)
monkeypatch.setattr(fc, "linked_commits", lambda _login: 0)
monkeypatch.setattr(fc, "ASSETS", tmp_path)
monkeypatch.setattr(fc, "MANIFEST", tmp_path / "contributors.json")
monkeypatch.setattr(fc, "AVATAR_DIR", tmp_path / "contributors")
monkeypatch.setattr(fc, "REPO_ROOT", tmp_path)

assert fc.main(["--expect-contributor", "someone"]) == 0
out = capsys.readouterr().out
assert "::warning title=Not credited::someone" in out
assert "linked to their GitHub account" in out