Skip to content
Open
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: 9 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,15 @@ git clone https://github.com/boostjp/image.git boostjp/image
これでローカルサーバが起動します。
http://localhost:8000 を開けば `index.html` が表示されます。

## 編集者の GitHub アイコン表示

settings に `GITHUB_REPO` (例: `'cpprefjp/site'`) が設定されている場合、各ページの右上にそのページを編集した人の GitHub アイコンを表示します。

- コミットのメールアドレスから GitHub アカウント名への変換結果は `<setting>.github_users.cache` (例: `settings.cpprefjp.github_users.cache`) に JSON 形式でキャッシュされます。
- 変換には GitHub API を使います。環境変数 `GITHUB_TOKEN` を設定しておくと、認証付きで問い合わせるためレート制限 (未認証だと 60 リクエスト/時) にかかりにくくなります。`./docker.sh run` は `GITHUB_TOKEN` をコンテナに引き継ぎます。トークンには公開リポジトリの読み取り権限があれば十分です。
- レート制限などで変換できなかったメールアドレスは、次回実行時に再度問い合わせます。GitHub アカウントと紐付いていないメールアドレスはキャッシュに `null` として保存され、そのエントリを削除すると再度問い合わせます。
- GitHub アカウントと紐付かないメールアドレスでも、同じ author 名で別のメールアドレスが GitHub アカウントに紐付いていれば、そのアカウントの人として扱います (同じ author 名が複数のアカウントに紐付く場合を除く)。

## コーディング規約(開発者向け)

ルールは1つです。
Expand Down
269 changes: 269 additions & 0 deletions contributors.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,269 @@
# -*- coding: utf-8 -*-

"""ページの編集者 (コミットの author) を収集し、GitHub アカウントと紐付ける

メールアドレスから GitHub アカウント名への変換は以下の順で行う。

1. `<id>+<login>@users.noreply.github.com` / `<login>@users.noreply.github.com`
形式のメールアドレスであれば、そこからアカウント名を取り出す。
2. それ以外は GitHub API (GET /repos/{owner}/{repo}/commits/{sha}) で、
そのメールアドレスで行われたコミットの `author.login` を取得する。
メールアドレスを公開していないユーザーでも、GitHub アカウントに
メールアドレスを登録していれば取得できる。

3. 上記で GitHub アカウントと紐付かなかったメールアドレスは、同じ author 名で
別のメールアドレスが紐付いていれば、そのアカウントとみなす
(author 名が複数のアカウントに紐付く場合は曖昧なので行わない)。

結果はキャッシュファイル (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 normalize_name(name):
"""author 名の比較用キー (前後の空白・連続する空白・大文字小文字の違いを無視する)"""
return ' '.join(name.split()).casefold()


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 = {}
self._name_to_login = {}

def _get_by_email(self, email):
login = parse_noreply_email(email)
if login is not None:
return login
return self._cache.get(email.lower())

def get(self, email, name=None):
"""メールアドレスから GitHub アカウント名を返す

メールアドレスで紐付かない場合は、name (author 名) で紐付いている
アカウント名を返す (build_name_index() を呼んでおく必要がある)。
"""
login = self._get_by_email(email)
if login is None and name:
login = self._name_to_login.get(normalize_name(name))
return login

def build_name_index(self, page_authors):
"""author 名から GitHub アカウント名への対応表を作る

page_authors は collect_page_authors() の戻り値の 1 つ目。
1 つの author 名が複数のアカウントに紐付く場合 (同姓同名の別人など) は
曖昧なので対応表に入れない。
"""
candidates = {}
for authors in page_authors.values():
for author in authors:
login = self._get_by_email(author['email'])
if login is None:
continue
key = normalize_name(author['name'])
if key:
candidates.setdefault(key, set()).add(login.lower())
self._name_to_login.setdefault(key, login)
for key, logins in candidates.items():
if len(logins) > 1:
del self._name_to_login[key]

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 人にまとめる。
GitHub アカウントに紐付かない人は、author 名が同じであれば 1 人にまとめる。
bot アカウントは除外する。
"""
contributors = []
by_login = {}
by_name = {}
for author in authors:
login = resolver.get(author['email'], author['name']) 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:
key = normalize_name(author['name'])
if key in by_name:
by_name[key]['commits'] += author['commits']
continue
contributor = {
'name': author['name'],
'login': None,
'url': None,
'avatar_url': None,
'commits': author['commits'],
}
by_name[key] = contributor
contributors.append(contributor)
return contributors
79 changes: 79 additions & 0 deletions cpprefjp/templates/content.html
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,85 @@
})();
</script>
{% endif %}
{% if contributors %}
<style>
.contributors .contributor-icon {
display: inline-block; width: 20px; height: 20px; line-height: 20px; border-radius: 50%;
box-shadow: 0 0 0 1px #1f232826; vertical-align: middle; margin-left: 3px;
text-align: center; color: #999; background: #eee;
}
.contributors .contributors-more {
display: inline-block; min-width: 20px; height: 20px; line-height: 20px; padding: 0 5px; border: 0; border-radius: 10px;
box-shadow: 0 0 0 1px #1f232826; vertical-align: middle; margin-left: 3px;
font-size: 11px; color: #555; background: #eee; cursor: pointer;
}
/* kunai の CSS では .edit-button .text-right が inline-flex になり、アイコンが縮んで
1 行に詰め込まれてしまうので、.text-right は使わずに幅いっぱいのブロックとして表示する */
.contributors { text-align: right; align-self: stretch; }
.contributors.is-collapsed { white-space: nowrap; overflow: hidden; }
</style>
<p class="contributors">
{% for contributor in contributors %}
{% if contributor.login %}
<a class="contributor" href="{{ contributor.url|e }}" target="_blank" title="{{ contributor.login|e }} ({{ contributor.commits }} コミット)" itemprop="contributor" itemscope itemtype="http://schema.org/Person"
><meta itemprop="name" content="{{ contributor.name|e }}" /><link itemprop="url" href="{{ contributor.url|e }}" /><img class="contributor-icon" src="{{ contributor.avatar_url|e }}" alt="{{ contributor.login|e }}" width="20" height="20" loading="lazy"></a>
{% else %}
<span class="contributor contributor-icon" title="{{ contributor.name|e }} ({{ contributor.commits }} コミット)" itemprop="contributor" itemscope itemtype="http://schema.org/Person"
><meta itemprop="name" content="{{ contributor.name|e }}" /><span class="fa fa-user"></span></span>
{% endif %}
{% endfor %}
<button type="button" class="contributors-more" style="display: none;"></button>
</p>
<script>
(function () {
// 編集者アイコンを画面幅に収まる人数だけ (最終編集日時が新しい順に) 1 行で表示し、
// 収まらない分は「+N」にまとめる。「+N」を押すと全員を表示する。
// JS が無効な環境では全員を折り返して表示する。
var rows = document.querySelectorAll('.contributors');
var row = rows[rows.length - 1];
var items = row.querySelectorAll('.contributor');
var more = row.querySelector('.contributors-more');
var expanded = false;

// 先頭から count 人を表示し、残りを「+N」にまとめたときに 1 行に収まるか
function fits(count) {
for (var i = 0; i < items.length; i++) { items[i].style.display = i < count ? '' : 'none'; }
more.textContent = '+' + (items.length - count);
more.title = '他 ' + (items.length - count) + ' 人を表示';
more.style.display = count < items.length ? '' : 'none';
return row.scrollWidth <= row.clientWidth;
}

function layout() {
if (expanded) { return; }
row.classList.add('is-collapsed');
if (fits(items.length)) { return; }
// 収まる最大の人数を二分探索する
var lo = 0, hi = items.length - 1;
while (lo < hi) {
var mid = Math.ceil((lo + hi) / 2);
if (fits(mid)) { lo = mid; } else { hi = mid - 1; }
}
fits(lo);
}

more.addEventListener('click', function () {
expanded = true;
row.classList.remove('is-collapsed');
more.style.display = 'none';
for (var i = 0; i < items.length; i++) { items[i].style.display = ''; }
});

var scheduled = false;
window.addEventListener('resize', function () {
if (scheduled) { return; }
scheduled = true;
window.requestAnimationFrame(function () { scheduled = false; layout(); });
});
layout();
})();
</script>
{% endif %}
{% endblock %}

{% block mathjax %}
Expand Down
2 changes: 1 addition & 1 deletion docker.sh
Original file line number Diff line number Diff line change
Expand Up @@ -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" )
Expand Down
Loading
Loading