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
6 changes: 4 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -152,15 +152,17 @@ authors' profile pictures. Nothing to configure:
`GH_TOKEN` or a logged-in `gh` CLI is already there, it is used, which also covers private
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. Public projects need
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
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
names the repository's server). Without one, GitLab's public lookup is used, which only
finds authors whose *public email* in their GitLab profile is the one they commit with.
Pictures that GitLab would take from Gravatar are ignored; only pictures uploaded to the
GitLab instance are shown.
- Other hosts, no picture, offline, rate limits: the coloured initials. No other service is
- Other hosts, no picture, offline, rate limits: the coloured initials (when the host could not
be reached, the page asks again a couple of minutes later). No other service is
ever contacted, and the page itself never talks to the internet (pictures go through the
local server).
- Pictures are cached for 7 days ("no picture" for 1 day, but asked again at once after you
Expand Down
10 changes: 10 additions & 0 deletions TESTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -165,6 +165,16 @@ Originally reported by the user on Windows (fixed on macOS, verified above):
before the login; those are now asked again (`avatars.LOOKUP_VERSION`, `auth` in the cache
metadata).

**Still initials with 1.1.1 (2026/11/27, fixed in 1.1.2):** the page asks once per author,
with the author's *newest* commit in the graph. That is often a local-only commit or merge
GitLab does not know, so GitLab answered nothing and only the public-email lookup was left.
A slow GraphQL answer (> 6 s; a cold first lookup measured 5 s) or a 5xx/429 was treated as
"offline": nothing cached, and the page never asked again. Now: the commit asked about is the
author's newest pushed non-merge commit (`git log --remotes --no-merges --author=<email>`,
~70 ms), then the shown one; GraphQL gets 15 s and any failure falls back to the email
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.

**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 <repo>…" in the app's colours and forwards with `location.replace` (meta
Expand Down
2 changes: 1 addition & 1 deletion src/gitgraph/__init__.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
"""gitgraph - interactive, GitLab-style commit graph for any git repository."""

__version__ = "1.1.1"
__version__ = "1.1.2"
75 changes: 54 additions & 21 deletions src/gitgraph/avatars.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,10 @@
* GitLab (gitlab.com or self-hosted): GitLab is asked who wrote the commit
(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). If
the project is not visible, the ``/api/v4/avatar`` lookup is used, which
only knows public profile emails. Gravatar answers are ignored: only
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
(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.

Nothing else is ever contacted: other hosts and failures (offline, private
Expand Down Expand Up @@ -42,11 +43,13 @@
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 = 2
LOOKUP_VERSION = 3
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
TIMEOUT_S = 6.0
GRAPHQL_TIMEOUT_S = 15.0 # GitLab resolves the commit through Gitaly: slower on big repositories
RETRY_S = 120.0 # after network trouble, ask again this much later (not remembered on disk)
IMAGE_TYPES = {"image/png", "image/jpeg", "image/gif", "image/webp"} # no SVG
_USER_AGENT = "gitgraph/%s (+https://github.com/edoardopanichi/gitgraph)" % __version__
_NOREPLY = re.compile(r"^(?:(\d+)\+)?([A-Za-z0-9-]+)@users\.noreply\.github\.com$", re.I)
Expand Down Expand Up @@ -159,10 +162,12 @@ class AvatarService:
"""Looks up and caches author pictures. Thread-safe; ``get`` may block on the network."""

def __init__(self, host: Dict[str, str], cache_dir: str, token: Optional[str] = None,
opener=None) -> None:
opener=None, repo: Optional[str] = None) -> None:
"""``token``: None finds one the user already has (env, gh/glab login) on first use;
"" means no token."""
"" means no token. ``repo``: the local repository, used to pick a pushed commit
of the author for GitLab."""
self.host = host
self.repo = repo
self.cache_dir = os.path.join(cache_dir, "avatars")
self._token = token
self._token_checked = token is not None
Expand Down Expand Up @@ -269,10 +274,10 @@ def prune(self) -> None:

# ---- network -------------------------------------------------------
def _request(self, url: str, headers: Optional[Dict[str, str]] = None, max_bytes: int = MAX_BYTES,
body: Optional[bytes] = None):
body: Optional[bytes] = None, timeout_s: float = TIMEOUT_S):
req = urllib.request.Request(url, data=body, headers=dict({"User-Agent": _USER_AGENT}, **(headers or {})))
with self._net:
with self._open(req, timeout=TIMEOUT_S) as res:
with self._open(req, timeout=timeout_s) as res:
data = res.read(max_bytes + 1)
if len(data) > max_bytes:
raise ValueError("response too large")
Expand Down Expand Up @@ -338,34 +343,56 @@ def _gitlab_commit_author(self, email: str, sha: str) -> Tuple[bool, Optional[st
"variables": {"project": self.host["path"], "sha": sha}}).encode("utf-8")
headers = dict({"Content-Type": "application/json", "Accept": "application/json"}, **self._auth(url))
try:
data, _, _ = self._request(url, headers, max_bytes=64 * 1024, body=body)
data, _, _ = self._request(url, headers, max_bytes=64 * 1024, body=body, timeout_s=GRAPHQL_TIMEOUT_S)
answer = json.loads(data.decode("utf-8")) or {}
except urllib.error.HTTPError as exc:
if exc.code == 401 and "Authorization" in headers:
_debug("the GitLab token was rejected (expired?): continuing without it")
self._token = ""
return False, None
if exc.code in (403, 404, 405): # GraphQL off or blocked: the email lookup may still work
_debug("GitLab GraphQL unavailable (HTTP %s)" % exc.code)
return False, None
raise
answer = json.loads(data.decode("utf-8")) or {}
else: # GraphQL off, blocked, overloaded...: the email lookup may still work
_debug("%s: GitLab GraphQL unavailable (HTTP %s)" % (email, exc.code))
return False, None
except (urllib.error.URLError, OSError, ValueError) as exc: # e.g. a slow server timing out
_debug("%s: GitLab GraphQL failed (%s: %s)" % (email, type(exc).__name__, exc))
return False, None
if not isinstance(answer, dict):
return False, None
project = (answer.get("data") or {}).get("project")
if not project:
_debug("%s: project %s not visible%s" % (
email, self.host["path"], "" if self._token else " (private? set GITLAB_TOKEN or run glab auth login)"))
return False, None
commit = ((project.get("repository") or {}).get("tree") or {}).get("lastCommit") or {}
same = commit.get("sha") == sha or (commit.get("authorEmail") or "").lower() == email.lower()
if not same: # e.g. an empty commit: GitLab names an earlier one
if not same: # unknown to GitLab (not pushed), or an empty commit: GitLab names another
_debug("%s: GitLab does not know commit %s" % (email, sha[:12]))
return False, None
avatar = (commit.get("author") or {}).get("avatarUrl")
if not avatar:
return True, None # GitLab knows no user with this email
return True, urllib.parse.urljoin(self.host["base"] + "/", avatar)

def _pushed_commit(self, email: str) -> Optional[str]:
"""The author's newest non-merge commit on a remote-tracking branch: one GitLab
knows (the commit shown may be local only) and that GitLab attributes to them."""
if not self.repo:
return None
try:
out = gitdata.run_git(self.repo, ["log", "--remotes", "--no-merges", "-1", "--format=%H",
"--fixed-strings", "--regexp-ignore-case",
"--author=<%s>" % email], timeout_s=10)
except (gitdata.GitError, OSError, subprocess.SubprocessError):
return None
sha = out.decode("ascii", "ignore").strip()
return sha if gitdata.is_sha(sha) else None

def _gitlab_avatar_url(self, email: str, sha: Optional[str] = None) -> Optional[str]:
if sha:
answered, avatar = self._gitlab_commit_author(email, sha)
shas = []
for candidate in (self._pushed_commit(email), sha):
if candidate and candidate not in shas:
shas.append(candidate)
for candidate in shas:
answered, avatar = self._gitlab_commit_author(email, candidate)
if answered:
return avatar
# only matches a user's public profile email
Expand All @@ -385,6 +412,12 @@ def _lookup(self, email: str, sha: Optional[str]) -> Optional[Tuple[bytes, str]]
return self._download_image(url) if url else None

# ---- public --------------------------------------------------------
def retry_after(self, email: str) -> float:
"""Seconds until ``email`` may be looked up again after network trouble (0: it was
a real answer, the picture or "no picture")."""
until = self._session_miss.get(self._key((email or "").strip()), 0.0)
return max(0.0, until - time.time())

def get(self, email: str, sha: Optional[str] = None) -> Optional[Tuple[bytes, str]]:
"""``(image bytes, content type)`` for the author, or None (show initials)."""
email = (email or "").strip()
Expand Down Expand Up @@ -415,15 +448,15 @@ def get(self, email: str, sha: Optional[str] = None) -> Optional[Tuple[bytes, st
_debug("%s: HTTP %s from %s" % (email, exc.code, exc.geturl() if hasattr(exc, "geturl") else "?"))
if exc.code == 404 and self.host["kind"] == "gitlab":
result = None # GitLab: no such user, a real answer
else: # rate limits, unpushed commits, private instance...: not an answer
self._session_miss[key] = time.time() + 600
else: # rate limits, private instance...: not an answer
self._session_miss[key] = time.time() + RETRY_S
return None
except _NoAnswer:
_debug("%s: not asked (no commit to look up, or rate limited)" % email)
return None
except (urllib.error.URLError, OSError, ValueError) as exc:
_debug("%s: %s: %s" % (email, type(exc).__name__, exc))
self._session_miss[key] = time.time() + 600 # offline or similar
self._session_miss[key] = time.time() + RETRY_S # offline or similar
return None
if not result:
_debug("%s: the host has no picture for this author" % email)
Expand Down
19 changes: 13 additions & 6 deletions src/gitgraph/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -230,7 +230,7 @@ def avatar_service(self):
from . import avatars
from .browser import cache_dir
host = avatars.detect_host(self.repo)
self._avatar_service = avatars.AvatarService(host, cache_dir()) if host else None
self._avatar_service = avatars.AvatarService(host, cache_dir(), repo=self.repo) if host else None
self._avatar_ready = True
return self._avatar_service

Expand Down Expand Up @@ -431,9 +431,12 @@ def log_message(self, fmt: str, *args: object) -> None: # noqa: D401 - stdlib s
super().log_message(fmt, *args)

# ---- helpers -------------------------------------------------------
def _headers(self, status: int, ctype: str, length: Optional[int] = None) -> None:
def _headers(self, status: int, ctype: str, length: Optional[int] = None,
extra: Optional[Dict[str, str]] = None) -> None:
self.send_response(status)
self.send_header("Content-Type", ctype)
for name, value in (extra or {}).items():
self.send_header(name, value)
if length is not None:
self.send_header("Content-Length", str(length))
self.send_header("Cache-Control", "no-store")
Expand All @@ -442,8 +445,8 @@ def _headers(self, status: int, ctype: str, length: Optional[int] = None) -> Non
self.send_header("Content-Security-Policy", CSP)
self.end_headers()

def _send(self, status: int, body: bytes, ctype: str) -> None:
self._headers(status, ctype, len(body))
def _send(self, status: int, body: bytes, ctype: str, extra: Optional[Dict[str, str]] = None) -> None:
self._headers(status, ctype, len(body), extra)
try:
self.wfile.write(body)
except ConnectionError: # broken pipe / reset / aborted (Windows)
Expand Down Expand Up @@ -591,8 +594,12 @@ def _avatar(self, q: Dict[str, List[str]]) -> None:
if sha is not None and not gitdata.is_sha(sha):
raise ValueError("bad commit id")
found = service.get(email, sha) if service is not None else None
if not found: # "no picture" is a normal answer, not an error (keeps consoles clean)
self._send(204, b"", "text/plain")
if not found:
retry_s = service.retry_after(email) if service is not None else 0.0
if retry_s > 0: # the host could not be asked right now: the page asks again later
self._send(503, b"", "text/plain", {"Retry-After": str(int(retry_s) + 1)})
return
self._send(204, b"", "text/plain") # "no picture" is a normal answer, not an error
return
data, ctype = found
self._send(200, data, ctype)
Expand Down
10 changes: 10 additions & 0 deletions src/gitgraph/web/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,7 @@
var avatarCache = new Map(); // lower-case email -> blob URL | null | 'pending'
var avatarQueue = [];
var avatarActive = 0;
var avatarTries = new Map(); // lower-case email -> lookups that the host could not answer
function avatarFor(email, sha) {
if (!S.meta || !S.meta.avatars || !email) return null;
var key = email.toLowerCase();
Expand All @@ -141,6 +142,15 @@
function fetchAvatar(email, sha) {
var key = email.toLowerCase();
fetch('api/avatar?email=' + encodeURIComponent(email) + (sha ? '&sha=' + sha : '')).then(function (res) {
if (res.status === 503) { // host not reachable right now: ask again later (a few times)
var tries = (avatarTries.get(key) || 0) + 1;
avatarTries.set(key, tries);
if (tries < 4) {
var wait_s = Math.min(600, Math.max(5, parseInt(res.headers.get('Retry-After'), 10) || 120));
setTimeout(function () { avatarCache.delete(key); invalidateRows(); schedule(); }, wait_s * 1000);
}
return null;
}
return res.status === 200 ? res.blob() : null; // 204: no picture
}).then(function (blob) {
avatarCache.set(key, blob ? URL.createObjectURL(blob) : null);
Expand Down
Loading
Loading