steid

@jamesgill /

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