steid

@jamesgill /

Rust43.6 KBCode·Blame·History·Raw
1//! One commit, and the comparison of two revisions.
2//!
3//! Three routes sharing one renderer: `/commits/{sha}` shows what a commit changed,
4//! `/compare` asks which two revisions, and `/compare/{base}...{head}` answers.
5//!
6//! The diff renderer is the reason they live together. A commit's diff and a
7//! comparison's diff are the same thing — [`Diff`] — and drawing them twice would be
8//! two places for the line numbering to be subtly wrong in.
9//!
10//! # The compare URL
11//!
12//! `{base}...{head}` in one path segment, each half percent-encoded exactly as the tree
13//! pages encode a revision, so `feature/login` stays inside its half. The separator is
14//! unambiguous because [`RefName`] refuses `..` outright — a revision cannot contain
15//! two consecutive dots, so three of them can only be the separator. It is also the
16//! spelling git itself uses for merge-base semantics, which is what the page does.
17//!
18//! The form cannot build that URL: a GET form submits query parameters, not path
19//! segments, and Steid does not require JavaScript. So the form posts nowhere — it GETs
20//! `/compare?base=…&head=…`, and that page redirects to the path form. The shareable
21//! URL is therefore always the path one, which is what the branches page links to.
22
23use topcoat::{
24 Result,
25 context::Cx,
26 icon::{icon, iconify::iconify_icon},
27 router::{
28 error::{RouterErrorExt, not_found, redirect},
29 page, path_param, query_params,
30 },
31 view::{Unescaped, attributes, component, view},
32};
33
34use crate::{
35 application::{
36 Compared, Comparison, Diff, DiffLine, FileChange, FileDiff, FileStat, LineKind,
37 MAX_FILE_DIFF_LINES, RefList, RepoView, Stores, compare_revisions, list_refs, view_commit,
38 },
39 components::{
40 button::{ButtonSize, ButtonVariant, button_variants},
41 input::input,
42 label::label,
43 },
44 domain::{CommitDetail, RefName, RepoPath},
45};
46
47use crate::infrastructure::highlight;
48
49use super::{
50 browse::commit_log,
51 context::{current_actor, memberships, orgs, queries, repos, server_error, timed_out},
52 format::{ago, timestamp},
53 layout::wide,
54 paging::{Pages, list_pages, requested_page, showing},
55 pulls::new_pull_url,
56 repo::{Tab, repo_for, repo_header},
57 urls::{encode, tree_url},
58};
59
60/// `{sha}` from the path: a full or abbreviated object id, or any other revision.
61#[path_param]
62struct Sha(str);
63
64/// `{spec}` from the path: `base...head`, each half already percent-decoded.
65#[path_param]
66struct Spec(str);
67
68/// `?page=N` on a comparison's commit list. The diff below it does not page — it is
69/// the whole range either way — so the number only moves the list.
70#[query_params(error = bad_request)]
71struct PageQuery {
72 page: Option<String>,
73}
74
75/// What the compare form submits, before it is turned into a path.
76#[query_params(error = bad_request)]
77struct CompareQuery {
78 base: Option<String>,
79 head: Option<String>,
80}
81
82// --- Routes -----------------------------------------------------------------------
83
84#[page("/{handle}/repos/{name}/commits/{sha}")]
85async fn commit_page(cx: &Cx) -> Result {
86 // A malformed revision is a page that does not exist, the same reasoning the tree
87 // pages apply to theirs.
88 let rev = RefName::new(path_param::<Sha>(cx)).map_err(|_| not_found())?;
89
90 view! { commit_view(rev: rev) }
91}
92
93#[page("/{handle}/repos/{name}/compare")]
94async fn compare_form_page(cx: &Cx) -> Result {
95 let repo = repo_for(cx).await?;
96 let submitted = query_params::<CompareQuery>(cx)?;
97
98 // The form's own submission, on its way to the URL it should have been able to
99 // target directly. A 307 is right here: this is a GET, so preserving the method is
100 // exactly what is wanted.
101 if let (Some(base), Some(head)) = (&submitted.base, &submitted.head) {
102 let (base, head) = (base.trim(), head.trim());
103
104 if !base.is_empty() && !head.is_empty() {
105 return Err(redirect(&compare_url(
106 repo.handle.as_str(),
107 repo.name.as_str(),
108 base,
109 head,
110 ))
111 .into());
112 }
113 }
114
115 let refs = refs_for(cx, &repo).await?;
116 let default = default_base(cx, &repo).await?;
117
118 view! {
119 wide(
120 repo_header(repo: &repo, rev: "", active: Tab::Code)
121 compare_form(repo: &repo, base: default.as_str(), head: "", refs: &refs, error: "")
122 )
123 }
124}
125
126#[page("/{handle}/repos/{name}/compare/{spec}")]
127async fn compare_page(cx: &Cx) -> Result {
128 let spec = path_param::<Spec>(cx);
129
130 // Three dots, not two: `RefName` refuses `..` in a revision, so the only way this
131 // separator can appear is as the separator.
132 let Some((base, head)) = spec.split_once("...") else {
133 return Err(not_found().into());
134 };
135
136 let (Ok(base), Ok(head)) = (RefName::new(base), RefName::new(head)) else {
137 return Err(not_found().into());
138 };
139
140 view! { comparison_view(base: base, head: head) }
141}
142
143// --- The commit page --------------------------------------------------------------
144
145/// A component rather than a plain function because `view!` needs the request context
146/// in scope — the same reason the browse pages are components.
147#[component]
148async fn commit_view(cx: &Cx, rev: RefName) -> Result {
149 let repo = repo_for(cx).await?;
150
151 let loaded = view_commit(
152 &repo.handle,
153 &repo.name,
154 &rev,
155 &current_actor(cx).await?,
156 &Stores::new(&orgs(cx), &memberships(cx), &repos(cx)),
157 &queries(cx),
158 )
159 .await;
160
161 let page = match unwrap_page(loaded)? {
162 Some(page) => page,
163 None => {
164 return view! {
165 wide(
166 repo_header(repo: &repo, rev: rev.as_str(), active: Tab::Commits)
167 took_too_long()
168 )
169 };
170 }
171 };
172
173 let handle = repo.handle.as_str();
174 let name = repo.name.as_str();
175 // The commit's own id, not the revision the URL used: a branch name in the header's
176 // links would send someone to a different commit tomorrow.
177 let at = page.commit.id.as_str();
178
179 view! {
180 wide(
181 repo_header(repo: &repo, rev: at, active: Tab::Commits)
182 commit_summary(handle: handle, name: name, commit: &page.commit)
183 diff_view(handle: handle, name: name, rev: at, diff: &page.diff)
184 )
185 }
186}
187
188/// The commit itself: what it says, who made it, and where it sits in the history.
189#[component]
190async fn commit_summary(handle: &str, name: &str, commit: &CommitDetail) -> Result {
191 let sha = commit.id.as_str();
192
193 view! {
194 <article class="mb-4 rounded-lg border border-border px-4 py-3">
195 <h2 class="text-base font-medium">(&commit.summary)</h2>
196
197 if !commit.body.is_empty() {
198 // Preformatted, because a commit body is written for a fixed-width
199 // reader — lists, wrapped prose, pasted output — and reflowing it
200 // rewrites what somebody wrote. It wraps rather than scrolls so a long
201 // line does not widen the page.
202 <pre class="mt-2 whitespace-pre-wrap font-mono text-xs leading-relaxed text-muted-foreground">(&commit.body)</pre>
203 }
204
205 <div class="mt-3 flex flex-wrap items-center gap-x-3 gap-y-1.5 border-t border-border pt-2.5 text-xs text-muted-foreground">
206 <span>
207 <span class="text-foreground">(&commit.author_name)</span>
208 " authored "
209 <span title=(timestamp(commit.authored_at))>(ago(commit.authored_at))</span>
210 </span>
211
212 // Named only when it differs. On an ordinary commit the two are the
213 // same person and saying it twice is noise.
214 if commit.has_distinct_committer() {
215 <span>
216 <span class="text-foreground">(&commit.committer_name)</span>
217 " committed "
218 <span title=(timestamp(commit.committed_at))>(ago(commit.committed_at))</span>
219 </span>
220 }
221
222 <span class="ml-auto flex flex-wrap items-center gap-x-3 gap-y-1.5">
223 match commit.parents.len() {
224 0 => <span>"root commit"</span>,
225 _ => <span class="flex items-center gap-1.5">
226 (if commit.parents.len() == 1 { "parent" } else { "parents" })
227 for parent in &commit.parents {
228 <a
229 href=(commit_url(handle, name, parent.as_str()))
230 class="font-mono hover:text-foreground"
231 >(parent.short())</a>
232 }
233 </span>,
234 }
235
236 <a
237 href=(tree_url(handle, name, &RefName::from_trusted(sha), &RepoPath::root()))
238 class="inline-flex items-center gap-1 hover:text-foreground"
239 >
240 icon(data: iconify_icon!("feather:folder"), attrs: attributes! {
241 class="size-3.5"
242 })
243 "Browse files"
244 </a>
245
246 // The full id, never the abbreviation: this is the page you copy a
247 // sha from, and seven characters is not a thing you can paste into
248 // `git show` with confidence on a large repository.
249 <code class="font-mono text-foreground">(sha)</code>
250 </span>
251 </div>
252 </article>
253 }
254}
255
256// --- The compare pages ------------------------------------------------------------
257
258#[component]
259async fn comparison_view(cx: &Cx, base: RefName, head: RefName) -> Result {
260 let repo = repo_for(cx).await?;
261 let page = requested_page(query_params::<PageQuery>(cx)?.page.as_deref());
262
263 let loaded = compare_revisions(
264 &repo.handle,
265 &repo.name,
266 &base,
267 &head,
268 page,
269 &current_actor(cx).await?,
270 &Stores::new(&orgs(cx), &memberships(cx), &repos(cx)),
271 &queries(cx),
272 )
273 .await;
274
275 let handle = repo.handle.as_str();
276 let name = repo.name.as_str();
277
278 let Some(compared) = unwrap_page(loaded)? else {
279 return view! {
280 wide(
281 repo_header(repo: &repo, rev: "", active: Tab::Code)
282 took_too_long()
283 )
284 };
285 };
286
287 // Two states want the ref list and it costs a whole `git` process, so the states
288 // that want neither still pay nothing. The form's datalist is one; the other is a
289 // comparison that could become a pull request, where the list is what says whether
290 // these two revisions are **branches** — a pull request merges branches, and a
291 // comparison of two shas has nothing for it to move.
292 let refs = match &compared {
293 Compared::UnknownRef { .. } => refs_for(cx, &repo).await?,
294 Compared::Ready(comparison) if !comparison.head_is_behind() => refs_for(cx, &repo).await?,
295 _ => RefList::default(),
296 };
297
298 // Offered only to the owner, who is the only person whose submission would be
299 // accepted, and only between two branches with something to bring across.
300 let branches = |rev: &RefName| refs.branches.iter().any(|branch| branch == rev);
301 let openable = repo.viewer_is_owner && branches(&base) && branches(&head);
302
303 // Built before the view, not inside it: a `format!` in an argument position is a
304 // temporary that the borrow it produces outlives.
305 let unknown = match &compared {
306 Compared::UnknownRef { rev } => {
307 format!("There is no branch, tag or commit called {rev} in this repository.")
308 }
309 _ => String::new(),
310 };
311
312 view! {
313 wide(
314 repo_header(repo: &repo, rev: "", active: Tab::Code)
315
316 match &compared {
317 Compared::UnknownRef { .. } => compare_form(
318 repo: &repo,
319 base: base.as_str(),
320 head: head.as_str(),
321 refs: &refs,
322 error: unknown.as_str(),
323 ),
324 Compared::Identical => {
325 compare_bar(handle: handle, name: name, base: base.as_str(), head: head.as_str())
326 <p class="rounded-lg border border-border px-4 py-10 text-center text-sm text-muted-foreground">
327 "Nothing to compare. These two revisions are the same commit."
328 </p>
329 }
330 Compared::Unrelated => {
331 compare_bar(handle: handle, name: name, base: base.as_str(), head: head.as_str())
332 <p class="rounded-lg border border-border px-4 py-10 text-center text-sm text-muted-foreground">
333 "These two revisions share no history, so there is nothing to compare them against."
334 </p>
335 }
336 Compared::Ready(comparison) => comparison_body(
337 handle: handle,
338 name: name,
339 comparison: comparison.as_ref(),
340 openable: openable,
341 ),
342 }
343 )
344 }
345}
346
347/// A successful comparison: what it is, what it adds, and what that changes.
348#[component]
349async fn comparison_body(
350 handle: &str,
351 name: &str,
352 comparison: &Comparison,
353 /// Whether to offer a pull request: the viewer owns the repository, both revisions
354 /// are branches of it, and there is something to bring across.
355 openable: bool,
356) -> Result {
357 let behind = comparison.head_is_behind();
358 let commits = &comparison.commits;
359 let sentence = showing(
360 commits.offset(),
361 commits.items.len(),
362 commits.total,
363 "commits",
364 );
365 // The revisions are a path segment, so `?page=` is the whole query string — and the
366 // diff below the list is unaffected by it.
367 let pages = Pages::numbered(commits.page, commits.pages, |page| {
368 format!(
369 "{}?page={page}",
370 compare_url(
371 handle,
372 name,
373 comparison.base.as_str(),
374 comparison.head.as_str()
375 )
376 )
377 });
378
379 view! {
380 compare_bar(
381 handle: handle,
382 name: name,
383 base: comparison.base.as_str(),
384 head: comparison.head.as_str(),
385 )
386
387 if behind {
388 // Not an error — the comparison is simply empty, and the one they meant is
389 // one click away.
390 <p class="mb-4 rounded-lg border border-border px-4 py-4 text-sm text-muted-foreground">
391 <span class="font-mono text-foreground">(comparison.head.as_str())</span>
392 " is already contained in "
393 <span class="font-mono text-foreground">(comparison.base.as_str())</span>
394 ", so it adds nothing. "
395 <a
396 href=(compare_url(handle, name, comparison.head.as_str(), comparison.base.as_str()))
397 class="text-primary hover:underline"
398 >"Compare them the other way round"</a>
399 "?"
400 </p>
401 } else {
402 <div class="mb-2 flex flex-wrap items-baseline gap-x-2 text-xs text-muted-foreground">
403 <span class="font-mono text-foreground">
404 (counted(comparison.total_commits(), "commit", "commits"))
405 </span>
406 " to bring across, from merge base "
407 <a
408 href=(commit_url(handle, name, comparison.merge_base.as_str()))
409 class="font-mono hover:text-foreground"
410 >(comparison.merge_base.short())</a>
411
412 // The way from "what does this branch add" to "let us land it", which is
413 // the question the compare page leaves you holding. `base` is the target
414 // and `head` the source: a comparison asks what head adds to base, and a
415 // pull request proposes merging exactly that.
416 if openable {
417 <a
418 href=(new_pull_url(
419 handle,
420 name,
421 comparison.head.as_str(),
422 comparison.base.as_str(),
423 ))
424 class=(format!(
425 "ml-auto {}",
426 button_variants(ButtonVariant::Primary, ButtonSize::Sm)
427 ))
428 >"Create pull request"</a>
429 }
430 </div>
431
432 commit_log(handle: handle, name: name, commits: &comparison.commits.items)
433 list_pages(summary: sentence.as_str(), pages: &pages)
434
435 <div class="mt-4">
436 diff_view(
437 handle: handle,
438 name: name,
439 rev: comparison.head_id.as_str(),
440 diff: &comparison.diff,
441 )
442 </div>
443 }
444 }
445}
446
447/// The two revisions, restated, with the way to swap them.
448#[component]
449async fn compare_bar(handle: &str, name: &str, base: &str, head: &str) -> Result {
450 view! {
451 <div class="mb-3 flex flex-wrap items-center gap-2 text-sm">
452 <span class="rounded-md border border-border px-2 py-0.5 font-mono text-xs">(base)</span>
453 <span class="text-muted-foreground">"←"</span>
454 <span class="rounded-md border border-border px-2 py-0.5 font-mono text-xs">(head)</span>
455 <a
456 href=(compare_url(handle, name, head, base))
457 class="inline-flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground"
458 >
459 icon(data: iconify_icon!("feather:repeat"), attrs: attributes! { class="size-3.5" })
460 "Swap"
461 </a>
462 <a
463 href=(format!("/{handle}/repos/{name}/compare"))
464 class="ml-auto text-xs text-muted-foreground hover:text-foreground"
465 >"Compare something else"</a>
466 </div>
467 }
468}
469
470/// Which two revisions to compare.
471///
472/// Two plain text inputs with a `<datalist>` rather than two `<select>`s: a revision
473/// need not be a branch or a tag — a sha is a perfectly good answer, and a select would
474/// make it unsayable. The datalist gives the common case autocompletion and leaves the
475/// rest typeable.
476#[component]
477async fn compare_form(
478 repo: &RepoView,
479 base: &str,
480 head: &str,
481 refs: &RefList,
482 error: &str,
483) -> Result {
484 let handle = repo.handle.as_str();
485 let name = repo.name.as_str();
486 let names: Vec<&str> = refs
487 .branches
488 .iter()
489 .chain(&refs.tags)
490 .map(RefName::as_str)
491 .collect();
492
493 view! {
494 <form method="get" action=(format!("/{handle}/repos/{name}/compare")) class="max-w-2xl">
495 <h2 class="text-sm font-medium">"Compare revisions"</h2>
496 <p class="mt-1 text-xs text-muted-foreground">
497 "What does the second revision add to the first? A branch, a tag or a commit id."
498 </p>
499
500 if !error.is_empty() {
501 <p class="mt-3 rounded-lg border border-destructive px-3 py-2 text-xs text-destructive">
502 (error)
503 </p>
504 }
505
506 <div class="mt-4 flex flex-wrap items-end gap-3">
507 <div class="flex min-w-48 flex-1 flex-col gap-1.5">
508 label(attrs: attributes! { for="base" class="text-xs" }, "Base")
509 input(attrs: attributes! {
510 id="base" name="base" list="compare-refs" required=(true)
511 autocomplete="off" spellcheck="false" class="font-mono"
512 value=(base) placeholder="main"
513 })
514 </div>
515
516 <span class="pb-2.5 font-mono text-sm text-muted-foreground">"..."</span>
517
518 <div class="flex min-w-48 flex-1 flex-col gap-1.5">
519 label(attrs: attributes! { for="head" class="text-xs" }, "Compare")
520 input(attrs: attributes! {
521 id="head" name="head" list="compare-refs" required=(true)
522 autocomplete="off" spellcheck="false" class="font-mono"
523 value=(head) placeholder="a branch, tag or sha"
524 })
525 </div>
526
527 <button
528 type="submit"
529 class=(button_variants(ButtonVariant::Primary, ButtonSize::Md))
530 >"Compare"</button>
531 </div>
532
533 <datalist id="compare-refs">
534 for git_ref in &names {
535 <option value=(*git_ref)></option>
536 }
537 </datalist>
538 </form>
539 }
540}
541
542// --- The diff ---------------------------------------------------------------------
543
544/// A whole diff: the summary line, then one panel per file.
545#[component]
546pub(super) async fn diff_view(handle: &str, name: &str, rev: &str, diff: &Diff) -> Result {
547 view! {
548 if diff.is_empty() {
549 <p class="rounded-lg border border-border px-4 py-10 text-center text-sm text-muted-foreground">
550 "This commit changed no files."
551 </p>
552 } else {
553 diff_stats(diff: diff)
554
555 if diff.truncated {
556 // The counts are still real — they come from git's own numstat, which
557 // is written before the patch and therefore survives the cap. Only the
558 // lines are missing.
559 <p class="mb-2 rounded-lg border border-border px-4 py-3 text-xs text-muted-foreground">
560 "This diff is too large to display. Every changed file is listed below with its counts; "
561 "clone the repository or run "
562 <code class="font-mono text-foreground">"git show"</code>
563 " to read the patch."
564 </p>
565
566 <ul class="divide-y divide-border rounded-lg border border-border">
567 for file in &diff.stats {
568 <li class="flex flex-wrap items-center gap-x-3 gap-y-1 px-4 py-2">
569 stat_row(file: file)
570 <span class="text-xs text-muted-foreground">"Diff too large to display"</span>
571 </li>
572 }
573 </ul>
574 } else {
575 for file in &diff.files {
576 file_diff(handle: handle, name: name, rev: rev, file: file)
577 }
578 }
579 }
580 }
581}
582
583/// `N files changed · +a −b`.
584///
585/// The two numbers are the only place on the page the success and destructive tokens
586/// appear as text. That is deliberate: they are the summary of the whole commit, and
587/// colouring anything else the same way would dilute them.
588#[component]
589async fn diff_stats(diff: &Diff) -> Result {
590 view! {
591 <p class="mb-2 flex flex-wrap items-center gap-x-3 text-xs text-muted-foreground">
592 <span>(counted(diff.files_changed(), "file changed", "files changed"))</span>
593 <span class="font-mono">
594 <span class="text-success">"+" (diff.added().to_string())</span>
595 " "
596 <span class="text-destructive">"−" (diff.removed().to_string())</span>
597 </span>
598 </p>
599 }
600}
601
602/// One file's path and counts, as the truncated listing shows it.
603#[component]
604async fn stat_row(file: &FileStat) -> Result {
605 view! {
606 <span class="min-w-0 truncate font-mono text-xs">
607 match &file.old_path {
608 Some(old) => <span class="text-muted-foreground">(old) " → "</span>,
609 None => "",
610 }
611 (&file.path)
612 </span>
613 <span class="ml-auto shrink-0 font-mono text-xs">
614 match (file.added, file.removed) {
615 (Some(added), Some(removed)) => {
616 <span class="text-success">"+" (added.to_string())</span>
617 " "
618 <span class="text-destructive">"−" (removed.to_string())</span>
619 }
620 _ => <span class="text-muted-foreground">"binary"</span>,
621 }
622 </span>
623 }
624}
625
626/// One file: a header that stays put, then the lines.
627///
628/// The header is `sticky`, which is why this panel is not `overflow-hidden` — a hidden
629/// overflow makes an ancestor a scroll container and sticky then sticks to a box that
630/// never scrolls, which looks exactly like sticky being broken. The corners are rounded
631/// on the children instead.
632#[component]
633async fn file_diff(handle: &str, name: &str, rev: &str, file: &FileDiff) -> Result {
634 // One entry per row, in step with `file.rows`, so the view stays a single loop.
635 let highlighted = highlighted_rows(&file.path, &file.rows);
636
637 let blob = tree_url(
638 handle,
639 name,
640 &RefName::from_trusted(rev),
641 &RepoPath::from_trusted(file.path.as_str()),
642 );
643
644 view! {
645 <section class="mb-4 rounded-lg border border-border">
646 <div class="sticky top-0 z-10 flex flex-wrap items-center gap-x-3 gap-y-1 rounded-t-lg border-b border-border bg-surface px-4 py-2">
647 <span class="min-w-0 truncate font-mono text-xs">
648 match &file.old_path {
649 Some(old) => <span class="text-muted-foreground">(old) " → "</span>,
650 None => "",
651 }
652 (&file.path)
653 </span>
654
655 <span class="ml-auto flex shrink-0 items-center gap-3 text-xs">
656 if file.binary {
657 <span class="font-mono text-muted-foreground">"binary"</span>
658 } else {
659 <span class="font-mono">
660 <span class="text-success">"+" (file.added.to_string())</span>
661 " "
662 <span class="text-destructive">"−" (file.removed.to_string())</span>
663 </span>
664 }
665 if file.change != FileChange::Deleted {
666 <a href=(&blob) class="text-muted-foreground hover:text-foreground">"View file"</a>
667 }
668 </span>
669 </div>
670
671 if file.binary {
672 <p class="px-4 py-5 text-center text-sm text-muted-foreground">
673 "Binary file changed"
674 </p>
675 } else if file.rows.is_empty() {
676 // A mode change, or a rename with no edit: git wrote a header and no
677 // hunks, and saying so is better than an empty panel.
678 <p class="px-4 py-5 text-center text-sm text-muted-foreground">
679 "No line changes."
680 </p>
681 } else {
682 <div class="overflow-x-auto rounded-b-lg">
683 <table class="w-full border-collapse font-mono text-xs leading-relaxed">
684 <tbody>
685 for (row, code) in file.rows.iter().zip(highlighted) {
686 diff_row(row: row, code: code)
687 }
688 </tbody>
689 </table>
690 </div>
691
692 if file.truncated() {
693 <p class="border-t border-border px-4 py-2.5 text-xs text-muted-foreground">
694 "Showing the first " (MAX_FILE_DIFF_LINES.to_string()) " lines of "
695 (file.total_rows.to_string()) ". "
696 <a href=(&blob) class="text-primary hover:underline">"View the whole file"</a>
697 " at this revision."
698 </p>
699 }
700 }
701 </section>
702 }
703}
704
705/// One line of a diff, as one table row.
706///
707/// A row per line, rather than a `<pre>` with a gutter, so the two line numbers stay
708/// aligned with the line they belong to when the content scrolls sideways — the same
709/// reasoning the blob view uses for its single gutter.
710///
711/// The tints are classes defined in `styles.css`, not Tailwind utilities: they are a
712/// token at low alpha, which is a colour Tailwind has no utility for and which must not
713/// be written out as a literal.
714#[component]
715async fn diff_row(row: &DiffLine, code: Option<String>) -> Result {
716 let (line_class, gutter_class, marker) = match row.kind {
717 LineKind::Added => ("diff-line-add", "diff-gutter-add", "+"),
718 LineKind::Removed => ("diff-line-del", "diff-gutter-del", "−"),
719 LineKind::Hunk => ("diff-line-hunk", "", ""),
720 LineKind::Note => ("", "", ""),
721 LineKind::Context => ("", "", " "),
722 };
723 let number = |value: Option<u32>| value.map(|value| value.to_string()).unwrap_or_default();
724
725 view! {
726 <tr class=(line_class)>
727 <td class=(format!(
728 "w-px select-none px-2 text-right align-top text-muted-foreground {gutter_class}"
729 ))>(number(row.old))</td>
730 <td class=(format!(
731 "w-px select-none border-r border-border px-2 text-right align-top text-muted-foreground {gutter_class}"
732 ))>(number(row.new))</td>
733 <td class="whitespace-pre px-3 align-top">
734 match row.kind {
735 // The hunk header and the "no newline" note are git's words about
736 // the file, not lines of it, so they are muted and unmarked.
737 LineKind::Hunk | LineKind::Note => <span class="text-muted-foreground">(&row.text)</span>,
738 _ => {
739 <span class="select-none text-muted-foreground">(marker)</span>
740 // An empty line has no height, and a diff row must keep the
741 // one the row above it has — so the space wins over an empty
742 // fragment whether or not the file was highlighted.
743 match code {
744 _ if row.text.is_empty() => (" "),
745 // Markup this codebase wrote: `highlight` escapes the
746 // source itself and emits nothing but spans.
747 Some(html) => (Unescaped::new_unchecked(html)),
748 None => (row.text.as_str()),
749 }
750 }
751 }
752 </td>
753 </tr>
754 }
755}
756
757/// Highlighted markup for each row of one file's diff, or `None` where a row is
758/// rendered as the plain text it always was.
759///
760/// **Hunk by hunk, and each hunk twice.** A hunk is highlighted as two standalone
761/// snippets — the file as it was on the left of the change, and as it is on the right —
762/// because interleaving a removed line with the added line that replaced it hands the
763/// parser the same code twice and colours the second copy as a continuation of the
764/// first. Removed rows take their markup from the old snippet, added rows from the new,
765/// and a context row from the new, where the two agree by definition.
766///
767/// A renamed file is highlighted by its **new** path, which is [`FileDiff::path`]: that
768/// is the name the lines have now, and the one the reader will open.
769///
770/// Every failure is `None` and therefore plain text: no grammar for the path, a parser
771/// that gave up, a file past the highlighting byte cap. Nothing on the page says so, in
772/// the last case deliberately — a diff that large is already announcing its own size,
773/// and a second notice about colour would be noise on top of it.
774fn highlighted_rows(path: &str, rows: &[DiffLine]) -> Vec<Option<String>> {
775 let mut highlighted = vec![None; rows.len()];
776
777 // The rows are already cut at `MAX_FILE_DIFF_LINES`, so nothing past that cut is
778 // ever parsed. This is the other cap — the byte one — measured over the rows that
779 // survived rather than over the file, since the rows are all there is to colour.
780 let bytes: usize = rows.iter().map(|row| row.text.len() + 1).sum();
781 if bytes > highlight::MAX_BYTES {
782 return highlighted;
783 }
784
785 // A hunk runs from one `@@` row to the next, or to the end. Anything before the
786 // first `@@` — git writes none, but a truncated patch could — is its own group and
787 // simply has no content rows in it.
788 let mut start = 0;
789 while start < rows.len() {
790 let end = rows[start + 1..]
791 .iter()
792 .position(|row| row.kind == LineKind::Hunk)
793 .map(|offset| start + 1 + offset)
794 .unwrap_or(rows.len());
795
796 highlight_hunk(path, &rows[start..end], &mut highlighted[start..end]);
797 start = end;
798 }
799
800 highlighted
801}
802
803/// Highlights one hunk into `into`, which is the same length as `rows`.
804fn highlight_hunk(path: &str, rows: &[DiffLine], into: &mut [Option<String>]) {
805 let mut old = String::new();
806 let mut new = String::new();
807
808 for row in rows {
809 for side in match row.kind {
810 LineKind::Context => [Some(&mut old), Some(&mut new)],
811 LineKind::Removed => [Some(&mut old), None],
812 LineKind::Added => [None, Some(&mut new)],
813 // A hunk header and the "no newline" note are git's words about the file,
814 // not lines of it, so they are in neither reconstruction.
815 LineKind::Hunk | LineKind::Note => [None, None],
816 }
817 .into_iter()
818 .flatten()
819 {
820 side.push_str(&row.text);
821 side.push('\n');
822 }
823 }
824
825 let old = highlight::snippet_lines(path, &old);
826 let new = highlight::snippet_lines(path, &new);
827
828 let (mut from_old, mut from_new) = (0, 0);
829 for (row, cell) in rows.iter().zip(into) {
830 *cell = match row.kind {
831 LineKind::Removed => {
832 from_old += 1;
833 old.as_ref()
834 .and_then(|lines| lines.get(from_old - 1))
835 .cloned()
836 }
837 LineKind::Added => {
838 from_new += 1;
839 new.as_ref()
840 .and_then(|lines| lines.get(from_new - 1))
841 .cloned()
842 }
843 LineKind::Context => {
844 from_old += 1;
845 from_new += 1;
846 new.as_ref()
847 .and_then(|lines| lines.get(from_new - 1))
848 .cloned()
849 }
850 LineKind::Hunk | LineKind::Note => None,
851 };
852 }
853}
854
855// --- Shared bits ------------------------------------------------------------------
856
857/// What the page says when git ran out of time.
858///
859/// A designed state rather than a 500: a timeout is this instance declining to spend
860/// more of itself on one request, which is a thing to say plainly and to offer a retry
861/// for — not a fault the visitor caused or can report.
862#[component]
863pub(super) async fn took_too_long() -> Result {
864 view! {
865 <div class="rounded-lg border border-border px-4 py-10 text-center">
866 <p class="text-sm">"This took too long to read."</p>
867 <p class="mt-1.5 text-xs text-muted-foreground">
868 "The repository is large enough that building this diff ran past the time one request is given. Reloading may work; cloning the repository certainly will."
869 </p>
870 </div>
871 }
872}
873
874/// Turns a use case's answer into either a page or a rendered state.
875///
876/// `Ok(None)` from the use case is a 404 — invisible and absent are one answer, as
877/// everywhere else. A **timeout** is the one failure that is not a 500: it comes back
878/// as `Ok(None)` here so the caller renders [`took_too_long`] instead.
879pub(super) fn unwrap_page<T>(loaded: crate::application::Result<Option<T>>) -> Result<Option<T>> {
880 match loaded {
881 Ok(Some(page)) => Ok(Some(page)),
882 Ok(None) => Err(not_found().into()),
883 Err(error) if timed_out(&error) => {
884 eprintln!("steid: {error}");
885 Ok(None)
886 }
887 Err(other) => Err(server_error(std::io::Error::other(other.to_string()))),
888 }
889}
890
891/// The branches and tags of a repository the viewer can already see, or 404.
892///
893/// One `git` process. Called only by the states that draw the form's datalist.
894async fn refs_for(cx: &Cx, repo: &RepoView) -> Result<RefList> {
895 Ok(list_refs(
896 &repo.handle,
897 &repo.name,
898 &current_actor(cx).await?,
899 &Stores::new(&orgs(cx), &memberships(cx), &repos(cx)),
900 &queries(cx),
901 )
902 .await
903 .map_err(server_error)?
904 .ok_or_not_found()?)
905}
906
907/// What the form's base field opens with: the repository's default branch.
908///
909/// Comparing against anything else is the unusual case, and an empty field would make
910/// the common one typing. One `git` process; empty for a repository with no commits,
911/// where there is nothing to prefill with.
912async fn default_base(cx: &Cx, repo: &RepoView) -> Result<String> {
913 use crate::application::port::GitQuery;
914
915 Ok(queries(cx)
916 .default_branch(&repo.handle, &repo.name)
917 .await
918 .map_err(server_error)?
919 .map(|branch| branch.as_str().to_owned())
920 .unwrap_or_default())
921}
922
923/// A count and the thing it counts, pluralised.
924fn counted(count: usize, one: &str, many: &str) -> String {
925 format!("{count} {}", if count == 1 { one } else { many })
926}
927
928// --- URLs -------------------------------------------------------------------------
929
930/// The page for one commit.
931///
932/// Takes a `&str` rather than an [`ObjectId`] because the sha in a URL may equally be a
933/// branch name someone typed — the page resolves whatever it is given.
934pub(super) fn commit_url(handle: &str, name: &str, sha: &str) -> String {
935 format!("/{handle}/repos/{name}/commits/{}", encode(sha, false))
936}
937
938/// The comparison of two revisions.
939///
940/// Each half is encoded on its own, so a slash inside a branch name cannot be mistaken
941/// for a path separator and the `...` between them is unambiguous.
942pub(super) fn compare_url(handle: &str, name: &str, base: &str, head: &str) -> String {
943 format!(
944 "/{handle}/repos/{name}/compare/{}...{}",
945 encode(base, false),
946 encode(head, false)
947 )
948}
949
950#[cfg(test)]
951mod tests {
952 use super::*;
953
954 #[test]
955 fn a_commit_url_carries_the_whole_sha() {
956 assert_eq!(
957 commit_url("ada", "steid", "a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6e7f8a9b0"),
958 "/ada/repos/steid/commits/a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6e7f8a9b0"
959 );
960 }
961
962 #[test]
963 fn a_compare_url_encodes_each_half_on_its_own() {
964 // A slash inside a branch name must not become a path separator, and the `...`
965 // between the halves must survive as the separator it is.
966 assert_eq!(
967 compare_url("ada", "steid", "main", "feature/login"),
968 "/ada/repos/steid/compare/main...feature%2Flogin"
969 );
970 }
971
972 #[test]
973 fn a_compare_url_round_trips_through_its_separator() {
974 // What `compare_page` does with the segment it is handed, in reverse.
975 let url = compare_url("ada", "steid", "v1.0", "v2.0");
976 let spec = url.rsplit('/').next().expect("a last segment");
977
978 assert_eq!(spec.split_once("..."), Some(("v1.0", "v2.0")));
979 }
980
981 #[test]
982 fn counts_read_as_english() {
983 assert_eq!(
984 counted(1, "file changed", "files changed"),
985 "1 file changed"
986 );
987 assert_eq!(
988 counted(3, "file changed", "files changed"),
989 "3 files changed"
990 );
991 }
992 // --- Highlighted diffs ---------------------------------------------------------
993
994 fn row(kind: LineKind, text: &str) -> DiffLine {
995 DiffLine {
996 kind,
997 old: None,
998 new: None,
999 text: text.to_owned(),
1000 }
1001 }
1002
1003 #[test]
1004 fn a_hunks_lines_are_highlighted_by_the_files_path() {
1005 let rows = vec![
1006 row(LineKind::Hunk, "@@ -1,3 +1,3 @@"),
1007 row(LineKind::Context, "fn main() {"),
1008 row(LineKind::Removed, " let x = 1;"),
1009 row(LineKind::Added, " let y = 2;"),
1010 row(LineKind::Context, "}"),
1011 ];
1012
1013 let highlighted = highlighted_rows("main.rs", &rows);
1014
1015 assert!(highlighted[0].is_none(), "a hunk header is git's words");
1016 for entry in &highlighted[1..] {
1017 let html = entry.as_deref().expect("highlighted");
1018 assert!(html.contains("hl-"), "{html}");
1019 assert_eq!(
1020 html.matches("<span").count(),
1021 html.matches("</span>").count()
1022 );
1023 assert!(!html.contains('\n'), "{html}");
1024 }
1025
1026 assert!(
1027 highlighted[2]
1028 .as_deref()
1029 .expect("highlighted")
1030 .contains('1'),
1031 "the removed row keeps its own text"
1032 );
1033 assert!(
1034 highlighted[3]
1035 .as_deref()
1036 .expect("highlighted")
1037 .contains('2'),
1038 "the added row keeps its own text"
1039 );
1040 }
1041
1042 /// The reason each hunk is highlighted twice: the removed line and the added line
1043 /// that replaced it are two versions of the *same* line, and feeding them to one
1044 /// parser in sequence reads the second as a continuation of the first.
1045 #[test]
1046 fn the_two_sides_of_a_change_are_parsed_independently() {
1047 let rows = vec![
1048 row(LineKind::Hunk, "@@ -1,1 +1,1 @@"),
1049 row(LineKind::Removed, "let a = \"one\";"),
1050 row(LineKind::Added, "let a = \"two\";"),
1051 ];
1052
1053 let highlighted = highlighted_rows("main.rs", &rows);
1054
1055 for index in [1, 2] {
1056 let html = highlighted[index].as_deref().expect("highlighted");
1057 assert!(html.contains("hl-storage"), "{html}");
1058 assert!(html.contains("hl-string"), "{html}");
1059 }
1060 }
1061
1062 #[test]
1063 fn a_path_with_no_grammar_is_left_plain() {
1064 let rows = vec![
1065 row(LineKind::Hunk, "@@ -1,1 +1,1 @@"),
1066 row(LineKind::Added, "fn main() {}"),
1067 ];
1068
1069 assert!(
1070 highlighted_rows("notes.wibble", &rows)
1071 .iter()
1072 .all(Option::is_none)
1073 );
1074 }
1075
1076 #[test]
1077 fn every_hunk_of_a_file_is_highlighted_not_just_the_first() {
1078 let rows = vec![
1079 row(LineKind::Hunk, "@@ -1,1 +1,1 @@"),
1080 row(LineKind::Added, "fn a() {}"),
1081 row(LineKind::Hunk, "@@ -9,1 +9,1 @@"),
1082 row(LineKind::Added, "fn b() {}"),
1083 row(LineKind::Note, "\\ No newline at end of file"),
1084 ];
1085
1086 let highlighted = highlighted_rows("main.rs", &rows);
1087
1088 assert!(highlighted[1].is_some());
1089 assert!(highlighted[3].is_some());
1090 assert!(highlighted[4].is_none(), "the note is git's words");
1091 }
1092
1093 #[test]
1094 fn the_source_of_a_diff_row_is_escaped_rather_than_passed_through() {
1095 let rows = vec![
1096 row(LineKind::Hunk, "@@ -1,1 +1,1 @@"),
1097 row(LineKind::Added, "// <script>alert(1)</script>"),
1098 ];
1099
1100 let html = highlighted_rows("main.rs", &rows)[1]
1101 .clone()
1102 .expect("highlighted");
1103
1104 assert!(!html.contains("<script"), "{html}");
1105 assert!(html.contains("&lt;script"), "{html}");
1106 }
1107
1108 #[test]
1109 fn a_diff_past_the_byte_cap_is_plain_with_no_notice() {
1110 let rows = vec![
1111 row(LineKind::Hunk, "@@ -1,2 +1,2 @@"),
1112 row(LineKind::Added, &"x".repeat(highlight::MAX_BYTES + 1)),
1113 ];
1114
1115 assert!(
1116 highlighted_rows("main.rs", &rows)
1117 .iter()
1118 .all(Option::is_none)
1119 );
1120 }
1121
1122 #[test]
1123 fn every_row_has_an_entry_so_the_view_can_zip_them() {
1124 let rows = vec![
1125 row(LineKind::Hunk, "@@ -1,3 +1,3 @@"),
1126 row(LineKind::Context, ""),
1127 row(LineKind::Removed, "a"),
1128 row(LineKind::Added, "b"),
1129 row(LineKind::Note, "\\ No newline at end of file"),
1130 ];
1131
1132 assert_eq!(highlighted_rows("main.rs", &rows).len(), rows.len());
1133 assert_eq!(highlighted_rows("notes.wibble", &rows).len(), rows.len());
1134 assert_eq!(highlighted_rows("main.rs", &[]).len(), 0);
1135 }
1136}