diff --git a/README.md b/README.md index 79a5c55..0985d5b 100644 --- a/README.md +++ b/README.md @@ -153,7 +153,8 @@ authors' profile pictures. Nothing to configure: repositories). - GitLab: GitLab is asked who wrote each author's commit, so the commit email is matched against all of the user's verified emails, like on GitLab's own pages. The commit asked about - is the author's newest *pushed* commit (GitLab can't know local-only commits). Public projects need + is the author's newest *pushed* commit (GitLab can't know local-only commits); your own + picture comes straight from your GitLab profile (any verified email). Public projects need nothing. **Private projects need a token** (an SSH key is not enough: it only works for git, not for GitLab's API): `GITLAB_TOKEN` with the `read_api` scope, or a `glab auth login` for that server, are used when already there (`GITLAB_TOKEN` only when `GITLAB_HOST` is unset or diff --git a/TESTING.md b/TESTING.md index 316b259..c233c88 100644 --- a/TESTING.md +++ b/TESTING.md @@ -175,6 +175,14 @@ Originally reported by the user on Windows (fixed on macOS, verified above): lookup; network trouble answers `503` + `Retry-After` and the page asks again (3 tries). `LOOKUP_VERSION` 3 re-asks the misses cached by 1.1.1. + **Only my own picture missing with 1.1.2 (2026/11/27, fixed in 1.1.3):** everyone else showed, + the token owner did not; a "no picture" was cached for their email (with a token). GitLab + itself answered correctly for 6 of their pushed commits, so the commit chosen locally was not + one GitLab could name (own work is the most likely to be unpushed), and the public-email + fallback finds nothing without a public email. Now the token owner's verified emails and + picture come from `/api/v4/user` + `/api/v4/user/emails` (once per run), no commit needed. + Verified live with an unknown commit id: picture in 1.6 s. `LOOKUP_VERSION` 4. + **Launch page (2026/11/27):** a cold Chromium start takes ~2-3 s on Windows, during which the private launch page is visible; it used to be a bare "Open gitgraph" link. It now shows the logo and "Opening …" in the app's colours and forwards with `location.replace` (meta diff --git a/src/gitgraph/__init__.py b/src/gitgraph/__init__.py index 17d955d..7a4a6ef 100644 --- a/src/gitgraph/__init__.py +++ b/src/gitgraph/__init__.py @@ -1,3 +1,3 @@ """gitgraph - interactive, GitLab-style commit graph for any git repository.""" -__version__ = "1.1.2" +__version__ = "1.1.3" diff --git a/src/gitgraph/avatars.py b/src/gitgraph/avatars.py index 1076116..aa094b3 100644 --- a/src/gitgraph/avatars.py +++ b/src/gitgraph/avatars.py @@ -8,7 +8,9 @@ (GraphQL), which matches the commit email against all of a user's verified emails, like GitLab's own pages. Private projects need a token the user already has (``GITLAB_TOKEN`` or a ``glab auth login`` for that server). - The commit asked about is the author's newest pushed non-merge commit + The token's owner (you) is recognised by any of their verified emails and + gets their own profile picture, even for commits not pushed yet. + For others, the commit asked about is the author's newest pushed non-merge commit (GitLab cannot know local-only commits). If GitLab cannot answer, the ``/api/v4/avatar`` lookup is used, which only knows public profile emails. Gravatar answers are ignored: only pictures people uploaded to the host. @@ -43,7 +45,7 @@ MISS_TTL_S = 24 * 3600 # Bumped when lookups find more pictures than before: "no picture" answers of older # versions are then asked again instead of being trusted for MISS_TTL_S. -LOOKUP_VERSION = 3 +LOOKUP_VERSION = 4 MAX_BYTES = 512 * 1024 # one picture CACHE_MAX_BYTES = 20 * 1024 * 1024 # whole avatar cache on disk (least recently used go first) SESSION_MAX_LOOKUPS = 300 # network lookups per gitgraph run, however many authors a repo has @@ -181,6 +183,8 @@ def __init__(self, host: Dict[str, str], cache_dir: str, token: Optional[str] = self.max_cache_bytes = CACHE_MAX_BYTES self.max_lookups = SESSION_MAX_LOOKUPS self._net = threading.Semaphore(3) # be polite to the host + self._me: Optional[Tuple[frozenset, Optional[str]]] = None # token owner: (emails, avatar URL) + self._me_lock = threading.Lock() # ---- cache --------------------------------------------------------- def _key(self, email: str) -> str: @@ -386,7 +390,44 @@ def _pushed_commit(self, email: str) -> Optional[str]: sha = out.decode("ascii", "ignore").strip() return sha if gitdata.is_sha(sha) else None + def _gitlab_me(self) -> Tuple[frozenset, Optional[str]]: + """The token owner's verified emails and avatar URL (asked once per run).""" + with self._me_lock: + if self._me is not None: + return self._me + emails: set = set() + avatar = None + if self._host_token(): + try: + url = self.host["base"] + "/api/v4/user" + data, _, _ = self._request(url, dict({"Accept": "application/json"}, **self._auth(url)), + max_bytes=64 * 1024) + user = json.loads(data.decode("utf-8")) or {} + # email: the primary email, verified by GitLab; the others may be blank + emails.update(user.get(k) or "" for k in ("email", "commit_email", "public_email")) + avatar = user.get("avatar_url") or None + url = self.host["base"] + "/api/v4/user/emails" + data, _, _ = self._request(url, dict({"Accept": "application/json"}, **self._auth(url)), + max_bytes=64 * 1024) + extra = json.loads(data.decode("utf-8")) or [] + if isinstance(extra, list): + emails.update(e.get("email") or "" for e in extra + if isinstance(e, dict) and e.get("confirmed_at")) + except urllib.error.HTTPError as exc: + if exc.code == 401: + _debug("the GitLab token was rejected (expired?): continuing without it") + self._token = "" + else: + _debug("could not ask GitLab who the token belongs to (HTTP %s)" % exc.code) + except (urllib.error.URLError, OSError, ValueError, AttributeError) as exc: + _debug("could not ask GitLab who the token belongs to (%s)" % type(exc).__name__) + self._me = (frozenset(e.strip().lower() for e in emails if e and "@" in e), avatar) + return self._me + def _gitlab_avatar_url(self, email: str, sha: Optional[str] = None) -> Optional[str]: + my_emails, my_avatar = self._gitlab_me() + if email.lower() in my_emails: # you: no need to find a commit GitLab knows + return urllib.parse.urljoin(self.host["base"] + "/", my_avatar) if my_avatar else None shas = [] for candidate in (self._pushed_commit(email), sha): if candidate and candidate not in shas: diff --git a/tests/test_avatars.py b/tests/test_avatars.py index 73a7b4a..4e20ebe 100644 --- a/tests/test_avatars.py +++ b/tests/test_avatars.py @@ -61,6 +61,11 @@ def __call__(self, req, timeout=None): GITLAB = {"kind": "gitlab", "base": "https://gitlab.example.org", "path": "group/app"} +def lookups(web): + """The requests about authors (without the one-off "who owns the token" ones).""" + return [(u, h, b) for (u, h), b in zip(web.calls, web.bodies) if "/api/v4/user" not in u] + + def service(tmp_path, host, routes, **kw): web = FakeWeb(routes) return avatars.AvatarService(host, str(tmp_path), token=kw.pop("token", ""), opener=web, **kw), web @@ -153,9 +158,9 @@ def test_gitlab_finds_the_author_of_the_commit(tmp_path): "https://gitlab.example.org/uploads/": (png(), "image/png"), }, token="gl-t0ken") assert svc.get("private-commit-email@example.com", sha)[1] == "image/png" - query = json.loads(web.bodies[0].decode("utf-8")) + query = json.loads(lookups(web)[0][2].decode("utf-8")) assert query["variables"] == {"project": "group/app", "sha": sha} - assert [u for u, _ in web.calls] == [GRAPHQL, "https://gitlab.example.org/uploads/-/system/user/avatar/3/me.png"] + assert [u for u, _, _ in lookups(web)] == [GRAPHQL, "https://gitlab.example.org/uploads/-/system/user/avatar/3/me.png"] assert all(h.get("Authorization") == "Bearer gl-t0ken" for _, h in web.calls) # same server only @@ -186,10 +191,11 @@ def test_gitlab_rejected_token_is_dropped(tmp_path): "https://gitlab.example.org/api/v4/avatar": (json.dumps({"avatar_url": None}).encode(), "application/json"), }, token="expired") assert svc.get("hal@example.com", "2" * 40) is None - assert web.calls[0][1].get("Authorization") == "Bearer expired" - assert "Authorization" not in web.calls[1][1] # the email lookup ran without it + calls = lookups(web) + assert calls[0][1].get("Authorization") == "Bearer expired" + assert "Authorization" not in calls[1][1] # the email lookup ran without it assert svc.get("ida@example.com", "3" * 40) is None - assert "Authorization" not in web.calls[2][1] # and so does everything after + assert "Authorization" not in lookups(web)[2][1] # and so does everything after def test_gitlab_empty_commit_is_not_taken_for_another(tmp_path): @@ -257,6 +263,35 @@ def test_network_trouble_asks_again_later(tmp_path, monkeypatch): svc.get("lee@example.com") assert len(web.calls) > calls + +def test_gitlab_token_owner_gets_their_own_picture(tmp_path): + # e.g. your newest commits are not pushed yet: GitLab cannot name their author + svc, web = service(tmp_path, GITLAB, { + "https://gitlab.example.org/api/v4/user/emails": (json.dumps([ + {"email": "Me@Old-Job.example", "confirmed_at": "2020-01-01"}, + {"email": "unverified@example.com", "confirmed_at": None}]).encode(), "application/json"), + "https://gitlab.example.org/api/v4/user": (json.dumps({ + "email": "me@example.com", "commit_email": None, "public_email": "", + "avatar_url": "https://gitlab.example.org/uploads/-/system/user/avatar/1/me.png"}).encode(), + "application/json"), + "https://gitlab.example.org/uploads/": (png(), "image/png"), + GRAPHQL: lambda q: commit_answer("", project=False), + "https://gitlab.example.org/api/v4/avatar": (json.dumps({"avatar_url": None}).encode(), "application/json"), + }, token="gl-t0ken") + assert svc.get("ME@example.com", "6" * 40)[1] == "image/png" + assert svc.get("me@old-job.example", "7" * 40)[1] == "image/png" + assert not any(u == GRAPHQL for u, _ in web.calls) # no commit lookup needed for you + assert svc.get("unverified@example.com", "8" * 40) is None + assert sum(u.endswith("/api/v4/user") for u, _ in web.calls) == 1 # asked once + + +def test_gitlab_without_token_does_not_ask_who_you_are(tmp_path): + svc, web = service(tmp_path, GITLAB, { + GRAPHQL: lambda q: commit_answer(q["variables"]["sha"]), + }) + assert svc.get("me@example.com", "9" * 40) is None + assert not any("/api/v4/user" in u for u, _ in web.calls) + def test_gitlab_token_sources(tmp_path, monkeypatch): from conftest import make_program glab = make_program(tmp_path, "glab", ( @@ -377,11 +412,11 @@ def test_old_or_tokenless_misses_are_asked_again(tmp_path): assert svc.get("kim@example.com", sha) is None and len(web.calls) == 1 assert service(tmp_path, GITLAB, routes)[0].get("kim@example.com", sha) is None # trusted: still no token svc, web = service(tmp_path, GITLAB, routes, token="new-login") - assert svc.get("kim@example.com", sha) is None and len(web.calls) == 1 # made without a token: asked again + assert svc.get("kim@example.com", sha) is None and len(lookups(web)) == 1 # made without a token: asked again svc, web = service(tmp_path, GITLAB, routes, token="new-login") assert svc.get("kim@example.com", sha) is None and web.calls == [] # made with one: trusted meta = [n for n in os.listdir(svc.cache_dir) if n.endswith(".json")][0] with open(os.path.join(svc.cache_dir, meta), "w") as fh: json.dump({"t": time.time(), "type": ""}, fh) # a miss saved by gitgraph 1.1.0 or older svc, web = service(tmp_path, GITLAB, routes, token="new-login") - assert svc.get("kim@example.com", sha) is None and len(web.calls) == 1 + assert svc.get("kim@example.com", sha) is None and len(lookups(web)) == 1