1954 lines
63 kB
1use crate::markdown::{is_markdown, write_markdown};
2use crate::repo_info::{
3 CommitDiff, CommitInfo, Dir, FileChange, Line, RefInfo, RepoInfo, TreeEntry, archive_name,
4 join_path,
5};
6
7use chrono::{DateTime, FixedOffset};
8use std::{
9 cmp::Reverse,
10 collections::{HashMap, HashSet},
11 fmt::Write,
12};
13
14const BRAND: &str = "wit";
15
16const CLONE_URL_BASE: &str = "https://git.paramogi.world/";
17
18const NO_DESCRIPTION: &str = "[no description]";
19
20const BRIEF_COUNT: usize = 5;
21
22const DATE: &str = "%d-%m-%Y";
23
24pub const COMMITS_PER_PAGE: usize = 200;
25
26const SUMMARY_REF_COUNT: usize = 3;
27
28const BYTE_UNITS: [&str; 5] = ["B", "kB", "MB", "GB", "TB"];
29
30const README_NAMES: [&str; 2] = ["README.md", "README"];
31
32const MARKDOWN_BOX: &str = "box markdown-body";
33
34pub const ARCHIVE_FORMATS: [&str; 2] = ["zip", "tar.gz"];
35
36const REPO_FILES: [(&str, &str, [&str; 2]); 2] = [
37 ("README", "book", README_NAMES),
38 ("LICENSE", "law", ["LICENSE", "COPYING"]),
39];
40
41const IMAGE_TYPES: [(&str, &str); 6] = [
42 ("png", "image/png"),
43 ("jpg", "image/jpeg"),
44 ("jpeg", "image/jpeg"),
45 ("gif", "image/gif"),
46 ("webp", "image/webp"),
47 ("svg", "image/svg+xml"),
48];
49
50const REF_MENU_ROWS: usize = 8;
51
52const REF_CHIPS: usize = 2;
53
54const MAX_LINKS: usize = 40;
55
56const LONG_WORD: usize = 50;
57
58const BASE64_CHARS: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
59
60const ICONS: [(&str, &str); 25] = [
61 ("book", include_str!("icons/book.svg")),
62 ("law", include_str!("icons/law.svg")),
63 ("file-directory", include_str!("icons/file-directory.svg")),
64 ("file", include_str!("icons/file.svg")),
65 ("file-archive", include_str!("icons/file-archive.svg")),
66 (
67 "file-symlink-file",
68 include_str!("icons/file-symlink-file.svg"),
69 ),
70 ("file-submodule", include_str!("icons/file-submodule.svg")),
71 ("git-branch", include_str!("icons/git-branch.svg")),
72 ("git-commit", include_str!("icons/git-commit.svg")),
73 ("tag", include_str!("icons/tag.svg")),
74 ("release", include_str!("icons/release.svg")),
75 ("chevron-down", include_str!("icons/chevron-down.svg")),
76 ("chevron-right", include_str!("icons/chevron-right.svg")),
77 ("chevron-up", include_str!("icons/chevron-up.svg")),
78 ("chevron-left", include_str!("icons/chevron-left.svg")),
79 ("diff-added", include_str!("icons/diff-added.svg")),
80 ("diff-removed", include_str!("icons/diff-removed.svg")),
81 ("diff-modified", include_str!("icons/diff-modified.svg")),
82 ("diff-renamed", include_str!("icons/diff-renamed.svg")),
83 ("link", include_str!("icons/link.svg")),
84 ("info", include_str!("icons/info.svg")),
85 ("light-bulb", include_str!("icons/light-bulb.svg")),
86 ("report", include_str!("icons/report.svg")),
87 ("alert", include_str!("icons/alert.svg")),
88 ("stop", include_str!("icons/stop.svg")),
89];
90
91#[derive(Clone, Copy, PartialEq)]
92enum Tab {
93 Summary,
94 Tree,
95 Commits,
96 Branches,
97 Tags,
98 Releases,
99}
100
101const TABS: [Tab; 6] = [
102 Tab::Summary,
103 Tab::Tree,
104 Tab::Commits,
105 Tab::Branches,
106 Tab::Tags,
107 Tab::Releases,
108];
109
110impl Tab {
111 fn label(self) -> &'static str {
112 match self {
113 Tab::Summary => "summary",
114 Tab::Tree => "tree",
115 Tab::Commits => "commits",
116 Tab::Branches => "branches",
117 Tab::Tags => "tags",
118 Tab::Releases => "releases",
119 }
120 }
121
122 fn main_class(self) -> &'static str {
123 match self {
124 Tab::Summary => "",
125 Tab::Tree => "action-code",
126 Tab::Commits => "action-commits",
127 Tab::Branches => "action-branches",
128 Tab::Tags => "",
129 Tab::Releases => "action-releases",
130 }
131 }
132
133 fn href(self, git_ref: &str) -> String {
134 match self {
135 Tab::Summary => String::new(),
136 Tab::Tree => format!("tree/{}/", percent_encode(git_ref)),
137 Tab::Commits => format!("commits/{}/", percent_encode(git_ref)),
138 Tab::Branches => "branches".to_string(),
139 Tab::Tags => "tags".to_string(),
140 Tab::Releases => "releases".to_string(),
141 }
142 }
143}
144
145fn repo_tabs(repo: &RepoInfo) -> impl Iterator<Item = Tab> {
146 TABS.into_iter().filter(move |&tab| match tab {
147 Tab::Tags => !repo.tags.is_empty(),
148 Tab::Releases => !repo.releases.is_empty(),
149 _ => true,
150 })
151}
152
153struct RepoNav<'a> {
154 repo: &'a RepoInfo,
155 git_ref: &'a str,
156 tab: Tab,
157 depth: usize,
158 path: &'a str,
159 commits: usize,
160}
161
162pub fn icon(name: &str) -> String {
163 format!(
164 "<svg width=\"16\" height=\"16\" aria-hidden=\"true\"><use href=\"#icon.{name}\"/></svg>"
165 )
166}
167
168fn ref_icon(git_ref: &RefInfo) -> String {
169 if git_ref.is_tag() {
170 icon("tag")
171 } else {
172 icon("git-branch")
173 }
174}
175
176pub fn escape_str(s: &str) -> String {
177 let mut escaped_str = String::with_capacity(s.len());
178 for c in s.chars() {
179 match c {
180 '&' => escaped_str.push_str("&"),
181 '<' => escaped_str.push_str("<"),
182 '>' => escaped_str.push_str(">"),
183 '"' => escaped_str.push_str("""),
184 '\'' => escaped_str.push_str("'"),
185 _ => escaped_str.push(c),
186 }
187 }
188 escaped_str
189}
190
191fn format_bytes(bytes: usize) -> String {
192 if bytes < 1000 {
193 return format!("{bytes} B");
194 }
195 let round = |value: f64| (value * 10.0 + 0.5).floor() / 10.0;
196 let mut value = bytes as f64;
197 let mut unit = 0;
198 while round(value) >= 999.5 && unit + 1 < BYTE_UNITS.len() {
199 value /= 1000.0;
200 unit += 1;
201 }
202 let value = round(value);
203 if value < 10.0 {
204 format!("{value:.1} {}", BYTE_UNITS[unit])
205 } else {
206 format!("{value:.0} {}", BYTE_UNITS[unit])
207 }
208}
209
210pub fn percent_encode(s: &str) -> String {
211 let mut encoded = String::with_capacity(s.len());
212 for b in s.bytes() {
213 if b.is_ascii_alphanumeric() || b"-._~/".contains(&b) {
214 encoded.push(b as char);
215 } else {
216 encoded.push_str(&format!("%{b:02X}"));
217 }
218 }
219 encoded
220}
221
222fn find_ref<'a>(repo: &'a RepoInfo, dir: &str) -> Option<&'a RefInfo> {
223 repo.branches
224 .iter()
225 .chain(&repo.tags)
226 .find(|git_ref| git_ref.dir == dir)
227}
228
229fn root_dir(git_ref: &RefInfo) -> Option<&Dir> {
230 git_ref.dirs.get("")
231}
232
233fn repo_file<'a>(dir: &'a Dir, names: &[&str]) -> Option<&'a TreeEntry> {
234 names
235 .iter()
236 .find_map(|name| dir.entry(name).filter(|e| !e.is_dir))
237}
238
239struct DocLink {
240 current: &'static str,
241 href: String,
242 label: &'static str,
243 icon: &'static str,
244}
245
246fn doc_links(nav: &RepoNav, repo_root: &str) -> Vec<DocLink> {
247 let Some(git_ref) = find_ref(nav.repo, nav.git_ref) else {
248 return Vec::new();
249 };
250 let Some(root) = root_dir(git_ref) else {
251 return Vec::new();
252 };
253 REPO_FILES
254 .iter()
255 .filter_map(|&(label, icon, names)| {
256 let path = follow_links(git_ref, &repo_file(root, &names)?.name)?;
257 let href = path_href(git_ref, repo_root, &path)?;
258 Some(DocLink {
259 current: if path == nav.path {
260 " aria-current=\"page\""
261 } else {
262 ""
263 },
264 href: escape_str(&href),
265 label,
266 icon,
267 })
268 })
269 .collect()
270}
271
272fn write_readme(body: &mut String, repo: &RepoInfo, git_ref: &RefInfo, dir: &Dir, repo_root: &str) {
273 let Some(path) = repo_file(dir, &README_NAMES)
274 .and_then(|entry| follow_links(git_ref, &join_path(&dir.path, &entry.name)))
275 else {
276 return;
277 };
278 let Some(entry) = find_file(git_ref, &path) else {
279 return;
280 };
281 let Some(blob) = entry
282 .blob
283 .filter(|_| entry.lines.is_some())
284 .and_then(|id| repo.git.find_blob(id).ok())
285 else {
286 return;
287 };
288 body.push_str(
289 "\
290<div class=\"summary-readme\">\n\
291<header class=\"subtitle\">\n\
292<h2>readme</h2>\n\
293</header>\n\
294",
295 );
296 let content = blob.content();
297 let markdown = is_markdown(&entry.name);
298 write_file_head(body, entry, content, markdown);
299 if markdown {
300 let base = path.rsplit_once('/').map_or("", |(parent, _)| parent);
301 write_markdown(body, MARKDOWN_BOX, repo, git_ref, base, repo_root, content);
302 write_code(body, content);
303 } else {
304 body.push_str(&format!(
305 "<pre class=\"white-space-bs\">{}</pre>\n",
306 escape_str(&String::from_utf8_lossy(content))
307 ));
308 }
309 body.push_str("</div>\n");
310}
311
312fn icon_symbols(parts: &[&str]) -> String {
313 let used: HashSet<&str> = parts
314 .iter()
315 .flat_map(|part| {
316 part.match_indices("href=\"#icon.")
317 .filter_map(|(at, found)| part[at + found.len()..].split('"').next())
318 })
319 .collect();
320 let symbols: String = ICONS
321 .iter()
322 .filter(|(id, _)| used.contains(id))
323 .map(|(id, svg)| {
324 let view_box = svg
325 .split("viewBox=\"")
326 .nth(1)
327 .and_then(|s| s.split('"').next());
328 let start = svg.find('>').map_or(0, |i| i + 1);
329 let end = svg.rfind("</svg>").unwrap_or(svg.len());
330 format!(
331 "<symbol id=\"icon.{id}\" viewBox=\"{}\">{}</symbol>",
332 view_box.unwrap_or_default(),
333 &svg[start..end]
334 )
335 })
336 .collect();
337 if symbols.is_empty() {
338 String::new()
339 } else {
340 format!("<svg style=\"display: none\" aria-hidden=\"true\">{symbols}</svg>\n")
341 }
342}
343
344fn wrap_page(title: &str, nav: Option<&RepoNav>, body: &str) -> String {
345 let (root, title) = match nav {
346 Some(nav) => (
347 "../".repeat(nav.depth + 1),
348 format!("{} - {title}", nav.tab.label()),
349 ),
350 None => (String::new(), title.to_string()),
351 };
352 let mut header = String::from("<header class=\"topbar\">\n<div id=\"header\">\n");
353 let (main_class, footer) = match nav {
354 Some(nav) => {
355 let repo_root = "../".repeat(nav.depth);
356 let name = escape_str(&nav.repo.name);
357 header.push_str(&format!(
358 "\
359<a class=\"brand\" href=\"{root}\">{BRAND}</a>\n\
360<h1 id=\"site_path\"><a href=\"{}\" title=\"{name}\">{}</a></h1>\n\
361",
362 here(repo_root.clone()),
363 fit_name(&name)
364 ));
365 let docs = doc_links(nav, &repo_root);
366 let on_file = docs.iter().any(|doc| !doc.current.is_empty());
367 let mut tabs = String::new();
368 let mut items = String::new();
369 for tab in repo_tabs(nav.repo) {
370 let current = match (tab == nav.tab, on_file) {
371 (false, _) => "",
372 (true, false) => " aria-current=\"page\"",
373 (true, true) => " aria-current=\"true\"",
374 };
375 let count = match tab {
376 Tab::Commits => Some(nav.commits),
377 Tab::Branches => Some(nav.repo.branches.len()),
378 Tab::Tags => Some(nav.repo.tags.len()),
379 Tab::Releases => Some(nav.repo.releases.len()),
380 _ => None,
381 };
382 let label = tab.label();
383 let href = here(format!("{repo_root}{}", tab.href(nav.git_ref)));
384 tabs.push_str(&format!(
385 "<a class=\"tab\"{current} href=\"{href}\"><span class=\"tab-label\" data-label=\"{label}\">{label}</span>"
386 ));
387 items.push_str(&format!("<a href=\"{href}\"{current}><span>{label}</span>"));
388 if let Some(count) = count {
389 tabs.push_str(&format!(
390 "<span class=\"tab-count\"><span class=\"vh\">, </span>{count}</span>"
391 ));
392 items.push_str(&format!("<span>{count}</span>"));
393 }
394 tabs.push_str("</a>\n");
395 items.push_str("</a>\n");
396 }
397 header.push_str(&format!(
398 "\
399<span class=\"nav-only\">/</span>\n\
400<button type=\"button\" class=\"nav-btn\" popovertarget=\"nav-menu\">{}{}</button>\n\
401<div class=\"ref-menu-list nav-menu\" id=\"nav-menu\" popover>\n{items}</div>\n\
402",
403 nav.tab.label(),
404 icon("chevron-down")
405 ));
406 if !docs.is_empty() {
407 header.push_str(&format!(
408 "<nav class=\"nav-icons docs-{}\" aria-label=\"documents\">\n",
409 docs.len()
410 ));
411 for doc in &docs {
412 let DocLink {
413 current,
414 href,
415 label,
416 ..
417 } = doc;
418 header.push_str(&format!(
419 "<a{current} href=\"{href}\" aria-label=\"{label}\" title=\"{label}\">{}<span>{label}</span></a>\n",
420 icon(doc.icon)
421 ));
422 }
423 header.push_str("</nav>\n");
424 }
425 header.push_str(&format!(
426 "</div>\n<nav class=\"repo-tabs\" aria-label=\"repository\">\n{tabs}</nav>\n"
427 ));
428 if !docs.is_empty() {
429 header.push_str("<nav class=\"repo-docs\" aria-label=\"documents\">\n");
430 for doc in &docs {
431 let DocLink {
432 current,
433 href,
434 label,
435 ..
436 } = doc;
437 header.push_str(&format!(
438 "<a class=\"doc-link\"{current} href=\"{href}\">{}{label}</a>\n",
439 icon(doc.icon)
440 ));
441 }
442 header.push_str("</nav>\n");
443 }
444 (
445 nav.tab.main_class(),
446 "<footer class=\"site-footer\">powered by <a href=\"https://git.paramogi.world/wit/\">wit</a></footer>\n",
447 )
448 }
449 None => {
450 header.push_str(&format!(
451 "<a class=\"brand\" aria-current=\"page\" href=\"./\">{BRAND}</a>\n</div>\n"
452 ));
453 ("action-index", "")
454 }
455 };
456 header.push_str("</header>\n");
457 let main = if main_class.is_empty() {
458 "<main>".to_string()
459 } else {
460 format!("<main class=\"{main_class}\">")
461 };
462 let icons = icon_symbols(&[&header, body]);
463 format!(
464 "\
465<!DOCTYPE html>\n\
466<html lang=\"en\">\n\
467<head>\n\
468<meta charset=\"utf-8\">\n\
469<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n\
470<title>{}</title>\n\
471<link rel=\"stylesheet\" href=\"{root}style.css\">\n\
472<link rel=\"icon\" href=\"{root}favicon.ico\">\n\
473</head>\n\
474<body>\n\
475{icons}\
476{header}\
477{main}\n\
478{body}\
479</main>\n\
480{footer}\
481</body>\n\
482</html>\n\
483",
484 escape_str(&title)
485 )
486}
487
488fn description(repo: &RepoInfo) -> (&'static str, String) {
489 if repo.description.is_empty() {
490 (" empty", NO_DESCRIPTION.to_string())
491 } else {
492 ("", escape_str(&repo.description))
493 }
494}
495
496pub fn gen_index(repos: &[RepoInfo]) -> String {
497 let mut sorted: Vec<&RepoInfo> = repos.iter().collect();
498 sorted.sort_by_key(|repo| Reverse(repo.commit_list[0].committer_date));
499
500 let mut body = String::from("<h1 class=\"vh\">repositories</h1>\n<ul class=\"repo-list\">\n");
501 for repo in sorted {
502 let name = escape_str(&repo.name);
503 let dir = percent_encode(&repo.name);
504 let links: String = repo_tabs(repo)
505 .map(|tab| {
506 format!(
507 "<a href=\"{dir}/{}\">{}</a>",
508 tab.href(&repo.head_dir),
509 tab.label()
510 )
511 })
512 .collect();
513 let (empty, description) = description(repo);
514 body.push_str(&format!(
515 "\
516<li class=\"repo-row\">\n\
517<h2 class=\"flex repo-name\"><a class=\"truncate row-link\" href=\"{dir}/\">{name}</a></h2>\n\
518<p class=\"repo-date\"><span class=\"repo-date-label\">last commit </span>{}</p>\n\
519<p class=\"repo-desc{empty}\">{description}</p>\n\
520<div class=\"repo-links\">{links}</div>\n\
521</li>\n\
522",
523 repo.commit_list[0].committer_date.format(DATE),
524 ));
525 }
526 body.push_str("</ul>\n");
527
528 wrap_page("repositories", None, &body)
529}
530
531pub fn gen_summary(repo: &RepoInfo, last: &HashMap<String, &CommitInfo>) -> String {
532 let nav = RepoNav {
533 repo,
534 git_ref: &repo.head_dir,
535 tab: Tab::Summary,
536 depth: 0,
537 path: "",
538 commits: repo.commit_list.len(),
539 };
540 let mut body = String::from("<div class=\"summary-layout\">\n<div class=\"summary-main\">\n");
541 let head = find_ref(repo, &repo.head_dir);
542 if let Some(head) = head
543 && let Some(root) = root_dir(head)
544 {
545 body.push_str("<div class=\"summary-tree\">\n");
546 body.push_str(&ref_bar(repo, head, "", "", repo.commit_list.len(), "true"));
547 let tree_dir = format!("tree/{}/", repo.head_dir);
548 write_listing(&mut body, head, root, "", &tree_dir, last);
549 body.push_str("</div>\n");
550 write_readme(&mut body, repo, head, root, "");
551 }
552 body.push_str("</div>\n<aside class=\"summary-side\">\n");
553
554 let meta_row = |key: &str, class: &str, val: &str| {
555 let key = if key.is_empty() {
556 String::new()
557 } else {
558 format!("<span class=\"summary-meta-key\">{key}</span>\n")
559 };
560 format!(
561 "<div class=\"summary-meta-row border-b\">\n{key}<span class=\"summary-meta-val{class}\">{val}</span>\n</div>\n"
562 )
563 };
564 let dot = " · ";
565 let newest = &repo.commit_list[0];
566 let (empty, description) = description(repo);
567 body.push_str("<div class=\"box summary-meta-box\">\n");
568 body.push_str(&meta_row("", empty, &description));
569 if !repo.owner.is_empty() {
570 body.push_str(&meta_row("owner", " truncate", &escape_str(&repo.owner)));
571 }
572 let last_commit = format!(
573 "{}{dot}{}",
574 short_id("", &newest.id),
575 newest.committer_date.format(DATE)
576 );
577 body.push_str(&meta_row("last commit", "", &last_commit));
578 if let Some(release) = repo.releases.first() {
579 let link = format!(
580 "<a href=\"{}\" class=\"release-id\">{}<span class=\"truncate\">{}</span></a>{dot}{}",
581 Tab::Releases.href(""),
582 icon("release"),
583 escape_str(&release.tag),
584 release.date.format(DATE)
585 );
586 body.push_str(&meta_row("latest release", "", &link));
587 }
588 let clone_url = format!("{CLONE_URL_BASE}{}.git", repo.name);
589 body.push_str(&meta_row("clone url", "", &escape_str(&clone_url)));
590 body.push_str("</div>\n");
591
592 write_briefs(&mut body, repo);
593 if repo.branches.len() > 1 {
594 let rows: String = repo
595 .branches
596 .iter()
597 .take(SUMMARY_REF_COUNT)
598 .map(|r| side_row(&ref_icon(r), &Tab::Tree.href(&r.dir), &r.name, &r.date))
599 .collect();
600 write_side_list(&mut body, Tab::Branches, &rows);
601 }
602 if !repo.tags.is_empty() {
603 let rows: String = repo
604 .tags
605 .iter()
606 .take(SUMMARY_REF_COUNT)
607 .map(|r| side_row(&ref_icon(r), &Tab::Tree.href(&r.dir), &r.name, &r.date))
608 .collect();
609 write_side_list(&mut body, Tab::Tags, &rows);
610 }
611 if !repo.releases.is_empty() {
612 let rows: String = repo
613 .releases
614 .iter()
615 .take(SUMMARY_REF_COUNT)
616 .enumerate()
617 .map(|(n, release)| {
618 let href = format!("{}#release-{}", Tab::Releases.href(""), n + 1);
619 side_row(&icon("release"), &href, &release.tag, &release.date)
620 })
621 .collect();
622 write_side_list(&mut body, Tab::Releases, &rows);
623 }
624 body.push_str("</aside>\n</div>\n");
625
626 wrap_page(&repo.name, Some(&nav), &body)
627}
628
629fn side_row(icon: &str, href: &str, name: &str, date: &DateTime<FixedOffset>) -> String {
630 format!(
631 "\
632<section class=\"flex items-center gap-2 px row tree-row border-b\">\n\
633<div class=\"branch-name flex-1 flex items-center gap\">{icon}<a class=\"truncate row-link\" href=\"{href}\">{}</a></div>\n\
634{}\
635</section>\n\
636",
637 escape_str(name),
638 date_cell(date)
639 )
640}
641
642fn write_side_list(body: &mut String, tab: Tab, rows: &str) {
643 let label = tab.label();
644 body.push_str(&format!(
645 "\
646<div>\n\
647<header class=\"subtitle\">\n\
648<h2>{label}</h2>\n\
649</header>\n\
650<div class=\"box p-0 side-list\">\n\
651{rows}\
652<div class=\"row side-all px\">\n\
653<a class=\"row-link\" href=\"{}\">all {label}</a>\n\
654</div>\n\
655</div>\n\
656</div>\n\
657",
658 tab.href("")
659 ));
660}
661
662pub fn gen_branches(repo: &RepoInfo, counts: &HashMap<String, usize>) -> String {
663 let (head, others): (Vec<&RefInfo>, Vec<&RefInfo>) = repo
664 .branches
665 .iter()
666 .partition(|git_ref| git_ref.dir == repo.head_dir);
667 let mut body = String::new();
668 write_refs(&mut body, "default branch", &head, counts);
669 if !others.is_empty() {
670 let heading = format!(
671 "other branches <span class=\"count\">{}</span>",
672 others.len()
673 );
674 write_refs(&mut body, &heading, &others, counts);
675 }
676 gen_refs(repo, Tab::Branches, &body)
677}
678
679pub fn gen_tags(repo: &RepoInfo, counts: &HashMap<String, usize>) -> String {
680 let tags: Vec<&RefInfo> = repo.tags.iter().collect();
681 let heading = format!("tags <span class=\"count\">{}</span>", tags.len());
682 let mut body = String::new();
683 write_refs(&mut body, &heading, &tags, counts);
684 gen_refs(repo, Tab::Tags, &body)
685}
686
687fn gen_refs(repo: &RepoInfo, tab: Tab, body: &str) -> String {
688 let nav = RepoNav {
689 repo,
690 git_ref: &repo.head_dir,
691 tab,
692 depth: 1,
693 path: "",
694 commits: repo.commit_list.len(),
695 };
696 wrap_page(&repo.name, Some(&nav), body)
697}
698
699fn write_refs(
700 body: &mut String,
701 heading: &str,
702 refs: &[&RefInfo],
703 counts: &HashMap<String, usize>,
704) {
705 if refs.is_empty() {
706 return;
707 }
708 body.push_str(&format!(
709 "<header class=\"subtitle\"><h2>{heading}</h2></header>\n<div class=\"box mt-0 p-0\">\n"
710 ));
711 for git_ref in refs {
712 body.push_str(&format!(
713 "\
714<div class=\"flex items-center gap-2 px row tree-row border-b branch-row\">\n\
715<div class=\"flex-1 flex items-center gap branch-name\">{}<a class=\"truncate row-link\" href=\"../{}\">{}</a></div>\n\
716<div class=\"tree-commit short-id branch-sha\">{}</div>\n\
717{}\
718{}\
719<a class=\"branch-log\" href=\"../{}\">{}</a>\n\
720</div>\n\
721",
722 ref_icon(git_ref),
723 Tab::Tree.href(&git_ref.dir),
724 escape_str(&git_ref.name),
725 short_id("../", &git_ref.id),
726 summary_cell("../", &git_ref.id, &git_ref.summary),
727 date_cell(&git_ref.date),
728 Tab::Commits.href(&git_ref.dir),
729 commit_count(counts[&git_ref.dir])
730 ));
731 }
732 body.push_str("</div>\n");
733}
734
735pub fn gen_releases(repo: &RepoInfo, sums: &[Vec<(usize, String)>]) -> String {
736 let nav = RepoNav {
737 repo,
738 git_ref: &repo.head_dir,
739 tab: Tab::Releases,
740 depth: 1,
741 path: "",
742 commits: repo.commit_list.len(),
743 };
744
745 let mut body = format!(
746 "<header class=\"subtitle\"><h2>releases <span class=\"count\">{}</span></h2></header>\n",
747 repo.releases.len()
748 );
749 for (n, (release, sums)) in repo.releases.iter().zip(sums).enumerate() {
750 let Some(tag) = repo.tags.iter().find(|t| t.name == release.tag) else {
751 continue;
752 };
753 let (hover, title) = if release.title.is_empty() {
754 Default::default()
755 } else {
756 let title = escape_str(&release.title);
757 (
758 format!(" title=\"{title}\""),
759 format!("<span class=\"rel-title\">{title}</span>"),
760 )
761 };
762 body.push_str(&format!(
763 "\
764<section id=\"release-{}\" class=\"box mt-0 p-0 rel\">\n\
765<div class=\"flex items-center gap-2 px border-b rel-head\">\n\
766<div class=\"flex-1 flex items-center gap rel-name\">{}<a class=\"truncate\" href=\"../{}\"{hover}>{}{title}</a></div>\n\
767<div class=\"ml-auto flex items-center\">\n\
768<div class=\"flex items-center tree-commit short-id\">{}</div>\n\
769{}\
770</div>\n\
771</div>\n\
772",
773 n + 1,
774 icon("release"),
775 Tab::Tree.href(&format!("tags/{}", release.tag)),
776 escape_str(&release.tag),
777 short_id("../", &tag.id),
778 date_cell(&release.date)
779 ));
780 if !release.notes.is_empty() {
781 let notes = release.notes.as_bytes();
782 write_markdown(
783 &mut body,
784 "markdown-body border-b",
785 repo,
786 tag,
787 "",
788 "../",
789 notes,
790 );
791 }
792 let dir = percent_encode(&release.tag);
793 let (file_sums, archive_sums) = sums.split_at(release.files.len());
794 for (name, sum) in release.files.iter().zip(file_sums) {
795 let href = format!("{dir}/{}", percent_encode(name));
796 body.push_str(&release_row("file", &href, name, name, sum));
797 }
798 let archive = archive_name(&repo.name, &release.tag);
799 for (format, sum) in ARCHIVE_FORMATS.iter().zip(archive_sums) {
800 let href = format!("../archive/{dir}.{format}");
801 let download = format!("{archive}.{format}");
802 body.push_str(&release_row(
803 "file-archive",
804 &href,
805 &download,
806 &download,
807 sum,
808 ));
809 }
810 body.push_str("</section>\n");
811 }
812
813 wrap_page(&repo.name, Some(&nav), &body)
814}
815
816fn release_row(
817 icon_name: &str,
818 href: &str,
819 download: &str,
820 label: &str,
821 (bytes, sha256): &(usize, String),
822) -> String {
823 format!(
824 "\
825<div class=\"flex items-center gap-2 px row tree-row border-b rel-file\">\n\
826<div class=\"flex-1 flex items-center gap rel-name\">{}<a class=\"truncate row-link\" download=\"{}\" href=\"{href}\">{}</a></div>\n\
827<div class=\"truncate rel-sum\"><span class=\"rel-sum-label\">sha256</span> {sha256}</div>\n\
828<div class=\"rel-size\">{}</div>\n\
829</div>\n\
830",
831 icon(icon_name),
832 escape_str(download),
833 escape_str(label),
834 format_bytes(*bytes)
835 )
836}
837
838fn summary_cell(repo_root: &str, id: &str, summary: &str) -> String {
839 let summary = escape_str(summary);
840 format!(
841 "<div class=\"flex flex-2 tree-commit\"><a class=\"truncate\" href=\"{repo_root}commits/{id}\" title=\"{summary}\">{summary}</a></div>\n"
842 )
843}
844
845fn commit_cells(repo_root: &str, id: &str, summary: &str, date: &DateTime<FixedOffset>) -> String {
846 let href = format!("{repo_root}commits/{id}");
847 let summary = escape_str(summary);
848 format!(
849 "\
850<div class=\"flex items-center tree-commit short-id\"><a href=\"{href}\" class=\"commit-id row-link\">{}{}</a></div>\n\
851<div class=\"flex flex-2 tree-commit\"><a class=\"truncate row-link\" href=\"{href}\" title=\"{summary}\">{summary}</a></div>\n\
852{}\
853",
854 icon("git-commit"),
855 &id[..7],
856 date_cell(date)
857 )
858}
859
860fn short_id(repo_root: &str, id: &str) -> String {
861 format!(
862 "<a href=\"{repo_root}commits/{id}\" class=\"commit-id\">{}{}</a>",
863 icon("git-commit"),
864 &id[..7]
865 )
866}
867
868fn date_cell(date: &DateTime<FixedOffset>) -> String {
869 format!("<div class=\"tree-date\">{}</div>\n", date.format(DATE))
870}
871
872fn format_zoned(date: &DateTime<FixedOffset>, format: &str) -> String {
873 let seconds = date.offset().local_minus_utc();
874 let sign = if seconds < 0 { '-' } else { '+' };
875 let (hours, minutes) = (seconds.abs() / 3600, seconds.abs() % 3600 / 60);
876 let zone = match (hours, minutes) {
877 (0, 0) => String::new(),
878 (_, 0) => format!("{sign}{hours}"),
879 _ => format!("{sign}{hours}:{minutes:02}"),
880 };
881 format!("{} UTC{zone}", date.format(format))
882}
883
884fn tree_depth(git_ref: &RefInfo, dir: &Dir) -> usize {
885 1 + join_path(&git_ref.dir, &dir.path).split('/').count()
886}
887
888fn last_details(repo_root: &str, last: &HashMap<String, &CommitInfo>, path: &str) -> String {
889 last.get(path).map_or_else(String::new, |commit| {
890 commit_cells(
891 repo_root,
892 &commit.id,
893 &commit.summary,
894 &commit.committer_date,
895 )
896 })
897}
898
899pub fn gen_tree(
900 repo: &RepoInfo,
901 git_ref: &RefInfo,
902 dir: &Dir,
903 last: &HashMap<String, &CommitInfo>,
904 commits: usize,
905) -> String {
906 let depth = tree_depth(git_ref, dir);
907 let nav = RepoNav {
908 repo,
909 git_ref: &git_ref.dir,
910 tab: Tab::Tree,
911 depth,
912 path: "",
913 commits,
914 };
915 let repo_root = "../".repeat(depth);
916
917 let mut body = ref_bar(repo, git_ref, &dir.path, &repo_root, commits, "page");
918 write_listing(&mut body, git_ref, dir, &repo_root, "", last);
919 write_readme(&mut body, repo, git_ref, dir, &repo_root);
920
921 let title = format!("{}/{}", repo.name, git_ref.name);
922 wrap_page(&title, Some(&nav), &body)
923}
924
925pub fn gen_blob(
926 repo: &RepoInfo,
927 git_ref: &RefInfo,
928 dir: &Dir,
929 entry: &TreeEntry,
930 content: &[u8],
931 last: &HashMap<String, &CommitInfo>,
932 commits: usize,
933) -> String {
934 let depth = tree_depth(git_ref, dir) + 1;
935 let path = join_path(&dir.path, &entry.name);
936 let nav = RepoNav {
937 repo,
938 git_ref: &git_ref.dir,
939 tab: Tab::Tree,
940 depth,
941 path: &path,
942 commits,
943 };
944 let repo_root = "../".repeat(depth);
945 let details = last_details(&repo_root, last, &path);
946
947 let mut body = ref_bar(repo, git_ref, &path, &repo_root, commits, "page");
948 if !details.is_empty() {
949 body.push_str(&format!(
950 "<div class=\"box joined flex items-center gap row last-commit\">\n{details}</div>\n"
951 ));
952 }
953 let views = has_source_view(entry);
954 write_file_head(&mut body, entry, content, views);
955 let text = entry.lines.is_some();
956 match image_type(&entry.name) {
957 Some(mime) => body.push_str(&format!(
958 "<div class=\"box\"><img src=\"{}\" alt=\"{}\"></div>\n",
959 data_uri(mime, content),
960 escape_str(&entry.name)
961 )),
962 None if text && is_markdown(&entry.name) => write_markdown(
963 &mut body,
964 MARKDOWN_BOX,
965 repo,
966 git_ref,
967 &dir.path,
968 &repo_root,
969 content,
970 ),
971 _ if text => write_code(&mut body, content),
972 _ => body.push_str(
973 "<pre class=\"chroma\"><code><span class=\"cl\">cannot display</span></code></pre>\n",
974 ),
975 }
976 if views {
977 write_code(&mut body, content);
978 }
979
980 let title = format!("{}/{}/{path}", repo.name, git_ref.name);
981 wrap_page(&title, Some(&nav), &body)
982}
983
984fn write_file_head(body: &mut String, entry: &TreeEntry, content: &[u8], views: bool) {
985 if views {
986 body.push_str(
987 "\
988<input type=\"radio\" class=\"vh\" name=\"view\" id=\"view-source\">\n\
989<input type=\"radio\" class=\"vh\" name=\"view\" id=\"view-rendered\" checked>\n\
990<div class=\"buttons flex view-switch\"><label for=\"view-source\">source</label>\n\
991<label for=\"view-rendered\">rendered</label></div>\n\
992",
993 );
994 }
995 let mut details = Vec::new();
996 if let Some(n) = entry.lines {
997 let s = if n == 1 { "" } else { "s" };
998 details.push(format!("<span>{n} line{s}</span>\n"));
999 }
1000 let bytes = entry.bytes.map(format_bytes).unwrap_or_default();
1001 details.push(format!("<span>{bytes}</span>\n"));
1002 if let Some((width, height)) =
1003 image_type(&entry.name).and_then(|mime| image_size(mime, content))
1004 {
1005 details.push(format!("<span>{width}x{height}px</span>\n"));
1006 }
1007 body.push_str("<div class=\"flex items-center file-head\">\n<div class=\"file-sizes\">\n");
1008 for shown in 1..=details.len() {
1009 let hidden = if shown < details.len() {
1010 " aria-hidden=\"true\""
1011 } else {
1012 ""
1013 };
1014 let strut = if shown > 1 {
1015 "<span class=\"fs-strut\"></span>\n"
1016 } else {
1017 ""
1018 };
1019 body.push_str(&format!(
1020 "<div class=\"fs-layer\"{hidden}>\n{strut}<div class=\"flex gap file-size\">\n{}</div>\n</div>\n",
1021 details[..shown].concat()
1022 ));
1023 }
1024 body.push_str("</div>\n</div>\n");
1025}
1026
1027fn page_href(page: usize, to: usize) -> String {
1028 let up = if page == 1 { "" } else { "../" };
1029 here(if to == 1 {
1030 up.to_string()
1031 } else {
1032 format!("{up}{to}")
1033 })
1034}
1035
1036fn here(href: String) -> String {
1037 if href.is_empty() {
1038 "./".to_string()
1039 } else {
1040 href
1041 }
1042}
1043
1044pub fn commits_page(page: usize) -> String {
1045 if page == 1 {
1046 "index.html".to_string()
1047 } else {
1048 format!("{page}/index.html")
1049 }
1050}
1051
1052pub fn gen_commits(
1053 repo: &RepoInfo,
1054 git_ref: &RefInfo,
1055 all: &[CommitInfo],
1056 stats: &HashMap<String, String>,
1057 page: usize,
1058) -> String {
1059 let depth = 1 + git_ref.dir.split('/').count() + usize::from(page > 1);
1060 let nav = RepoNav {
1061 repo,
1062 git_ref: &git_ref.dir,
1063 tab: Tab::Commits,
1064 depth,
1065 path: "",
1066 commits: all.len(),
1067 };
1068 let repo_root = "../".repeat(depth);
1069 let total = all.len();
1070 let start = (page - 1) * COMMITS_PER_PAGE;
1071 let end = total.min(start + COMMITS_PER_PAGE);
1072 let commits = &all[start..end];
1073 let count = if page > 1 {
1074 format!(
1075 "<span class=\"font-bold\">{}–{end}</span> of {total} commits",
1076 start + 1
1077 )
1078 } else if end < total {
1079 format!("<span class=\"font-bold\">{end}</span> of {total} commits")
1080 } else {
1081 commit_count(total)
1082 };
1083
1084 let mut body = format!(
1085 "\
1086<div class=\"log\">\n\
1087<div class=\"box sticky flex items-center gap flex-wrap m-0\">\n\
1088{}\
1089<div class=\"ml-auto\">{count}</div>\n\
1090</div>\n\
1091",
1092 ref_menu(repo, git_ref, &repo_root, Tab::Commits, "", "page")
1093 );
1094 let mut day = String::new();
1095 let mut menus = 1;
1096 for commit in commits {
1097 let date = commit.committer_date.format(DATE).to_string();
1098 let joined = if date == day {
1099 " joined"
1100 } else {
1101 if !day.is_empty() {
1102 body.push_str("</div>\n");
1103 }
1104 body.push_str(&format!(
1105 "<div class=\"log-day\">\n<div class=\"text-xs log-date\">{date}</div>\n"
1106 ));
1107 ""
1108 };
1109 let labels = ref_labels(repo, &commit.id, &repo_root, &mut menus);
1110 write_commit_row(
1111 &mut body,
1112 commit,
1113 Some(&stats[&commit.id]),
1114 &labels,
1115 &repo_root,
1116 joined,
1117 &format_zoned(&commit.committer_date, "%H:%M"),
1118 );
1119 day = date;
1120 }
1121 body.push_str("</div>\n");
1122 let pages = total.div_ceil(COMMITS_PER_PAGE);
1123 if pages > 1 {
1124 body.push_str(&commits_pager(page, pages));
1125 }
1126 body.push_str("</div>\n");
1127
1128 let title = format!("{}/{}", repo.name, git_ref.name);
1129 wrap_page(&title, Some(&nav), &body)
1130}
1131
1132pub fn diff_stat(diff: &CommitDiff) -> String {
1133 if diff.files.is_empty() {
1134 return "no changes".to_string();
1135 }
1136 let s = if diff.files.len() == 1 { "" } else { "s" };
1137 format!(
1138 "<strong>{}</strong> file{s} changed, <span class=\"color-green\">+{}</span>, <span class=\"color-red\">-{}</span>",
1139 diff.files.len(),
1140 diff.files.iter().map(|f| f.added).sum::<usize>(),
1141 diff.files.iter().map(|f| f.removed).sum::<usize>()
1142 )
1143}
1144
1145fn break_long_words(text: &str) -> String {
1146 text.split_inclusive(char::is_whitespace)
1147 .map(|piece| {
1148 let word = piece.trim_end();
1149 if word.chars().count() <= LONG_WORD {
1150 return escape_str(piece);
1151 }
1152 format!(
1153 "<span class=\"long-word\">{}</span>{}",
1154 escape_str(word),
1155 &piece[word.len()..]
1156 )
1157 })
1158 .collect()
1159}
1160
1161pub fn gen_commit(
1162 repo: &RepoInfo,
1163 git_ref: &RefInfo,
1164 commit: &CommitInfo,
1165 diff: &CommitDiff,
1166 commits: usize,
1167) -> String {
1168 let nav = RepoNav {
1169 repo,
1170 git_ref: &git_ref.dir,
1171 tab: Tab::Commits,
1172 depth: 2,
1173 path: "",
1174 commits,
1175 };
1176 let short = &commit.id[..7];
1177 let parents: Vec<String> = diff
1178 .parents
1179 .iter()
1180 .map(|id| format!("<a href=\"../{id}\">{}</a>", &id[..7]))
1181 .collect();
1182 let parents = match parents.len() {
1183 0 => String::new(),
1184 1 => format!(
1185 "<div class=\"commit-parent\"><span>parent</span><span>{}</span></div>\n",
1186 parents[0]
1187 ),
1188 _ => format!(
1189 "<div class=\"commit-parent\"><span>parents</span><span>{}</span></div>\n",
1190 parents.join(", ")
1191 ),
1192 };
1193 let format = "%d-%m-%Y %H:%M";
1194 let rest = commit
1195 .message
1196 .trim()
1197 .split_once("\n\n")
1198 .map_or("", |(_, rest)| rest.trim());
1199 let message_body = if rest.is_empty() {
1200 String::new()
1201 } else {
1202 format!(
1203 "<div class=\"white-space-bs commit-body\">{}</div>\n",
1204 break_long_words(rest)
1205 )
1206 };
1207
1208 let mut body = format!(
1209 "\
1210<div class=\"box commit-head\">\n\
1211<div class=\"commit-msg\">\n\
1212<div class=\"commit-changes\">{}</div>\n\
1213<div class=\"commit-title\"><span class=\"commit-id\">{}{short}</span>{}</div>\n\
1214{message_body}\
1215</div>\n\
1216<div class=\"commit-meta\">\n\
1217<div>author</div>\n\
1218<div>{} <{}> on {}</div>\n\
1219<div>committer</div>\n\
1220<div>{} <{}> on {}</div>\n\
1221{parents}\
1222</div>\n\
1223</div>\n\
1224",
1225 diff_stat(diff),
1226 icon("git-commit"),
1227 break_long_words(&commit.summary),
1228 escape_str(&commit.author_name),
1229 escape_str(&commit.author_email),
1230 format_zoned(&commit.author_date, format),
1231 escape_str(&commit.committer_name),
1232 escape_str(&commit.committer_email),
1233 format_zoned(&commit.committer_date, format)
1234 );
1235 if !diff.files.is_empty() {
1236 body.push_str("<div class=\"box joined commit-files\">\n");
1237 for (n, file) in diff.files.iter().enumerate() {
1238 body.push_str(&format!(
1239 "<div class=\"flex items-center gap\">{}<a href=\"#diff-{n}\">{}</a><div class=\"ml-auto diff-stat\">{}</div></div>\n",
1240 status_icon(file.status),
1241 change_path(file),
1242 file_stat(file)
1243 ));
1244 }
1245 body.push_str("</div>\n");
1246 }
1247 for (n, file) in diff.files.iter().enumerate() {
1248 body.push_str(&format!(
1249 "\
1250<div>\n\
1251<div id=\"diff-{n}\" class=\"box sticky flex items-center diff-head\">\n\
1252<div class=\"flex-1 flex items-center gap\">{}<a href=\"#diff-{n}\">{}</a></div>\n\
1253<div class=\"diff-stat\">{}</div>\n\
1254</div>\n\
1255",
1256 status_icon(file.status),
1257 change_path(file),
1258 file_stat(file)
1259 ));
1260 match file.binary {
1261 Some((old, new)) => {
1262 let sizes = match file.status {
1263 'A' => format_bytes(new),
1264 'D' => format_bytes(old),
1265 _ => format!("{} → {}", format_bytes(old), format_bytes(new)),
1266 };
1267 body.push_str(&format!(
1268 "<div class=\"box joined\">binary file, {sizes}</div>\n"
1269 ));
1270 }
1271 None if !file.lines.is_empty() => write_diff(&mut body, n, &file.lines),
1272 None if file.status == 'R' => {
1273 body.push_str("<div class=\"box joined\">renamed without changes</div>\n")
1274 }
1275 None => {}
1276 }
1277 body.push_str("</div>\n");
1278 }
1279
1280 let title = format!("{}/{short}: {}", repo.name, commit.summary);
1281 wrap_page(&title, Some(&nav), &body)
1282}
1283
1284fn status_icon(status: char) -> String {
1285 let (name, class, title) = match status {
1286 'A' => ("diff-added", " color-green", "added"),
1287 'D' => ("diff-removed", " color-red", "deleted"),
1288 'R' => ("diff-renamed", "", "renamed"),
1289 'T' => ("diff-modified", " color-orange", "type changed"),
1290 _ => ("diff-modified", " color-orange", "modified"),
1291 };
1292 format!(
1293 "<span class=\"flex{class}\" title=\"{title}\" role=\"img\" aria-label=\"{title}\">{}</span>",
1294 icon(name)
1295 )
1296}
1297
1298fn file_stat(file: &FileChange) -> String {
1299 format!(
1300 "<span class=\"color-green\">+{}</span>, <span class=\"color-red\">-{}</span>",
1301 file.added, file.removed
1302 )
1303}
1304
1305fn change_path(file: &FileChange) -> String {
1306 match &file.old_path {
1307 Some(old) => format!("{} → {}", escape_str(old), escape_str(&file.path)),
1308 None => escape_str(&file.path),
1309 }
1310}
1311
1312fn write_diff(body: &mut String, n: usize, lines: &[Line]) {
1313 let max = lines.iter().filter_map(|l| l.old.max(l.new)).max();
1314 let width = max.unwrap_or(0).to_string().len();
1315 let number = |body: &mut String, side: &str, num: Option<u32>| {
1316 let _ = match num {
1317 Some(num) => write!(
1318 body,
1319 "<a class=\"ln\" id=\"d{n}-{side}{num}\" href=\"#d{n}-{side}{num}\" tabindex=\"-1\">{num:>width$}</a>"
1320 ),
1321 None => write!(body, "<span class=\"ln\">{:width$}</span>", ""),
1322 };
1323 };
1324 body.push_str("<pre class=\"chroma joined\"><code>");
1325 for line in lines {
1326 let text = escape_str(&line.text);
1327 let (class, text, old, new) = match line.origin {
1328 '@' => ("", format!("<span class=\"gu\">{text}</span>"), None, None),
1329 '+' => (" gi", format!("+{text}"), None, line.new),
1330 '-' => (" gd", format!("-{text}"), line.old, None),
1331 ' ' => ("", format!(" {text}"), line.old, line.new),
1332 _ => ("", "\\ No newline at end of file\n".to_string(), None, None),
1333 };
1334 let _ = write!(body, "<span class=\"line{class}\">");
1335 number(body, "L", old);
1336 number(body, "R", new);
1337 body.push_str("<span class=\"cl\">");
1338 push_line(body, &text);
1339 body.push_str("</span></span>");
1340 }
1341 body.push_str("</code></pre>\n");
1342}
1343
1344fn commits_pager(page: usize, pages: usize) -> String {
1345 let arrow = |n: usize, label: &str, name: &str| {
1346 format!(
1347 "<a href=\"{}\" title=\"{label}\" aria-label=\"{label}\">{}</a>\n",
1348 page_href(page, n),
1349 icon(name)
1350 )
1351 };
1352 let mut pager =
1353 String::from("<nav class=\"buttons flex flex-wrap pager\" aria-label=\"pages\">\n");
1354 if page > 1 {
1355 pager.push_str(&arrow(page - 1, "previous page", "chevron-left"));
1356 }
1357 let mut shown = 0;
1358 for n in 1..=pages {
1359 if n != 1 && n != pages && n.abs_diff(page) > 1 {
1360 continue;
1361 }
1362 if n > shown + 1 {
1363 pager.push_str("<span class=\"pager-gap\">…</span>\n");
1364 }
1365 if n == page {
1366 pager.push_str(&format!("<span aria-current=\"page\">{n}</span>\n"));
1367 } else {
1368 pager.push_str(&format!("<a href=\"{}\">{n}</a>\n", page_href(page, n)));
1369 }
1370 shown = n;
1371 }
1372 if page < pages {
1373 pager.push_str(&arrow(page + 1, "next page", "chevron-right"));
1374 }
1375 pager.push_str("</nav>\n");
1376 pager
1377}
1378
1379fn has_source_view(entry: &TreeEntry) -> bool {
1380 entry.lines.is_some() && (image_type(&entry.name).is_some() || is_markdown(&entry.name))
1381}
1382
1383fn blob_href(git_ref: &RefInfo, path: &str) -> String {
1384 percent_encode(&format!("blob/{}/{path}", git_ref.dir))
1385}
1386
1387pub fn path_href(git_ref: &RefInfo, repo_root: &str, path: &str) -> Option<String> {
1388 let path = follow_links(git_ref, path)?;
1389 if git_ref.dirs.contains_key(&path) {
1390 let href = Tab::Tree.href(&join_path(&git_ref.dir, &path));
1391 return Some(format!("{repo_root}{href}"));
1392 }
1393 let entry = find_entry(git_ref, &path)?;
1394 if entry.blob.is_some() {
1395 return Some(format!("{repo_root}{}", blob_href(git_ref, &path)));
1396 }
1397 entry.commit.as_ref()?;
1398 git_ref
1399 .submodules
1400 .iter()
1401 .filter(|(module, _)| *module == path)
1402 .find_map(|(_, url)| web_url(url))
1403}
1404
1405fn web_url(url: &str) -> Option<String> {
1406 if url.starts_with("https://") {
1407 return Some(url.to_string());
1408 }
1409 let (host, path) = match url.strip_prefix("ssh://git@") {
1410 Some(rest) => rest
1411 .split_once('/')
1412 .filter(|(host, _)| !host.contains(':'))?,
1413 None => url
1414 .strip_prefix("git@")?
1415 .split_once(':')
1416 .filter(|(host, _)| !host.contains('/'))?,
1417 };
1418 let path = path.trim_start_matches('/');
1419 (!host.is_empty() && !path.is_empty()).then(|| format!("https://{host}/{path}"))
1420}
1421
1422pub fn follow_links(git_ref: &RefInfo, path: &str) -> Option<String> {
1423 let mut path = path.to_string();
1424 let mut dir_only = false;
1425 for _ in 0..=MAX_LINKS {
1426 let dir = path.rsplit_once('/').map_or("", |(dir, _)| dir);
1427 let link = find_entry(git_ref, &path).and_then(|entry| entry.link.as_deref());
1428 match link {
1429 Some(target) if target.is_empty() || target.starts_with('/') => return None,
1430 Some(target) => {
1431 dir_only |= target.ends_with('/');
1432 path = resolve_path(dir, target)?;
1433 }
1434 None => {
1435 let is_dir = git_ref.dirs.contains_key(&path);
1436 return (is_dir || !dir_only).then_some(path);
1437 }
1438 }
1439 }
1440 None
1441}
1442
1443pub fn resolve_path(base: &str, path: &str) -> Option<String> {
1444 let mut parts: Vec<&str> = base.split('/').filter(|part| !part.is_empty()).collect();
1445 for part in path.split('/') {
1446 match part {
1447 "" | "." => {}
1448 ".." => {
1449 parts.pop()?;
1450 }
1451 _ => parts.push(part),
1452 }
1453 }
1454 Some(parts.join("/"))
1455}
1456
1457fn find_entry<'a>(git_ref: &'a RefInfo, path: &str) -> Option<&'a TreeEntry> {
1458 let (dir, name) = path.rsplit_once('/').unwrap_or(("", path));
1459 git_ref.dirs.get(dir)?.entry(name)
1460}
1461
1462pub fn find_file<'a>(git_ref: &'a RefInfo, path: &str) -> Option<&'a TreeEntry> {
1463 find_entry(git_ref, path).filter(|entry| entry.blob.is_some())
1464}
1465
1466pub fn data_uri(mime: &str, content: &[u8]) -> String {
1467 format!("data:{mime};base64,{}", base64(content))
1468}
1469
1470pub fn image_type(name: &str) -> Option<&'static str> {
1471 let (_, ext) = name.rsplit_once('.')?;
1472 IMAGE_TYPES
1473 .iter()
1474 .find(|(known, _)| ext.eq_ignore_ascii_case(known))
1475 .map(|(_, mime)| *mime)
1476}
1477
1478fn image_size(mime: &str, content: &[u8]) -> Option<(usize, usize)> {
1479 if mime != "image/svg+xml" {
1480 let size = imagesize::blob_size(content).ok()?;
1481 return Some((size.width, size.height));
1482 }
1483 let text = String::from_utf8_lossy(content);
1484 let start = text.find("<svg")?;
1485 let tag = &text[start..start + text[start..].find('>')?];
1486 let number = |value: &str| value.trim().trim_end_matches("px").parse::<f64>().ok();
1487 if let (Some(width), Some(height)) = (
1488 attr(tag, "width").and_then(number),
1489 attr(tag, "height").and_then(number),
1490 ) {
1491 return Some((width.round() as usize, height.round() as usize));
1492 }
1493 let view_box: Vec<f64> = attr(tag, "viewBox")?
1494 .split(|c: char| c.is_whitespace() || c == ',')
1495 .filter(|part| !part.is_empty())
1496 .map(str::parse)
1497 .collect::<Result<_, _>>()
1498 .ok()?;
1499 match view_box[..] {
1500 [_, _, width, height] => Some((width.round() as usize, height.round() as usize)),
1501 _ => None,
1502 }
1503}
1504
1505fn attr<'a>(tag: &'a str, name: &str) -> Option<&'a str> {
1506 let mut from = 0;
1507 while let Some(i) = tag[from..].find(name).map(|i| from + i) {
1508 from = i + name.len();
1509 if !tag[..i].ends_with(|c: char| c.is_ascii_whitespace()) {
1510 continue;
1511 }
1512 let Some(value) = tag[from..].strip_prefix('=') else {
1513 continue;
1514 };
1515 let quote = value.chars().next().filter(|c| matches!(c, '"' | '\''))?;
1516 return value[1..].find(quote).map(|end| &value[1..1 + end]);
1517 }
1518 None
1519}
1520
1521fn base64(bytes: &[u8]) -> String {
1522 let mut encoded = String::with_capacity(bytes.len().div_ceil(3) * 4);
1523 for chunk in bytes.chunks(3) {
1524 let byte = |i: usize| chunk.get(i).copied().unwrap_or(0);
1525 let n = u32::from_be_bytes([0, byte(0), byte(1), byte(2)]);
1526 for i in 0..4 {
1527 if i <= chunk.len() {
1528 encoded.push(BASE64_CHARS[((n >> (18 - 6 * i)) & 63) as usize] as char);
1529 } else {
1530 encoded.push('=');
1531 }
1532 }
1533 }
1534 encoded
1535}
1536
1537fn ref_bar(
1538 repo: &RepoInfo,
1539 git_ref: &RefInfo,
1540 path: &str,
1541 repo_root: &str,
1542 commits: usize,
1543 current: &str,
1544) -> String {
1545 let mut bar = String::from(
1546 "<div class=\"box sticky flex items-center gap flex-wrap ref-bar\">\n<div class=\"ref-main\">\n",
1547 );
1548 bar.push_str(&ref_menu(
1549 repo,
1550 git_ref,
1551 repo_root,
1552 Tab::Tree,
1553 path,
1554 current,
1555 ));
1556 let mut parts = vec![(repo.name.as_str(), git_ref.dir.clone())];
1557 for part in path.split('/').filter(|p| !p.is_empty()) {
1558 let tree_path = format!("{}/{part}", parts[parts.len() - 1].1);
1559 parts.push((part, tree_path));
1560 }
1561 let links: Vec<(String, String)> = parts
1562 .iter()
1563 .map(|(part, tree_path)| {
1564 (
1565 format!("{repo_root}{}", Tab::Tree.href(tree_path)),
1566 escape_str(part),
1567 )
1568 })
1569 .collect();
1570 if let [parents @ .., (_, name)] = links.as_slice() {
1571 let last = format!("<span class=\"font-bold\">{name}</span>\n");
1572 match parents {
1573 [] => bar.push_str(&last),
1574 [(href, repo_name), folders @ ..] => {
1575 bar.push_str(&format!(
1576 "<a class=\"ref-repo\" href=\"{href}\">{}</a>\n<span>/</span>\n",
1577 fit_name(repo_name)
1578 ));
1579 if folders.is_empty() {
1580 bar.push_str(&last);
1581 } else {
1582 write_path_layers(&mut bar, folders, &last);
1583 }
1584 }
1585 }
1586 }
1587 bar.push_str("</div>\n");
1588 bar.push_str(&format!(
1589 "<a class=\"ref-bar-commits\" href=\"{repo_root}{}\">{}</a>\n</div>\n",
1590 Tab::Commits.href(&git_ref.dir),
1591 commit_count(commits)
1592 ));
1593 bar
1594}
1595
1596fn write_path_layers(body: &mut String, folders: &[(String, String)], last: &str) {
1597 body.push_str("<div class=\"ref-path\">\n");
1598 for hidden in (0..=folders.len()).rev() {
1599 let mut crumbs = Vec::new();
1600 let tabindex = if hidden > 0 { " tabindex=\"-1\"" } else { "" };
1601 if let Some((href, name)) = folders[..hidden].last() {
1602 crumbs.push(format!(
1603 "<a{tabindex} href=\"{href}\" title=\"{name}\" aria-label=\"folders up to {name}\">…</a>\n"
1604 ));
1605 }
1606 for (href, name) in &folders[hidden..] {
1607 crumbs.push(format!("<a{tabindex} href=\"{href}\">{name}</a>\n"));
1608 }
1609 crumbs.push(last.to_string());
1610 let (class, strut) = if hidden == folders.len() {
1611 (" last", "")
1612 } else {
1613 ("", "<span class=\"ref-strut\"></span>\n")
1614 };
1615 let aria = if hidden > 0 {
1616 " aria-hidden=\"true\""
1617 } else {
1618 ""
1619 };
1620 body.push_str(&format!(
1621 "<div class=\"ref-layer{class}\"{aria}>\n{strut}<div class=\"ref-crumbs\">\n{}</div>\n</div>\n",
1622 crumbs.join("<span>/</span>\n")
1623 ));
1624 }
1625 body.push_str("</div>\n");
1626}
1627
1628fn fit_name(name: &str) -> String {
1629 format!(
1630 "<span class=\"fit-name\"><span class=\"fit-full\"><i>​</i><span>{name}</span></span><span class=\"fit-cut\" aria-hidden=\"true\"><span class=\"truncate\">{name}</span><span class=\"fit-dots\">…</span></span></span>"
1631 )
1632}
1633
1634fn commit_count(commits: usize) -> String {
1635 let s = if commits == 1 { "" } else { "s" };
1636 format!("<span class=\"font-bold\">{commits}</span> commit{s}")
1637}
1638
1639fn menu_target(git_ref: &RefInfo, path: &str) -> (String, bool) {
1640 if find_file(git_ref, path).is_some() {
1641 return (blob_href(git_ref, path), true);
1642 }
1643 let mut dir = path;
1644 while !dir.is_empty() && !git_ref.dirs.contains_key(dir) {
1645 dir = dir.rsplit_once('/').map_or("", |(parent, _)| parent);
1646 }
1647 (Tab::Tree.href(&join_path(&git_ref.dir, dir)), dir == path)
1648}
1649
1650fn ref_menu(
1651 repo: &RepoInfo,
1652 git_ref: &RefInfo,
1653 repo_root: &str,
1654 tab: Tab,
1655 path: &str,
1656 current: &str,
1657) -> String {
1658 let name = escape_str(&git_ref.name);
1659 let label = match tab {
1660 Tab::Tree => fit_name(&name),
1661 _ => format!("<span class=\"truncate\">{name}</span>"),
1662 };
1663 let mut menu = format!(
1664 "\
1665<div class=\"ref-menu\">\n\
1666<button type=\"button\" class=\"ref-btn\" popovertarget=\"ref-menu\" aria-label=\"{name}, switch branch or tag\">{}{label}{}{}</button>\n\
1667<div class=\"ref-menu-list\" id=\"ref-menu\" popover>\n\
1668",
1669 ref_icon(git_ref),
1670 icon("chevron-down"),
1671 icon("chevron-up")
1672 );
1673 let list = |class: &str, refs: &[RefInfo]| -> String {
1674 let long = if refs.len() > REF_MENU_ROWS {
1675 " long"
1676 } else {
1677 ""
1678 };
1679 let entries: String = refs
1680 .iter()
1681 .map(|r| {
1682 let active = if r.dir == git_ref.dir {
1683 format!(" aria-current=\"{current}\"")
1684 } else {
1685 String::new()
1686 };
1687 let (href, found) = match tab {
1688 Tab::Tree => menu_target(r, path),
1689 _ => (tab.href(&r.dir), true),
1690 };
1691 let kind = if r.is_tag() {
1692 "tag"
1693 } else {
1694 "branch"
1695 };
1696 let (missing, title) = if found {
1697 ("", String::new())
1698 } else {
1699 (" missing", format!(" title=\"not in this {kind}\""))
1700 };
1701 format!(
1702 "<a class=\"flex items-center gap{missing}\"{title}{active} href=\"{repo_root}{href}\">{}{}</a>\n",
1703 ref_icon(r),
1704 escape_str(&r.name)
1705 )
1706 })
1707 .collect();
1708 format!("<div class=\"{class} buttons{long}\">\n{entries}</div>\n")
1709 };
1710 if !repo.tags.is_empty() {
1711 let (branches, tags) = if git_ref.is_tag() {
1712 ("", " checked")
1713 } else {
1714 (" checked", "")
1715 };
1716 menu.push_str(&format!(
1717 "\
1718<input type=\"radio\" class=\"vh\" name=\"ref-kind\" id=\"ref-branches\"{branches}>\n\
1719<input type=\"radio\" class=\"vh\" name=\"ref-kind\" id=\"ref-tags\"{tags}>\n\
1720<div class=\"ref-kinds buttons flex\"><label for=\"ref-branches\">branches</label><label for=\"ref-tags\">tags</label></div>\n\
1721{}\
1722",
1723 list("ref-tags", &repo.tags)
1724 ));
1725 }
1726 menu.push_str(&list("ref-branches", &repo.branches));
1727 menu.push_str("</div>\n</div>\n");
1728 menu
1729}
1730
1731fn write_code(body: &mut String, content: &[u8]) {
1732 let text = escape_str(&String::from_utf8_lossy(content));
1733 let lines: Vec<&str> = text.split_inclusive('\n').collect();
1734 let width = lines.len().to_string().len();
1735 let _ = write!(
1736 body,
1737 "<pre class=\"chroma\" style=\"--ln: {width}ch\"><code>"
1738 );
1739 for (i, line) in lines.iter().enumerate() {
1740 let n = i + 1;
1741 let (text, newline) = match line.strip_suffix('\n') {
1742 Some(text) => (text, "\n"),
1743 None => (*line, ""),
1744 };
1745 let _ = write!(
1746 body,
1747 "<a class=\"ln\" id=\"L{n}\" href=\"#L{n}\" tabindex=\"-1\">{n:>width$}</a><span class=\"cl\">"
1748 );
1749 push_line(body, text);
1750 body.push_str("</span>");
1751 body.push_str(newline);
1752 }
1753 body.push_str("</code></pre>\n");
1754}
1755
1756fn push_line(body: &mut String, text: &str) {
1757 for (i, piece) in text.split('\r').enumerate() {
1758 if i > 0 && !piece.starts_with('\n') {
1759 body.push('\n');
1760 }
1761 body.push_str(piece);
1762 }
1763}
1764
1765fn write_listing(
1766 body: &mut String,
1767 git_ref: &RefInfo,
1768 dir: &Dir,
1769 repo_root: &str,
1770 tree_dir: &str,
1771 last: &HashMap<String, &CommitInfo>,
1772) {
1773 body.push_str("<div class=\"box p-0 joined\">\n");
1774 let head = if dir.path.is_empty() {
1775 commit_cells(repo_root, &git_ref.id, &git_ref.summary, &git_ref.date)
1776 } else {
1777 last_details(repo_root, last, &dir.path)
1778 };
1779 if !head.is_empty() {
1780 body.push_str(&format!(
1781 "<div class=\"flex items-center gap px row border-b last-commit\">\n{head}</div>\n"
1782 ));
1783 }
1784 if !dir.path.is_empty() {
1785 body.push_str(&format!(
1786 "\
1787<div class=\"flex items-center gap-2 px row tree-row border-b up-row\">\n\
1788<div class=\"flex-1 tree-path flex items-center gap\">\n\
1789{}\n\
1790<a class=\"truncate row-link\" href=\"../\" title=\"parent folder\">..</a>\n\
1791</div>\n\
1792</div>\n\
1793",
1794 icon("file-directory")
1795 ));
1796 }
1797 for entry in &dir.entries {
1798 let name = &entry.name;
1799 let path = join_path(&dir.path, name);
1800 let link = |href: String, text: String| {
1801 format!(
1802 "<a class=\"truncate row-link\" href=\"{}\">{text}</a>",
1803 escape_str(&href)
1804 )
1805 };
1806 let leads = |text: String| match path_href(git_ref, repo_root, &path) {
1807 Some(href) => link(href, text),
1808 None => format!("<span class=\"truncate\">{text}</span>"),
1809 };
1810 let last_change = match last.get(&path) {
1811 Some(commit) => format!(
1812 "{}{}",
1813 summary_cell(repo_root, &commit.id, &commit.summary),
1814 date_cell(&commit.committer_date)
1815 ),
1816 None => {
1817 "<div class=\"flex flex-2 tree-commit\"></div>\n<div class=\"tree-date\"></div>\n"
1818 .to_string()
1819 }
1820 };
1821 let (icon_name, name) = if entry.is_dir {
1822 let href = percent_encode(&format!("{tree_dir}{name}/"));
1823 ("file-directory", link(href, escape_str(name)))
1824 } else if let Some(target) = &entry.link {
1825 let text = format!("{} → {}", escape_str(name), escape_str(target));
1826 ("file-symlink-file", leads(text))
1827 } else if let Some(commit) = &entry.commit {
1828 let text = format!("{} @ {}", escape_str(name), &commit[..7]);
1829 ("file-submodule", leads(text))
1830 } else {
1831 ("file", leads(escape_str(name)))
1832 };
1833 body.push_str(&format!(
1834 "\
1835<div class=\"flex items-center gap-2 px row tree-row border-b\">\n\
1836<div class=\"flex-1 tree-path flex items-center gap\">\n\
1837{}\n\
1838{name}\n\
1839</div>\n\
1840{last_change}\
1841</div>\n\
1842",
1843 icon(icon_name)
1844 ));
1845 }
1846 body.push_str("</div>\n");
1847}
1848
1849fn ref_labels(repo: &RepoInfo, id: &str, repo_root: &str, menus: &mut usize) -> String {
1850 let mut refs: Vec<&RefInfo> = repo
1851 .branches
1852 .iter()
1853 .chain(&repo.tags)
1854 .filter(|git_ref| git_ref.id == id)
1855 .collect();
1856 if refs.is_empty() {
1857 return String::new();
1858 }
1859 refs.sort_by(|a, b| RefInfo::newest_first(a, b));
1860 let link = |git_ref: &&RefInfo| {
1861 (
1862 format!("{repo_root}{}", Tab::Tree.href(&git_ref.dir)),
1863 format!("{}{}", ref_icon(git_ref), escape_str(&git_ref.name)),
1864 )
1865 };
1866 let chips: String = refs
1867 .iter()
1868 .take(REF_CHIPS)
1869 .map(|git_ref| {
1870 let (href, text) = link(git_ref);
1871 format!("<a class=\"chip flex\" href=\"{href}\"><code>{text}</code></a>\n")
1872 })
1873 .collect();
1874 let entries: String = refs
1875 .iter()
1876 .map(|git_ref| {
1877 let (href, text) = link(git_ref);
1878 format!("<a class=\"flex items-center gap\" href=\"{href}\">{text}</a>\n")
1879 })
1880 .collect();
1881 *menus += 1;
1882 let n = *menus;
1883 let s = if refs.len() == 1 { "" } else { "s" };
1884 format!(
1885 "\
1886<div class=\"chips text-xs\">\n{chips}</div>\n\
1887<div class=\"ref-menu ref-more text-xs\">\n\
1888<button type=\"button\" class=\"ref-btn\" popovertarget=\"ref-more-{n}\">{} ref{s}{}{}</button>\n\
1889<div class=\"ref-menu-list buttons\" id=\"ref-more-{n}\" popover>\n{entries}</div>\n\
1890</div>\n\
1891",
1892 refs.len(),
1893 icon("chevron-down"),
1894 icon("chevron-up")
1895 )
1896}
1897
1898fn write_commit_row(
1899 body: &mut String,
1900 commit: &CommitInfo,
1901 stat: Option<&str>,
1902 labels: &str,
1903 repo_root: &str,
1904 joined: &str,
1905 date: &str,
1906) {
1907 let href = format!("{repo_root}commits/{}", commit.id);
1908 let stat = stat
1909 .map(|stat| format!("<div class=\"commit-stat flex-1\"><div>{stat}</div></div>\n"))
1910 .unwrap_or_default();
1911 body.push_str(&format!(
1912 "\
1913<div class=\"box m-0 row commit-row{joined}\">\n\
1914<div class=\"flex flex-wrap items-center gap text-xs\">\n\
1915<a href=\"{href}\" class=\"commit-id row-link\">{}{}</a>\n\
1916<div class=\"flex items-center commit-by\">\n\
1917<span class=\"truncate\">{}</span>\n\
1918<span> · </span>\n\
1919<span>{date}</span>\n\
1920</div>\n\
1921{stat}\
1922</div>\n\
1923<div class=\"flex items-center commit-line\">\n\
1924<div class=\"flex commit-summary\"><a class=\"truncate row-link\" href=\"{href}\">{}</a></div>\n\
1925{labels}\
1926</div>\n\
1927</div>\n\
1928",
1929 icon("git-commit"),
1930 &commit.id[..7],
1931 escape_str(&commit.author_name),
1932 escape_str(&commit.summary)
1933 ));
1934}
1935
1936fn write_briefs(body: &mut String, repo: &RepoInfo) {
1937 body.push_str("<div>\n<header class=\"subtitle\">\n<h2>commits</h2>\n</header>\n");
1938 let mut menus = 1;
1939 for (n, commit) in repo.commit_list.iter().take(BRIEF_COUNT).enumerate() {
1940 let joined = if n == 0 { "" } else { " joined" };
1941 let labels = ref_labels(repo, &commit.id, "", &mut menus);
1942 let date = commit.committer_date.format(DATE).to_string();
1943 write_commit_row(body, commit, None, &labels, "", joined, &date);
1944 }
1945 body.push_str(&format!(
1946 "\
1947<div class=\"box m-0 joined row side-all px\">\n\
1948<a class=\"row-link\" href=\"{}\">all commits</a>\n\
1949</div>\n\
1950</div>\n\
1951",
1952 Tab::Commits.href(&repo.head_dir)
1953 ));
1954}