diff --git a/README.md b/README.md index 436edc7..d96d808 100644 --- a/README.md +++ b/README.md @@ -93,6 +93,14 @@ git clone https://github.com/boostjp/image.git boostjp/image これでローカルサーバが起動します。 http://localhost:8000 を開けば `index.html` が表示されます。 +## 編集者の GitHub アイコン表示 + +settings に `GITHUB_REPO` (例: `'cpprefjp/site'`) が設定されている場合、各ページの右上にそのページを編集した人の GitHub アイコンを表示します。 + +- コミットのメールアドレスから GitHub アカウント名への変換結果は `.github_users.cache` (例: `settings.cpprefjp.github_users.cache`) に JSON 形式でキャッシュされます。 +- 変換には GitHub API を使います。環境変数 `GITHUB_TOKEN` を設定しておくと、認証付きで問い合わせるためレート制限 (未認証だと 60 リクエスト/時) にかかりにくくなります。`./docker.sh run` は `GITHUB_TOKEN` をコンテナに引き継ぎます。トークンには公開リポジトリの読み取り権限があれば十分です。 +- レート制限などで変換できなかったメールアドレスは、次回実行時に再度問い合わせます。GitHub アカウントと紐付いていないメールアドレスはキャッシュに `null` として保存され、そのエントリを削除すると再度問い合わせます。 + ## コーディング規約(開発者向け) ルールは1つです。 diff --git a/contributors.py b/contributors.py new file mode 100644 index 0000000..d9d832d --- /dev/null +++ b/contributors.py @@ -0,0 +1,220 @@ +# -*- coding: utf-8 -*- + +"""ページの編集者 (コミットの author) を収集し、GitHub アカウントと紐付ける + +メールアドレスから GitHub アカウント名への変換は以下の順で行う。 + +1. `+@users.noreply.github.com` / `@users.noreply.github.com` + 形式のメールアドレスであれば、そこからアカウント名を取り出す。 +2. それ以外は GitHub API (GET /repos/{owner}/{repo}/commits/{sha}) で、 + そのメールアドレスで行われたコミットの `author.login` を取得する。 + メールアドレスを公開していないユーザーでも、GitHub アカウントに + メールアドレスを登録していれば取得できる。 + +結果はキャッシュファイル (JSON) に保存し、次回以降は API を呼ばない。 +GitHub アカウントと紐付いていないメールアドレスは null として保存する。 +null のエントリを削除すれば、次回の実行時に再度問い合わせる。 + +環境変数 GITHUB_TOKEN が設定されていれば API の認証に利用する。 +未設定の場合は未認証 (60 リクエスト/時) で問い合わせ、レート制限に +達したらそこで打ち切る (残りは次回以降の実行で解決される)。 +""" + +import json +import os +import re +import subprocess +import sys +import urllib.error +import urllib.request + + +_NOREPLY_RE = re.compile(r'^(?:\d+\+)?([^@+]+)@users\.noreply\.github\.com$', re.IGNORECASE) + + +def _warn(message): + print('contributors: {}'.format(message), file=sys.stderr) + + +def parse_noreply_email(email): + m = _NOREPLY_RE.match(email) + return m.group(1) if m else None + + +def is_bot_login(login): + return login is not None and login.endswith('[bot]') + + +def collect_page_authors(input_dir): + """input_dir 内の全 .md ファイルについて、編集したコミットの author を収集する + + git log を 1 回だけ実行して全ページ分を集計する。 + + 戻り値は (page_authors, email_to_sha) のタプル。 + page_authors は {ページのパス (拡張子なし): [author, ...]} で、 + author は {'name', 'email', 'commits', 'last_updated'} の辞書。 + リストは最後に編集した日時が新しい順に並ぶ。 + email_to_sha は {メールアドレス (小文字): そのメールアドレスによる最新コミットのハッシュ}。 + """ + output = subprocess.check_output( + ['git', 'log', '-z', '--no-renames', '--format=%x1e%H%x09%at%x09%aN%x09%aE', '--name-only', '--', '*.md'], + cwd=input_dir, text=True, errors='ignore') + + page_authors = {} + email_to_sha = {} + for record in output.split('\x1e'): + if not record: + continue + header, _, files = record.partition('\0') + fields = header.split('\t', 3) + if len(fields) != 4: + continue + sha, timestamp, name, email = fields + email = email.strip() + if not email: + continue + key = email.lower() + email_to_sha.setdefault(key, sha) + + for file in files.split('\0'): + file = file.strip('\n') + if not file.endswith('.md'): + continue + path = file[:-len('.md')] + # git log は新しいコミットから順に出力するので、 + # 最初に出てきたときの名前・日時がそのページでの最新のものになる + authors = page_authors.setdefault(path, {}) + if key in authors: + authors[key]['commits'] += 1 + else: + authors[key] = { + 'name': name, + 'email': email, + 'commits': 1, + 'last_updated': int(timestamp), + } + + # dict は挿入順を保持するので、そのまま最終編集日時の新しい順になっている + return {path: list(authors.values()) for path, authors in page_authors.items()}, email_to_sha + + +class GitHubUserResolver(object): + """メールアドレスから GitHub アカウント名を引く (結果はファイルにキャッシュする)""" + + API_URL_FORMAT = 'https://api.github.com/repos/{repo}/commits/{sha}' + + def __init__(self, cache_file, repo, token=None, timeout=10): + self._cache_file = cache_file + self._repo = repo + self._token = token + self._timeout = timeout + try: + with open(cache_file, encoding='utf-8') as f: + self._cache = json.load(f) + except FileNotFoundError: + self._cache = {} + except Exception as e: + _warn('failed to load {}: {}'.format(cache_file, e)) + self._cache = {} + + def get(self, email): + login = parse_noreply_email(email) + if login is not None: + return login + return self._cache.get(email.lower()) + + def resolve(self, email_to_sha): + """キャッシュに無いメールアドレスについて GitHub アカウント名を問い合わせる""" + targets = [(email, sha) for email, sha in email_to_sha.items() + if parse_noreply_email(email) is None and email not in self._cache] + if not targets: + return + + print('contributors: resolving {} email address(es) via GitHub API'.format(len(targets))) + resolved = 0 + for email, sha in targets: + ok, login = self._fetch_commit_author(sha) + if not ok: + break + self._cache[email] = login + resolved += 1 + + if resolved < len(targets): + _warn('{} email address(es) are left unresolved; they will be retried on the next run'.format(len(targets) - resolved)) + self._flush() + + def _fetch_commit_author(self, sha): + """コミットの author のアカウント名を取得する + + 戻り値は (処理を継続してよいか, アカウント名 or None)。 + """ + url = self.API_URL_FORMAT.format(repo=self._repo, sha=sha) + headers = { + 'Accept': 'application/vnd.github+json', + 'User-Agent': 'site_generator', + 'X-GitHub-Api-Version': '2022-11-28', + } + if self._token: + headers['Authorization'] = 'Bearer {}'.format(self._token) + + try: + with urllib.request.urlopen(urllib.request.Request(url, headers=headers), timeout=self._timeout) as res: + data = json.load(res) + except urllib.error.HTTPError as e: + if e.code in (403, 429): + _warn('GitHub API rate limit exceeded (HTTP {}). Set GITHUB_TOKEN to raise the limit.'.format(e.code)) + return False, None + # 404/422: コミットが GitHub 上に存在しない (push されていない等)。 + # キャッシュはせずに次へ進む。 + _warn('failed to fetch commit {} (HTTP {})'.format(sha, e.code)) + return True, None + except Exception as e: + _warn('failed to access GitHub API: {}'.format(e)) + return False, None + + author = data.get('author') + return True, (author or {}).get('login') + + def _flush(self): + tmp_file = self._cache_file + '.tmp' + with open(tmp_file, 'w', encoding='utf-8') as f: + json.dump(self._cache, f, ensure_ascii=False, indent=2, sort_keys=True) + f.write('\n') + os.replace(tmp_file, self._cache_file) + + +def make_page_contributors(authors, resolver): + """ページの author リストを、テンプレートで表示するための contributor リストに変換する + + 同じ GitHub アカウントに紐付く複数のメールアドレスは 1 人にまとめる。 + bot アカウントは除外する。 + """ + contributors = [] + by_login = {} + for author in authors: + login = resolver.get(author['email']) if resolver else None + if is_bot_login(login): + continue + if login is not None: + key = login.lower() + if key in by_login: + by_login[key]['commits'] += author['commits'] + continue + contributor = { + 'name': author['name'], + 'login': login, + 'url': 'https://github.com/{}'.format(login), + 'avatar_url': 'https://github.com/{}.png?size=40'.format(login), + 'commits': author['commits'], + } + by_login[key] = contributor + else: + contributor = { + 'name': author['name'], + 'login': None, + 'url': None, + 'avatar_url': None, + 'commits': author['commits'], + } + contributors.append(contributor) + return contributors diff --git a/cpprefjp/templates/content.html b/cpprefjp/templates/content.html index 19bf98a..d7ef03d 100644 --- a/cpprefjp/templates/content.html +++ b/cpprefjp/templates/content.html @@ -136,6 +136,26 @@ })(); {% endif %} + {% if contributors %} +

+ {% for contributor in contributors %} + {% if contributor.login %} + + + + {{ contributor.login|e }} + + {% else %} + + + + + {% endif %} + {% endfor %} +

+ {% endif %} {% endblock %} {% block mathjax %} diff --git a/docker.sh b/docker.sh index b6e230d..a305296 100755 --- a/docker.sh +++ b/docker.sh @@ -33,7 +33,7 @@ case "$1" in exit 1 fi shift 1 - docker run $DOCKER_RM -v `pwd`:/var/src cpprefjp/site_generator ./run.py "$@" ;; + docker run $DOCKER_RM -v `pwd`:/var/src -e GITHUB_TOKEN cpprefjp/site_generator ./run.py "$@" ;; "coding" ) docker run $DOCKER_RM -v `pwd`:/var/src cpprefjp/site_generator flake8 *.py markdown_to_html/*.py ;; "console" ) diff --git a/run.py b/run.py index 20d1698..69bb1a3 100755 --- a/run.py +++ b/run.py @@ -14,6 +14,8 @@ import atom +import contributors + import jinja2 import markdown @@ -30,6 +32,7 @@ settings = importlib.import_module(sys.argv[1]) CONVERT_ALL = '--all' in sys.argv[2:] CACHE_FILE = sys.argv[1] + '.cache' +GITHUB_USERS_CACHE_FILE = sys.argv[1] + '.github_users.cache' TARGET_PREFIX = [x[len('--prefix='):] for x in sys.argv[2:] if x.startswith('--prefix=')] TARGET_PREFIX = TARGET_PREFIX[0] if TARGET_PREFIX else '' CONCURRENCY = [int(x[len('--concurrency='):]) for x in sys.argv[2:] if x.startswith('--concurrency=')] @@ -531,7 +534,25 @@ def remove_not_target_paths(paths): pass -def convert_pageinfo(pageinfo, sidebar, sidebar_index, template, hrefs, global_qualify_list, global_defined_words, commit_info_dict): +def make_contributors_getter(): + """ページのパスから、そのページを編集した人のリストを返す関数を作る + + settings.GITHUB_REPO が設定されていない場合は常に空リストを返す。 + """ + repo = getattr(settings, 'GITHUB_REPO', None) + if not repo: + return lambda path: [] + + page_authors, email_to_sha = contributors.collect_page_authors(settings.INPUT_DIR) + resolver = contributors.GitHubUserResolver(GITHUB_USERS_CACHE_FILE, repo, os.environ.get('GITHUB_TOKEN')) + resolver.resolve(email_to_sha) + + def get_contributors(path): + return contributors.make_page_contributors(page_authors.get(path, []), resolver) + return get_contributors + + +def convert_pageinfo(pageinfo, sidebar, sidebar_index, template, hrefs, global_qualify_list, global_defined_words, commit_info_dict, get_contributors): path = pageinfo['path'] if path.count("/") <= 1: print(path) @@ -561,6 +582,7 @@ def convert_pageinfo(pageinfo, sidebar, sidebar_index, template, hrefs, global_q 'project_url': settings.PROJECT_URL, 'project_name': settings.PROJECT_NAME, 'latest_commit_info': latest_commit_info, + 'contributors': get_contributors(pageinfo['path']), 'keywords': settings.META_KEYWORDS, 'relative_base': '', 'relative_index': '/' @@ -601,6 +623,7 @@ def main(): global_defined_words = None cache = Cache(CACHE_FILE) + get_contributors = make_contributors_getter() env = jinja2.Environment(loader=jinja2.FileSystemLoader(settings.PAGE_TEMPLATE_DIR)) template = env.get_template('content.html') hrefs = {pageinfo['href'] for pageinfo in pageinfos} @@ -620,7 +643,7 @@ def main(): if settings.DISABLE_SIDEBAR: def run(pageinfos): for pageinfo in pageinfos: - convert_pageinfo(pageinfo, sidebar, sidebar_index, template, hrefs, global_qualify_list, global_defined_words, commit_info_dict) + convert_pageinfo(pageinfo, sidebar, sidebar_index, template, hrefs, global_qualify_list, global_defined_words, commit_info_dict, get_contributors) target_pageinfos_list = [[] for n in range(CONCURRENCY)] for i, pageinfo in enumerate(target_pageinfos): @@ -641,7 +664,7 @@ def run(pageinfos): else: # サイドバーを出力する場合は sidebar への書き込みが発生して怖いので普通に出力する for pageinfo in target_pageinfos: - convert_pageinfo(pageinfo, sidebar, sidebar_index, template, hrefs, global_qualify_list, global_defined_words, commit_info_dict) + convert_pageinfo(pageinfo, sidebar, sidebar_index, template, hrefs, global_qualify_list, global_defined_words, commit_info_dict, get_contributors) for pageinfo in pageinfos: cache.converted(pageinfo['path']) diff --git a/settings/cpprefjp.py b/settings/cpprefjp.py index ee73458..51ee4bf 100644 --- a/settings/cpprefjp.py +++ b/settings/cpprefjp.py @@ -24,6 +24,10 @@ PROJECT_URL = 'https://github.com/cpprefjp/site' PROJECT_NAME = 'GitHub Project' +# 入力ディレクトリの GitHub リポジトリ (owner/repo) +# 設定すると、各ページに編集者の GitHub アイコンを表示する +GITHUB_REPO = 'cpprefjp/site' + # ブランド名 BRAND = 'cpprefjp - C++日本語リファレンス'