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