|
| 1 | +import { execSync } from "child_process"; |
| 2 | + |
| 3 | +export interface CommitterInfo { |
| 4 | + name: string; |
| 5 | + href: string; |
| 6 | +} |
| 7 | + |
| 8 | +export interface CommitInfo { |
| 9 | + hash: string; |
| 10 | + committer: CommitterInfo; |
| 11 | +} |
| 12 | + |
| 13 | +const token = process.env.GITHUB_TOKEN; |
| 14 | + |
| 15 | +const options: RequestInit = token |
| 16 | + ? { |
| 17 | + headers: { |
| 18 | + Accept: "application/vnd.github+json", |
| 19 | + "User-Agent": "papermc-docs/author", |
| 20 | + Authorization: `Bearer ${token}`, |
| 21 | + }, |
| 22 | + } |
| 23 | + : { |
| 24 | + headers: { |
| 25 | + Accept: "application/vnd.github+json", |
| 26 | + "User-Agent": "papermc-docs/author", |
| 27 | + }, |
| 28 | + }; |
| 29 | + |
| 30 | +export const REPO = "PaperMC/docs"; |
| 31 | +const cache = new Map<string, CommitterInfo>(); |
| 32 | + |
| 33 | +export const getCommitInfo = async (filePath: string): Promise<CommitInfo | null> => { |
| 34 | + let email: string, hash: string; |
| 35 | + try { |
| 36 | + email = execSync(`git log -1 --pretty="format:%ae" -- "${filePath}"`).toString(); |
| 37 | + hash = execSync(`git log -1 --pretty="format:%H" -- "${filePath}"`).toString(); |
| 38 | + } catch (e) { |
| 39 | + return null; |
| 40 | + } |
| 41 | + |
| 42 | + const cached = cache.get(email); |
| 43 | + if (cached) { |
| 44 | + return { hash, committer: cached }; |
| 45 | + } |
| 46 | + |
| 47 | + let name: string; |
| 48 | + try { |
| 49 | + name = execSync(`git log -1 --pretty="format:%an" -- "${filePath}"`).toString(); |
| 50 | + } catch (e) { |
| 51 | + return null; |
| 52 | + } |
| 53 | + |
| 54 | + const info: CommitterInfo = { name, href: `mailto:${email}` }; |
| 55 | + |
| 56 | + const res = await fetch(`https://api.github.com/repos/${REPO}/commits/${hash}`, options); |
| 57 | + if (res.ok) { |
| 58 | + const commit = await res.json(); |
| 59 | + info.href = commit.author.html_url; |
| 60 | + } |
| 61 | + |
| 62 | + cache.set(email, info); |
| 63 | + return { hash, committer: info }; |
| 64 | +}; |
0 commit comments