23-11-2026
319 lines
10 kB
1mod html;
2mod markdown;
3mod repo_info;
4
5use anyhow::{Context, Result, bail};
6use html::{
7 ARCHIVE_FORMATS, COMMITS_PER_PAGE, commits_page, diff_stat, gen_blob, gen_branches, gen_commit,
8 gen_commits, gen_index, gen_releases, gen_summary, gen_tags, gen_tree,
9};
10use repo_info::{CommitInfo, RepoInfo, archive_name};
11use sha2::{Digest, Sha256};
12use std::{
13 collections::HashMap,
14 env,
15 fs::{self, File},
16 io::{ErrorKind, Read},
17 iter,
18 path::{Path, PathBuf},
19 process,
20};
21
22const USAGE: &str = "usage: wit [-O owner] [-u repo.git] -o outdir repo.git...";
23
24struct Args {
25 owner: Option<String>,
26 out_dir: PathBuf,
27 update: Option<String>,
28 repos: Vec<String>,
29}
30
31fn main() {
32 if let Err(e) = run() {
33 eprintln!("{e:#}");
34 process::exit(1);
35 }
36}
37
38fn parse_args() -> Result<Args> {
39 let mut owner = None;
40 let mut out_dir = None;
41 let mut update = None;
42 let mut repos = Vec::new();
43 let mut args = env::args().skip(1);
44 while let Some(arg) = args.next() {
45 match arg.as_str() {
46 "-O" => owner = Some(args.next().context(USAGE)?),
47 "-o" => out_dir = Some(PathBuf::from(args.next().context(USAGE)?)),
48 "-u" => update = Some(args.next().context(USAGE)?),
49 s if s.starts_with('-') => bail!(USAGE),
50 _ => repos.push(arg),
51 }
52 }
53 let out_dir = out_dir.context(USAGE)?;
54 if repos.is_empty() {
55 bail!(USAGE);
56 }
57 Ok(Args {
58 owner,
59 out_dir,
60 update,
61 repos,
62 })
63}
64
65fn write_file(path: &Path, contents: &str) -> Result<()> {
66 let dir = path.parent().unwrap_or(Path::new(""));
67 fs::create_dir_all(dir)
68 .and_then(|()| fs::write(path, contents))
69 .with_context(|| path.display().to_string())
70}
71
72fn link_file(from: &Path, to: &Path) -> Result<()> {
73 let dir = to.parent().unwrap_or(Path::new(""));
74 fs::create_dir_all(dir)
75 .and_then(|()| fs::hard_link(from, to).or_else(|_| fs::copy(from, to).map(drop)))
76 .with_context(|| to.display().to_string())
77}
78
79fn write_archive(repo: &RepoInfo, tag: &str, format: &str, to: &Path) -> Result<()> {
80 let dir = to.parent().unwrap_or(Path::new(""));
81 fs::create_dir_all(dir).with_context(|| dir.display().to_string())?;
82 let output = process::Command::new("git")
83 .arg("--git-dir")
84 .arg(repo.git.path())
85 .arg("archive")
86 .arg(format!("--format={format}"))
87 .arg(format!("--prefix={}/", archive_name(&repo.name, tag)))
88 .arg("-o")
89 .arg(to)
90 .arg(format!("refs/tags/{tag}"))
91 .output()
92 .with_context(|| format!("git archive {tag}"))?;
93 if !output.status.success() {
94 let error = String::from_utf8_lossy(&output.stderr);
95 bail!("git archive {tag}: {}", error.trim());
96 }
97 Ok(())
98}
99
100fn file_sum(path: &Path) -> Result<(usize, String)> {
101 let mut file = File::open(path).with_context(|| path.display().to_string())?;
102 let mut hasher = Sha256::new();
103 let mut buf = vec![0; 1 << 16];
104 let mut bytes = 0;
105 loop {
106 let n = file
107 .read(&mut buf)
108 .with_context(|| path.display().to_string())?;
109 if n == 0 {
110 break;
111 }
112 hasher.update(&buf[..n]);
113 bytes += n;
114 }
115 let sha256 = hasher
116 .finalize()
117 .iter()
118 .map(|b| format!("{b:02x}"))
119 .collect();
120 Ok((bytes, sha256))
121}
122
123fn last_changes<'a>(
124 commits: &'a [CommitInfo],
125 changes: &HashMap<String, Vec<String>>,
126) -> HashMap<String, &'a CommitInfo> {
127 let mut last = HashMap::new();
128 for commit in commits {
129 for path in changes.get(&commit.id).into_iter().flatten() {
130 let mut path = path.as_str();
131 loop {
132 let newest = last.entry(path.to_string()).or_insert(commit);
133 if commit.committer_date > newest.committer_date {
134 *newest = commit;
135 }
136 match path.rsplit_once('/') {
137 Some((dir, _)) => path = dir,
138 None => break,
139 }
140 }
141 }
142 }
143 last
144}
145
146fn page_clash(repo: &RepoInfo) -> Option<String> {
147 if let Some(release) = repo
148 .releases
149 .iter()
150 .find(|r| r.tag.split('/').next() == Some("index.html"))
151 {
152 return Some(format!("release {} clashes with a page", release.tag));
153 }
154 repo.branches.iter().chain(&repo.tags).find_map(|git_ref| {
155 let path = git_ref
156 .dirs
157 .keys()
158 .find(|path| path.rsplit('/').next() == Some("index.html"))?;
159 Some(format!("dir {path} in {} clashes with a page", git_ref.dir))
160 })
161}
162
163fn run() -> Result<()> {
164 let args = parse_args()?;
165 let update = args
166 .update
167 .as_ref()
168 .map(|path| fs::canonicalize(path).with_context(|| path.clone()))
169 .transpose()?;
170 let is_update = |path: &str| fs::canonicalize(path).ok() == update;
171 if let Some(path) = &args.update
172 && !args.repos.iter().any(|repo| is_update(repo))
173 {
174 bail!("-u {path}: not one of the repos");
175 }
176 let mut repos: Vec<RepoInfo> = Vec::new();
177 for path in &args.repos {
178 let repo = RepoInfo::open(path, args.owner.as_deref()).with_context(|| path.clone())?;
179 let repo = match repo {
180 Ok(repo) => repo,
181 Err(reason) => {
182 eprintln!("{path}: {reason}, skipped");
183 continue;
184 }
185 };
186 if let Some(clash) = page_clash(&repo) {
187 eprintln!("{path}: {clash}, skipped");
188 continue;
189 }
190 if let Some(first) = repos.iter().find(|r| r.name == repo.name) {
191 bail!(
192 "{} and {} are both named {}",
193 first.path,
194 repo.path,
195 repo.name
196 );
197 }
198 repos.push(repo);
199 }
200 write_file(&args.out_dir.join("index.html"), &gen_index(&repos))?;
201 for repo in &repos {
202 let repo_dir = args.out_dir.join(&repo.name);
203 if update.is_some() && !is_update(&repo.path) && repo_dir.exists() {
204 continue;
205 }
206 write_repo(repo, &repo_dir).with_context(|| repo.path.clone())?;
207 }
208 Ok(())
209}
210
211fn write_repo(repo: &RepoInfo, repo_dir: &Path) -> Result<()> {
212 if let Err(e) = fs::remove_dir_all(repo_dir)
213 && e.kind() != ErrorKind::NotFound
214 {
215 return Err(e).with_context(|| repo_dir.display().to_string());
216 }
217 let mut sums = Vec::new();
218 for release in &repo.releases {
219 let release_dir = repo_dir.join("releases").join(&release.tag);
220 let mut release_sums = Vec::new();
221 for name in &release.files {
222 let to = release_dir.join(name);
223 link_file(&release.dir.join(name), &to)?;
224 release_sums.push(file_sum(&to)?);
225 }
226 for format in ARCHIVE_FORMATS {
227 let to = repo_dir
228 .join("archive")
229 .join(format!("{}.{format}", release.tag));
230 write_archive(repo, &release.tag, format, &to)?;
231 release_sums.push(file_sum(&to)?);
232 }
233 sums.push(release_sums);
234 }
235 if !repo.releases.is_empty() {
236 write_file(
237 &repo_dir.join("releases").join("index.html"),
238 &gen_releases(repo, &sums),
239 )?;
240 }
241 let refs = || repo.branches.iter().chain(&repo.tags);
242 let head_first = refs()
243 .filter(|r| r.dir == repo.head_dir)
244 .chain(refs().filter(|r| r.dir != repo.head_dir));
245 let mut stats = HashMap::new();
246 let mut changes = HashMap::new();
247 let mut counts = HashMap::new();
248 let mut rev = repo.git.revwalk()?;
249 for git_ref in head_first {
250 let commits = repo.read_commits(&mut rev, &git_ref.id)?;
251 counts.insert(git_ref.dir.clone(), commits.len());
252 for commit in &commits {
253 if stats.contains_key(&commit.id) {
254 continue;
255 }
256 let diff = repo.read_diff(&commit.id)?;
257 write_file(
258 &repo_dir.join("commits").join(&commit.id).join("index.html"),
259 &gen_commit(repo, git_ref, commit, &diff, commits.len()),
260 )?;
261 stats.insert(commit.id.clone(), diff_stat(&diff));
262 if diff.parents.len() < 2 {
263 let paths: Vec<String> = diff
264 .files
265 .iter()
266 .flat_map(|f| iter::once(&f.path).chain(&f.old_path))
267 .cloned()
268 .collect();
269 changes.insert(commit.id.clone(), paths);
270 }
271 }
272 let last = last_changes(&commits, &changes);
273 let commits_dir = repo_dir.join("commits").join(&git_ref.dir);
274 for page in 1..=commits.len().div_ceil(COMMITS_PER_PAGE) {
275 write_file(
276 &commits_dir.join(commits_page(page)),
277 &gen_commits(repo, git_ref, &commits, &stats, page),
278 )?;
279 }
280 for dir in git_ref.dirs.values() {
281 let tree_dir = repo_dir.join("tree").join(&git_ref.dir).join(&dir.path);
282 write_file(
283 &tree_dir.join("index.html"),
284 &gen_tree(repo, git_ref, dir, &last, commits.len()),
285 )?;
286 let blob_dir = repo_dir.join("blob").join(&git_ref.dir).join(&dir.path);
287 for entry in &dir.entries {
288 let Some(id) = entry.blob else {
289 continue;
290 };
291 let blob = repo.git.find_blob(id)?;
292 write_file(
293 &blob_dir.join(&entry.name).join("index.html"),
294 &gen_blob(
295 repo,
296 git_ref,
297 dir,
298 entry,
299 blob.content(),
300 &last,
301 commits.len(),
302 ),
303 )?;
304 }
305 }
306 }
307 write_file(
308 &repo_dir.join("branches").join("index.html"),
309 &gen_branches(repo, &counts),
310 )?;
311 if !repo.tags.is_empty() {
312 write_file(
313 &repo_dir.join("tags").join("index.html"),
314 &gen_tags(repo, &counts),
315 )?;
316 }
317 let head_last = last_changes(&repo.commit_list, &changes);
318 write_file(&repo_dir.join("index.html"), &gen_summary(repo, &head_last))
319}