steid

@jamesgill /

Rust18.5 KBCode·Blame·History·Raw
1//! Reading one commit, and comparing two revisions.
2//!
3//! Two use cases that share a renderer and a shape: both end in a [`Diff`], and both
4//! reach it through the same authorization every other read does — see
5//! [`visible_repo`](super::repo::visible_repo). A repository invisible on its page has no
6//! commits and nothing to compare, by construction.
7//!
8//! # Why compare is three-dot
9//!
10//! `compare_revisions` diffs the **merge base** of the two revisions against the head,
11//! not the base against the head. That is what `git diff base...head` means and it is
12//! the only definition that answers the question anybody is actually asking: *what does
13//! this branch add?* A two-dot diff also undoes everything the base gained since the
14//! branch left it, which shows up as a wall of deletions nobody made. It is also
15//! precisely what a pull request will need, which is why it is settled here rather than
16//! at the point a pull request exists.
17
18use crate::domain::{
19 Actor, CommitDetail, CommitSummary, ObjectId, OrgName, RefName, RepoName,
20 repository::{MembershipRepository, OrgRepository, RepoRepository},
21};
22
23use super::{
24 browse::MAX_RAW_BYTES,
25 diff::{Diff, parse_diff},
26 error::Result,
27 paging::{Paged, clamp, offset, page_count},
28 port::GitQuery,
29 repo::visible_repo,
30};
31
32/// How many commits one page of a comparison lists.
33///
34/// Twice the log's page, because a comparison's list is read as one thing — "what this
35/// branch adds" — rather than browsed, so the useful page is the one that usually holds
36/// the whole answer.
37pub const COMPARE_LOG_LIMIT: usize = 100;
38
39/// One commit and what it changed.
40#[derive(Debug, Clone, PartialEq, Eq)]
41pub struct CommitPage {
42 pub commit: CommitDetail,
43 pub diff: Diff,
44}
45
46/// Reads a commit and its diff.
47///
48/// The diff is against the **first parent**, which is what a commit page means by "what
49/// this commit changed" — for a merge, the other parents' changes belong to the commits
50/// that made them, and diffing against all of them would show a merge as either empty
51/// or as the whole of the branch it merged. A root commit has no parent and is diffed
52/// against nothing, so the first commit in a history shows everything it introduced
53/// rather than an empty page.
54///
55/// `Ok(None)` on the usual terms: invisible, absent, or a revision that names no commit.
56///
57/// **Three `git` processes** — two to resolve and read the commit, one for the diff.
58/// The diff takes the id the commit already resolved to, so nothing is resolved twice.
59#[allow(clippy::too_many_arguments)]
60pub async fn view_commit(
61 handle: &OrgName,
62 name: &RepoName,
63 rev: &RefName,
64 actor: &Actor,
65 orgs: &impl OrgRepository,
66 memberships: &impl MembershipRepository,
67 repos: &impl RepoRepository,
68 queries: &impl GitQuery,
69) -> Result<Option<CommitPage>> {
70 if visible_repo(handle, name, actor, orgs, memberships, repos)
71 .await?
72 .is_none()
73 {
74 return Ok(None);
75 }
76
77 let Some(commit) = queries.commit(handle, name, rev).await? else {
78 return Ok(None);
79 };
80
81 let diff = diff_between(handle, name, commit.parents.first(), &commit.id, queries).await?;
82
83 Ok(Some(CommitPage { commit, diff }))
84}
85
86/// What comparing two revisions produced.
87///
88/// A parsed answer rather than an error for each way it can go nowhere: an unknown ref
89/// re-renders the form, identical refs say so, and unrelated histories are a real state
90/// of a real repository. None of the three is a fault, and turning any of them into one
91/// would put a 500 in front of a typo.
92#[derive(Debug, Clone, PartialEq, Eq)]
93pub enum Compared {
94 /// One of the two revisions names nothing in this repository.
95 UnknownRef {
96 rev: RefName,
97 },
98 /// Both revisions resolve to the same commit.
99 Identical,
100 /// The two commits share no ancestor, so there is nothing a diff could be relative
101 /// to. Happens when two histories are pushed into one repository.
102 Unrelated,
103 Ready(Box<Comparison>),
104}
105
106/// Two revisions, and what separates them.
107#[derive(Debug, Clone, PartialEq, Eq)]
108pub struct Comparison {
109 pub base: RefName,
110 pub head: RefName,
111 pub base_id: ObjectId,
112 pub head_id: ObjectId,
113 pub merge_base: ObjectId,
114 /// One page of the commits on `head` that are not on `base`, newest first,
115 /// [`COMPARE_LOG_LIMIT`] to a page.
116 ///
117 /// The diff beside it is **the whole range**, not this page: a comparison's diff is
118 /// what the range changes, and slicing it by the commit list would make a page
119 /// answer a question nobody asked.
120 pub commits: Paged<CommitSummary>,
121 pub diff: Diff,
122}
123
124impl Comparison {
125 /// Whether `head` is already contained in `base` — nothing to bring across.
126 ///
127 /// The merge base being the head itself is exactly that: every commit on `head` is
128 /// reachable from `base`. The page offers the comparison the other way round rather
129 /// than showing an empty one, because that is almost always what was meant.
130 pub fn head_is_behind(&self) -> bool {
131 self.merge_base == self.head_id
132 }
133
134 /// How many commits the range holds in total.
135 pub fn total_commits(&self) -> usize {
136 self.commits.total
137 }
138}
139
140/// Compares two revisions, three-dot.
141///
142/// `Ok(None)` means the repository is invisible or absent — the same answer as
143/// everywhere else. Everything that is wrong with the *revisions* comes back as a
144/// [`Compared`] variant instead, because the page's answer to those is a rendered
145/// explanation and not a 404.
146///
147/// **Six `git` processes** at most: two to resolve, one for the merge base, then the
148/// commit count, the commit list and the diff. The two resolutions run concurrently, as
149/// do the last three, so the page waits on three round trips rather than six. The count
150/// is what pages the list — see [ui.md](../../plans/ui.md#paging).
151#[allow(clippy::too_many_arguments)]
152pub async fn compare_revisions(
153 handle: &OrgName,
154 name: &RepoName,
155 base: &RefName,
156 head: &RefName,
157 page: usize,
158 actor: &Actor,
159 orgs: &impl OrgRepository,
160 memberships: &impl MembershipRepository,
161 repos: &impl RepoRepository,
162 queries: &impl GitQuery,
163) -> Result<Option<Compared>> {
164 if visible_repo(handle, name, actor, orgs, memberships, repos)
165 .await?
166 .is_none()
167 {
168 return Ok(None);
169 }
170
171 let (base_id, head_id) = tokio::try_join!(
172 queries.resolve(handle, name, base),
173 queries.resolve(handle, name, head),
174 )?;
175
176 // Reported one at a time, and the base first, so the form can point at the field
177 // that is wrong rather than at both.
178 let Some(base_id) = base_id else {
179 return Ok(Some(Compared::UnknownRef { rev: base.clone() }));
180 };
181 let Some(head_id) = head_id else {
182 return Ok(Some(Compared::UnknownRef { rev: head.clone() }));
183 };
184
185 if base_id == head_id {
186 return Ok(Some(Compared::Identical));
187 }
188
189 let Some(merge_base) = queries.merge_base(handle, name, &base_id, &head_id).await? else {
190 return Ok(Some(Compared::Unrelated));
191 };
192
193 // The count decides how many pages there are, so it is asked for alongside rather
194 // than inferred from one row past the limit — which would say only that a next page
195 // exists. It runs concurrently with the other two, so it costs a process, not a
196 // round trip.
197 let total = queries
198 .count_between(handle, name, Some(&merge_base), &head_id)
199 .await?;
200 let page = clamp(page, page_count(total, COMPARE_LOG_LIMIT));
201
202 let (commits, diff) = tokio::try_join!(
203 queries.log_between(
204 handle,
205 name,
206 Some(&merge_base),
207 &head_id,
208 offset(page, COMPARE_LOG_LIMIT),
209 COMPARE_LOG_LIMIT,
210 ),
211 diff_between(handle, name, Some(&merge_base), &head_id, queries),
212 )?;
213
214 Ok(Some(Compared::Ready(Box::new(Comparison {
215 base: base.clone(),
216 head: head.clone(),
217 base_id,
218 head_id,
219 merge_base,
220 commits: Paged::of(commits, total, page, COMPARE_LOG_LIMIT),
221 diff,
222 }))))
223}
224
225/// Reads a patch and parses it.
226///
227/// The byte cap is [`MAX_RAW_BYTES`] rather than a new number: it is already the answer
228/// to "how much of a repository may one request hold in memory", and a patch is
229/// governed by exactly that question. A diff over it is reported as truncated, with the
230/// per-file counts intact — see [`Diff`].
231async fn diff_between(
232 handle: &OrgName,
233 name: &RepoName,
234 base: Option<&ObjectId>,
235 head: &ObjectId,
236 queries: &impl GitQuery,
237) -> std::result::Result<Diff, super::port::GitQueryError> {
238 let raw = queries
239 .diff(handle, name, base, head, MAX_RAW_BYTES)
240 .await?;
241
242 Ok(parse_diff(&raw.numstat, &raw.patch, raw.truncated))
243}
244
245#[cfg(test)]
246mod tests {
247 use std::time::SystemTime;
248
249 use super::*;
250 use crate::{
251 domain::{
252 Membership, MembershipId, OrgId, Organization, RepoId, Repository, UserId, Visibility,
253 },
254 infrastructure::{
255 git::InMemoryGitQuery,
256 repository::{InMemoryMembershipRepo, InMemoryOrgRepo, InMemoryRepoRepo},
257 },
258 };
259
260 struct Fixture {
261 orgs: InMemoryOrgRepo,
262 memberships: InMemoryMembershipRepo,
263 repos: InMemoryRepoRepo,
264 handle: OrgName,
265 owner: Actor,
266 stranger: Actor,
267 }
268
269 async fn fixture(visibility: Visibility) -> Fixture {
270 let orgs = InMemoryOrgRepo::new();
271 let memberships = InMemoryMembershipRepo::new();
272 let repos = InMemoryRepoRepo::new();
273
274 let org = Organization::new(OrgId::generate(), "acme", None).expect("valid org");
275 orgs.save(&org).await.expect("save org");
276
277 let owner = UserId::generate();
278 memberships
279 .save(&Membership::new(
280 MembershipId::generate(),
281 org.id.clone(),
282 owner.clone(),
283 crate::domain::Role::Owner,
284 ))
285 .await
286 .expect("save membership");
287
288 repos
289 .save(
290 &Repository::new(
291 RepoId::generate(),
292 org.id.clone(),
293 "steid",
294 None,
295 visibility,
296 SystemTime::now(),
297 )
298 .expect("valid repository"),
299 )
300 .await
301 .expect("save repo");
302
303 Fixture {
304 orgs,
305 memberships,
306 repos,
307 handle: org.name,
308 owner: Actor::User(owner),
309 stranger: Actor::Anonymous,
310 }
311 }
312
313 fn repo_name() -> RepoName {
314 RepoName::new("steid").expect("valid repository name")
315 }
316
317 fn rev(value: &str) -> RefName {
318 RefName::new(value).expect("valid revision")
319 }
320
321 fn detail() -> CommitDetail {
322 CommitDetail {
323 id: ObjectId::from_trusted("a".repeat(40)),
324 tree: ObjectId::from_trusted("b".repeat(40)),
325 parents: vec![ObjectId::from_trusted("c".repeat(40))],
326 summary: "feat: a thing".to_owned(),
327 body: "why it was done".to_owned(),
328 author_name: "Ada Lovelace".to_owned(),
329 author_email: "ada@example.com".to_owned(),
330 authored_at: SystemTime::UNIX_EPOCH,
331 committer_name: "Ada Lovelace".to_owned(),
332 committer_email: "ada@example.com".to_owned(),
333 committed_at: SystemTime::UNIX_EPOCH,
334 }
335 }
336
337 const PATCH: &str = "\
338diff --git a/a.txt b/a.txt
339--- a/a.txt
340+++ b/a.txt
341@@ -1,1 +1,1 @@
342-old
343+new
344";
345
346 impl Fixture {
347 async fn commit(
348 &self,
349 actor: &Actor,
350 queries: &InMemoryGitQuery,
351 ) -> Result<Option<CommitPage>> {
352 view_commit(
353 &self.handle,
354 &repo_name(),
355 &rev("main"),
356 actor,
357 &self.orgs,
358 &self.memberships,
359 &self.repos,
360 queries,
361 )
362 .await
363 }
364
365 async fn compare(
366 &self,
367 actor: &Actor,
368 queries: &InMemoryGitQuery,
369 ) -> Result<Option<Compared>> {
370 self.compare_page(actor, queries, 1).await
371 }
372
373 async fn compare_page(
374 &self,
375 actor: &Actor,
376 queries: &InMemoryGitQuery,
377 page: usize,
378 ) -> Result<Option<Compared>> {
379 compare_revisions(
380 &self.handle,
381 &repo_name(),
382 &rev("main"),
383 &rev("next"),
384 page,
385 actor,
386 &self.orgs,
387 &self.memberships,
388 &self.repos,
389 queries,
390 )
391 .await
392 }
393 }
394
395 // --- view_commit --------------------------------------------------------------
396
397 #[tokio::test]
398 async fn a_commit_comes_back_with_its_parsed_diff() {
399 let f = fixture(Visibility::Public).await;
400 let queries = InMemoryGitQuery::new()
401 .with_commit(detail())
402 .with_diff(PATCH, "1\t1\ta.txt\n");
403
404 let page = f
405 .commit(&f.owner, &queries)
406 .await
407 .expect("should read")
408 .expect("found");
409
410 assert_eq!(page.commit.summary, "feat: a thing");
411 assert_eq!(page.diff.files_changed(), 1);
412 assert_eq!((page.diff.added(), page.diff.removed()), (1, 1));
413 assert_eq!(page.diff.files[0].rows.len(), 3);
414 }
415
416 #[tokio::test]
417 async fn a_revision_that_names_no_commit_is_not_found() {
418 let f = fixture(Visibility::Public).await;
419
420 assert!(
421 f.commit(&f.owner, &InMemoryGitQuery::new())
422 .await
423 .expect("should read")
424 .is_none()
425 );
426 }
427
428 #[tokio::test]
429 async fn a_private_repositorys_commits_are_invisible_to_a_stranger() {
430 // A commit message and a diff are content. Same answer as every other read.
431 let f = fixture(Visibility::Private).await;
432 let queries = InMemoryGitQuery::new()
433 .with_commit(detail())
434 .with_diff(PATCH, "1\t1\ta.txt\n");
435
436 assert!(
437 f.commit(&f.stranger, &queries)
438 .await
439 .expect("should read")
440 .is_none()
441 );
442 assert!(
443 f.commit(&f.owner, &queries)
444 .await
445 .expect("should read")
446 .is_some()
447 );
448 }
449
450 // --- compare_revisions --------------------------------------------------------
451
452 #[tokio::test]
453 async fn identical_revisions_have_nothing_to_compare() {
454 // The fake resolves every revision to the same id, which is exactly this case.
455 let f = fixture(Visibility::Public).await;
456
457 let compared = f
458 .compare(&f.owner, &InMemoryGitQuery::new())
459 .await
460 .expect("should read")
461 .expect("visible");
462
463 assert_eq!(compared, Compared::Identical);
464 }
465
466 #[tokio::test]
467 async fn an_unknown_revision_is_reported_rather_than_being_a_404() {
468 // The page re-renders its form with the reason; a 404 would discard what was
469 // typed and say nothing about which of the two was wrong.
470 let f = fixture(Visibility::Public).await;
471
472 let compared = f
473 .compare(&f.owner, &InMemoryGitQuery::empty())
474 .await
475 .expect("should read")
476 .expect("visible");
477
478 assert_eq!(compared, Compared::UnknownRef { rev: rev("main") });
479 }
480
481 #[tokio::test]
482 async fn a_private_repository_cannot_be_compared_by_a_stranger() {
483 let f = fixture(Visibility::Private).await;
484
485 assert!(
486 f.compare(&f.stranger, &InMemoryGitQuery::new())
487 .await
488 .expect("should read")
489 .is_none()
490 );
491 }
492
493 #[test]
494 fn a_head_contained_in_its_base_is_behind_it() {
495 let id = |value: &str| ObjectId::from_trusted(value.repeat(40));
496
497 let comparison = Comparison {
498 base: rev("main"),
499 head: rev("next"),
500 base_id: id("a"),
501 head_id: id("b"),
502 merge_base: id("b"),
503 commits: Paged::of(Vec::new(), 0, 1, COMPARE_LOG_LIMIT),
504 diff: Diff::default(),
505 };
506
507 assert!(comparison.head_is_behind());
508 assert_eq!(comparison.total_commits(), 0);
509 }
510
511 #[tokio::test]
512 async fn the_second_page_of_a_comparison_starts_where_the_first_ended() {
513 let f = fixture(Visibility::Public).await;
514 let commits: Vec<_> = (0..COMPARE_LOG_LIMIT + 5)
515 .map(|n| CommitSummary {
516 id: ObjectId::from_trusted(format!("{n:040x}")),
517 summary: format!("commit {n}"),
518 author_name: "Ada Lovelace".to_owned(),
519 committed_at: std::time::UNIX_EPOCH + std::time::Duration::from_secs(n as u64),
520 })
521 .collect();
522 let queries = InMemoryGitQuery::new()
523 .with_resolved("next", "b")
524 .with_merge_base(&"c".repeat(40))
525 .with_log(commits)
526 .with_diff(PATCH, "1\t1\ta.txt\n");
527
528 let Some(Compared::Ready(first)) = f
529 .compare_page(&f.owner, &queries, 1)
530 .await
531 .expect("should read")
532 else {
533 panic!("a comparison");
534 };
535 let Some(Compared::Ready(second)) = f
536 .compare_page(&f.owner, &queries, 2)
537 .await
538 .expect("should read")
539 else {
540 panic!("a comparison");
541 };
542
543 assert_eq!(first.commits.items.len(), COMPARE_LOG_LIMIT);
544 assert_eq!(second.commits.items.len(), 5);
545 assert_eq!(second.commits.offset(), COMPARE_LOG_LIMIT);
546 assert_eq!(
547 second.commits.items[0].summary,
548 format!("commit {COMPARE_LOG_LIMIT}")
549 );
550 // The diff is the whole range on both pages: it answers "what does this bring
551 // across", which the commit list's page number does not narrow.
552 assert_eq!(first.diff, second.diff);
553 }
554
555 #[tokio::test]
556 async fn a_comparison_page_past_the_end_clamps() {
557 let f = fixture(Visibility::Public).await;
558 let queries = InMemoryGitQuery::new()
559 .with_resolved("next", "b")
560 .with_merge_base(&"c".repeat(40))
561 .with_diff(PATCH, "1\t1\ta.txt\n");
562
563 let Some(Compared::Ready(comparison)) = f
564 .compare_page(&f.owner, &queries, 400)
565 .await
566 .expect("should read")
567 else {
568 panic!("a comparison");
569 };
570
571 assert_eq!(comparison.commits.page, 1);
572 }
573}