-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgenerate_readme.py
More file actions
200 lines (167 loc) · 6.6 KB
/
Copy pathgenerate_readme.py
File metadata and controls
200 lines (167 loc) · 6.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
#!/usr/bin/env -S uv run
# /// script
# requires-python = ">=3.11"
# dependencies = [
# "pyyaml>=6",
# "requests>=2.31",
# ]
# ///
"""Generate the mithro profile README.md from the mith.ro site data.
The https://mith.ro front page is a Jekyll site whose content is driven by
the ``_data/*.yaml`` files in https://github.com/mithro/mithro.github.io.
This script fetches those same source-of-truth files (not the rendered
HTML) and renders README.md, so the profile shows exactly the numbers and
content the site does.
Run from the repository root: uv run scripts/generate_readme.py
"""
import datetime
import html
import pathlib
import re
import sys
import requests
import yaml
SITE = "https://mith.ro"
RAW = "https://raw.githubusercontent.com/mithro/mithro.github.io/master"
README = pathlib.Path(__file__).resolve().parent.parent / "README.md"
RECENT_TALKS = 5
POPULAR_REPOS = 6
def fetch(path: str) -> str:
url = f"{RAW}/{path}"
resp = requests.get(url, timeout=30)
resp.raise_for_status()
return resp.text
def fetch_yaml(name: str):
return yaml.safe_load(fetch(f"_data/{name}.yaml"))
def extract_bio(index_html: str) -> str:
"""Pull the hero bio paragraph out of the site's index.html."""
match = re.search(r'<p class="bio">(.*?)</p>', index_html, re.DOTALL)
if not match:
raise SystemExit("Could not find the bio paragraph in index.html")
bio = html.unescape(re.sub(r"<[^>]+>", "", match.group(1)))
return re.sub(r"\s+", " ", bio).strip()
def md_escape(text: str) -> str:
"""Make arbitrary text safe inside a Markdown table cell."""
return re.sub(r"\s+", " ", str(text)).replace("|", "\\|").strip()
def talk_cell(talk: dict) -> str:
title = md_escape(talk["title"])
slides = talk.get("slides_short") or talk.get("slides")
cell = f"[{title}]({slides})" if slides else title
if talk.get("video"):
cell += f" ([▶ video]({talk['video']}))"
return cell
def render(data: dict) -> str:
contact = data["contact"]
github = data["github"]
talks = data["talks"]
interviews = data["interviews"]
papers = data["papers"]
projects = data["projects"]
bio = data["bio"]
profile = github["profile"]
today = datetime.datetime.now(datetime.timezone.utc).date().isoformat()
lines: list[str] = []
out = lines.append
# Hero -----------------------------------------------------------------
out("# Tim 'mithro' Ansell")
out("")
out(bio.replace("wafer.space.", "[wafer.space](https://wafer.space)."))
out("")
links = " · ".join(
f"[{link['label']}]({link['url']})" for link in contact["links"]
)
out(f"🌐 **[mith.ro]({SITE})** · {links} · 📧 {contact['email']}")
out("")
# Stat counters (mirrors the six counters on the mith.ro front page) ---
stats = [
("🎤 Talks", len(talks), f"{SITE}/talks/"),
("🎙️ Interviews", len(interviews), f"{SITE}/interviews/"),
("📄 Papers", len(papers["papers"]), f"{SITE}/papers/"),
("🎓 Citations", papers["metrics"]["citations"],
papers["metrics"]["profile"]),
("🐙 Repos", profile["public_repos"],
f"{profile['url']}?tab=repositories"),
("👥 Followers", profile["followers"],
f"{profile['url']}?tab=followers"),
]
out("| " + " | ".join(label for label, _, _ in stats) + " |")
out("|" + "---:|" * len(stats))
out("| " + " | ".join(f"[{n}]({url})" for _, n, url in stats) + " |")
out("")
# Projects -------------------------------------------------------------
out(f"## 🔭 What I'm working on")
out("")
for proj in projects:
if proj.get("status") != "active":
continue
blurb = re.sub(r"\s+", " ", proj["blurb"]).strip()
out(f"- **[{proj['name']}]({proj['url']})** — {proj['role']}, "
f"{proj['years']}. {blurb}")
out("")
out(f"Earlier projects — TimVideos/HDMI2USB, F4PGA (SymbiFlow), LiteX, "
f"Tomu/Fomu and more — are on the [projects page]({SITE}/projects/).")
out("")
# Recent talks ---------------------------------------------------------
out("## 🎤 Recent talks")
out("")
out("| Year | Talk | Event |")
out("|---|---|---|")
recent = sorted(talks, key=lambda t: str(t.get("sort_date", "")),
reverse=True)[:RECENT_TALKS]
for talk in recent:
event = md_escape(talk["event"])
if talk.get("event_url"):
event = f"[{event}]({talk['event_url']})"
out(f"| {talk['year']} | {talk_cell(talk)} | {event} |")
out("")
out(f"[All {len(talks)} talks →]({SITE}/talks/)")
out("")
# GitHub extras --------------------------------------------------------
out("## 🐙 On GitHub")
out("")
out(f"On GitHub [since {profile['member_since']}]({profile['url']}), "
f"with {profile['public_repos']} public repositories. Some popular "
f"ones under my own account:")
out("")
out("| Repository | ⭐ | About |")
out("|---|---:|---|")
for repo in github["top_repos"][:POPULAR_REPOS]:
out(f"| [{repo['name']}]({repo['url']}) | {repo['stars']} "
f"| {md_escape(repo.get('description') or '')} |")
out("")
orgs = ", ".join(
f"[{org}](https://github.com/{org})" for org in github["orgs"]
)
out(f"Most of my open source work lives in shared organisations: {orgs}.")
out("")
# Footer ---------------------------------------------------------------
out("---")
out("")
out(f"<sub>Generated from the [mith.ro]({SITE}) site data by "
f"[`scripts/generate_readme.py`](scripts/generate_readme.py) "
f"([workflow](.github/workflows/update-readme.yml)) · "
f"last updated {today}.</sub>")
out("")
return "\n".join(lines)
def main() -> None:
data = {
"contact": fetch_yaml("contact"),
"github": fetch_yaml("github"),
"talks": fetch_yaml("talks"),
"interviews": fetch_yaml("interviews"),
"papers": fetch_yaml("papers"),
"projects": fetch_yaml("projects"),
"bio": extract_bio(fetch("index.html")),
}
rendered = render(data)
old = README.read_text() if README.exists() else None
# The footer date alone doesn't count as a change — otherwise the
# daily workflow would commit a new README every single day.
date_re = re.compile(r"last updated \d{4}-\d{2}-\d{2}")
if old is not None and date_re.sub("", rendered) == date_re.sub("", old):
print("README.md unchanged", file=sys.stderr)
return
README.write_text(rendered)
print(f"Wrote {README}", file=sys.stderr)
if __name__ == "__main__":
main()