steid

@jamesgill /

Rust63.3 KBCode·Blame·History·Raw
1//! Reading a repository's contents for display.
2//!
3//! Authorization is not re-implemented here: every entry point goes through
4//! [`visible_repo`](super::repo::visible_repo), so a repository invisible on its page is
5//! invisible in its file tree, by construction rather than by remembering to check.
6
7use std::collections::HashMap;
8
9use crate::domain::{
10 Actor, BranchRow, CommitSummary, EntryCommit, ObjectId, OrgName, RefKind, RefName, RepoName,
11 RepoPath, TagRow,
12 repository::{MembershipRepository, OrgRepository, RepoRepository},
13};
14
15use super::{
16 error::Result,
17 paging::{Paged, clamp, offset, page_count},
18 port::{Blob, GitQuery},
19 repo::visible_repo,
20};
21
22/// The largest file Steid will render.
23///
24/// A page has a person waiting on it, and past a megabyte nobody is reading the file —
25/// they are waiting for a browser to lay out a megabyte of text. Bigger files are
26/// reported by size rather than shown.
27pub const MAX_BLOB_BYTES: u64 = 1024 * 1024;
28
29/// How many commits one page of a log shows.
30pub const LOG_LIMIT: usize = 50;
31
32/// How many branches or tags one page of a refs page shows.
33///
34/// Larger than a log's page because a ref row is one line and read by scanning for a
35/// name, so more of them on a page is straightforwardly better.
36pub const REF_LIMIT: usize = 100;
37
38/// The largest file Steid will hand back raw.
39///
40/// Much larger than [`MAX_BLOB_BYTES`], because nobody is reading a raw response — it is
41/// being saved or piped, and the megabyte cap exists to protect a *browser*. It is still
42/// capped, and capped well below what a repository can hold, because [`GitQuery`] reads
43/// bytes rather than streaming them: this number is the memory one request may cost, so
44/// it bounds what a handful of concurrent requests can do to a small VPS. Anything
45/// larger is what `git clone` is for.
46pub const MAX_RAW_BYTES: u64 = 10 * 1024 * 1024;
47
48/// A file, as far as it can be displayed.
49#[derive(Debug, Clone, PartialEq, Eq)]
50pub struct FileView {
51 pub id: ObjectId,
52 pub size: u64,
53 /// The contents, when they are text small enough to show.
54 ///
55 /// `None` covers both "not valid UTF-8" and "too large"; [`too_large`](Self::too_large)
56 /// tells them apart, because the page says something different for each.
57 pub text: Option<String>,
58 pub too_large: bool,
59}
60
61impl FileView {
62 /// Whether the file exists and is simply not displayable as text.
63 pub fn is_binary(&self) -> bool {
64 self.text.is_none() && !self.too_large
65 }
66}
67
68/// What is at a path in a repository.
69#[derive(Debug, Clone, PartialEq, Eq)]
70pub enum Browsed {
71 /// The repository has no commits. Distinct from an empty directory: there is
72 /// nothing to point a revision at, so the page offers push instructions rather than
73 /// an empty listing.
74 Empty,
75 Directory {
76 rev: RefName,
77 path: RepoPath,
78 /// Ordered directories-first, then case-insensitively by name.
79 entries: Vec<crate::domain::TreeEntry>,
80 /// The commit that last touched each entry, by entry name.
81 ///
82 /// Sparse on purpose: an entry whose last change is older than the walk reaches
83 /// is absent, and its row shows nothing rather than a commit that is merely the
84 /// oldest one looked at.
85 history: HashMap<String, EntryCommit>,
86 /// What a listing knows about an entry beyond its tree record, by entry name.
87 ///
88 /// Sparse, and empty for the ordinary directory: only a submodule or a symlink
89 /// has anything here, and reading it is skipped entirely when the listing holds
90 /// neither. See [`entry_details`].
91 details: HashMap<String, EntryDetail>,
92 },
93 File {
94 rev: RefName,
95 path: RepoPath,
96 file: FileView,
97 },
98}
99
100/// What a listing knows about an entry beyond its own tree record.
101///
102/// One struct rather than a map per fact: both facts are rare, both are read from the
103/// same listing, and a row asks for all of them at once.
104#[derive(Debug, Clone, Default, PartialEq, Eq)]
105pub struct EntryDetail {
106 /// A submodule's upstream, when `.gitmodules` gives an `https://` one.
107 ///
108 /// Only `https://`. A `git@host:owner/repo` or a `../sibling` is a URL for a git
109 /// client rather than for a browser, and a link a reader cannot follow is worse
110 /// than the sha they can at least copy.
111 pub url: Option<String>,
112 /// A symlink's target, exactly as the link stores it.
113 pub target: Option<String>,
114 /// Where that target lands inside this repository, when it lands inside it at all.
115 ///
116 /// `None` for an absolute target, one that walks out through `..`, and one that is
117 /// simply not readable — all of which are links Steid can show but not follow.
118 pub resolved: Option<RepoPath>,
119}
120
121/// How big a `.gitmodules` may be before it is ignored.
122///
123/// It is a hand-written config file listing a repository's submodules; a real one is
124/// hundreds of bytes. The cap is here because the file is repository content and this
125/// reads it into memory on a page request.
126const MAX_GITMODULES_BYTES: u64 = 64 * 1024;
127
128/// How many symlinks in one listing have their targets read.
129///
130/// Each target is a round trip to the kept-alive `cat-file` — no process, but not free
131/// either — and a directory of thousands of links would pay for a column nobody is
132/// scanning. Past the cap **no** target is read rather than an arbitrary hundred of
133/// them: a column that is filled in for some rows and blank for others says something
134/// false about the blank ones.
135const MAX_SYMLINK_TARGETS: usize = 100;
136
137/// Resolves a path in a repository into whatever is there.
138///
139/// `rev` of `None` means the default branch, which is what a bare repository URL asks
140/// for.
141///
142/// `Ok(None)` means the repository is invisible, absent, or has nothing at that path —
143/// all rendered identically as 404, for the reason
144/// [`visible_repo`](super::repo::visible_repo) gives.
145#[allow(clippy::too_many_arguments)]
146pub async fn browse_repo(
147 handle: &OrgName,
148 name: &RepoName,
149 rev: Option<&RefName>,
150 path: &RepoPath,
151 actor: &Actor,
152 orgs: &impl OrgRepository,
153 memberships: &impl MembershipRepository,
154 repos: &impl RepoRepository,
155 queries: &impl GitQuery,
156) -> Result<Option<Browsed>> {
157 if visible_repo(handle, name, actor, orgs, memberships, repos)
158 .await?
159 .is_none()
160 {
161 return Ok(None);
162 }
163
164 let Some(rev) = resolve_revision(handle, name, rev, queries).await? else {
165 return Ok(Some(Browsed::Empty));
166 };
167
168 // A directory first, because that is the common case and the cheaper question.
169 if let Some(mut entries) = queries.list_tree(handle, name, &rev, path).await? {
170 entries.sort_by_key(crate::domain::TreeEntry::ordering_key);
171
172 // One `git` process for the whole listing, and only for a listing: a blob path
173 // never gets here. It cannot run beside the tree read — it needs the names the
174 // tree read produces — so this is the one place a browse costs two round trips
175 // in sequence.
176 let names: Vec<String> = entries.iter().map(|entry| entry.name.clone()).collect();
177 let history = queries
178 .last_commits(handle, name, &rev, path, &names)
179 .await?;
180
181 let details = entry_details(handle, name, &rev, path, &entries, queries).await?;
182
183 return Ok(Some(Browsed::Directory {
184 rev,
185 path: path.clone(),
186 entries,
187 history,
188 details,
189 }));
190 }
191
192 let Some(blob) = queries
193 .read_blob(handle, name, &rev, path, MAX_BLOB_BYTES)
194 .await?
195 else {
196 return Ok(None);
197 };
198
199 Ok(Some(Browsed::File {
200 rev,
201 path: path.clone(),
202 file: view_of(blob),
203 }))
204}
205
206/// The submodule and symlink facts a listing needs, and nothing when it needs none.
207///
208/// **Costs nothing for an ordinary directory.** A listing with no submodule never opens
209/// `.gitmodules`, and one with no symlink never asks what a link points at — and
210/// neither read is a `git` process, since both go to the kept-alive `cat-file`.
211async fn entry_details(
212 handle: &OrgName,
213 name: &RepoName,
214 rev: &RefName,
215 path: &RepoPath,
216 entries: &[crate::domain::TreeEntry],
217 queries: &impl GitQuery,
218) -> Result<HashMap<String, EntryDetail>> {
219 use crate::domain::EntryKind;
220
221 let mut details: HashMap<String, EntryDetail> = HashMap::new();
222
223 if entries
224 .iter()
225 .any(|entry| entry.kind == EntryKind::Submodule)
226 {
227 // `.gitmodules` lives at the root of the revision, whatever directory is being
228 // listed, and is read once for the whole listing.
229 let modules = RepoPath::from_trusted(".gitmodules");
230 let text = queries
231 .read_blob(handle, name, rev, &modules, MAX_GITMODULES_BYTES)
232 .await?
233 .and_then(|blob| blob.content)
234 .and_then(|bytes| String::from_utf8(bytes).ok())
235 .unwrap_or_default();
236
237 let urls = parse_gitmodules(&text);
238
239 for entry in entries
240 .iter()
241 .filter(|entry| entry.kind == EntryKind::Submodule)
242 {
243 // Keyed by the submodule's path from the repository root, which is what
244 // `.gitmodules` records — the entry's own name is only its last component.
245 let full = path.join(&entry.name);
246
247 if let Some((_, url)) = urls.iter().find(|(at, _)| at == full.as_str()) {
248 details.entry(entry.name.clone()).or_default().url = Some(url.clone());
249 }
250 }
251 }
252
253 let links: Vec<&crate::domain::TreeEntry> = entries
254 .iter()
255 .filter(|entry| entry.kind == EntryKind::Symlink)
256 .collect();
257
258 if !links.is_empty() && links.len() <= MAX_SYMLINK_TARGETS {
259 let ids: Vec<ObjectId> = links.iter().map(|entry| entry.id.clone()).collect();
260 let targets = queries.symlink_targets(handle, name, &ids).await?;
261
262 for entry in links {
263 let Some(target) = targets.get(&entry.id) else {
264 continue;
265 };
266
267 let detail = details.entry(entry.name.clone()).or_default();
268
269 // A link resolves against the directory it is *in*, which is where the
270 // relative path in its own bytes is written from.
271 detail.resolved = resolve_relative(path, target);
272 detail.target = Some(target.clone());
273 }
274 }
275
276 Ok(details)
277}
278
279/// The `path = …` and `url = …` of every submodule in a `.gitmodules`, paired.
280///
281/// A deliberately small reading of git's config format rather than a parser for it:
282/// section headers and `key = value` lines, `#` and `;` comments, and nothing else. A
283/// value it cannot make sense of is skipped, because the consequence of misreading one
284/// is a link to somewhere a reader did not ask to go.
285///
286/// **Only `https://` URLs come back.** An `ssh://`, a `git@host:owner/repo` and a
287/// relative `../sibling` are all legitimate in the file and none of them is something a
288/// browser can open.
289pub fn parse_gitmodules(text: &str) -> Vec<(String, String)> {
290 let mut found: Vec<(String, String)> = Vec::new();
291 let mut path: Option<String> = None;
292 let mut url: Option<String> = None;
293
294 // A section ends the one before it, so what was collected is banked here as well as
295 // at the end of the file.
296 fn bank(
297 found: &mut Vec<(String, String)>,
298 path: &mut Option<String>,
299 url: &mut Option<String>,
300 ) {
301 if let (Some(path), Some(url)) = (path.take(), url.take())
302 && url.starts_with("https://")
303 && !path.is_empty()
304 {
305 found.push((path, url));
306 }
307 }
308
309 for line in text.lines() {
310 let line = line.trim();
311
312 if line.is_empty() || line.starts_with('#') || line.starts_with(';') {
313 continue;
314 }
315
316 if line.starts_with('[') {
317 bank(&mut found, &mut path, &mut url);
318 continue;
319 }
320
321 let Some((key, value)) = line.split_once('=') else {
322 continue;
323 };
324
325 // Trailing comments are not stripped: git does not treat `#` inside a value as
326 // one, and a URL may legitimately end in a fragment.
327 let value = value.trim().trim_matches('"').to_owned();
328
329 match key.trim().to_ascii_lowercase().as_str() {
330 "path" => path = Some(value.trim_matches('/').to_owned()),
331 "url" => url = Some(value),
332 _ => {}
333 }
334 }
335
336 bank(&mut found, &mut path, &mut url);
337
338 found
339}
340
341/// Where a relative reference written inside `dir` points, if it points inside the
342/// repository at all.
343///
344/// Shared by symlinks and by the links in a rendered markdown file, because they are
345/// the same question asked twice: a path written relative to the file it appears in.
346///
347/// `None` for an absolute path, for one that walks out through `..`, and for one that
348/// resolves to the root itself — none of which is a file this repository can show.
349/// `RepoPath` refuses `.` and `..` outright, which is why they are resolved here rather
350/// than handed to it.
351pub fn resolve_relative(dir: &RepoPath, target: &str) -> Option<RepoPath> {
352 let target = target.trim();
353
354 if target.is_empty() || target.starts_with('/') {
355 return None;
356 }
357
358 let mut parts: Vec<&str> = dir.components().collect();
359
360 for component in target.split('/') {
361 match component {
362 "" | "." => {}
363 ".." => {
364 // Nothing left to walk out of is a link that leaves the repository.
365 parts.pop()?;
366 }
367 name => parts.push(name),
368 }
369 }
370
371 if parts.is_empty() {
372 return None;
373 }
374
375 RepoPath::new(parts.join("/")).ok()
376}
377
378/// One page of the commit log for a revision, newest first.
379///
380/// `Ok(None)` on the same terms as [`browse_repo`]. An empty repository logs nothing
381/// rather than failing, and so does a page number past the end — which clamps to the
382/// last page there is, so a link into a branch that has since been rewritten shows
383/// history rather than a 500.
384///
385/// **Two `git` processes** rather than one: the count is what tells the page how many
386/// pages there are, and it is the same `rev-list --count` the repository page already
387/// spends on itself. Asking the log for one row past the limit would say only whether
388/// there is *a* next page, which is not enough to render "3 of 7".
389#[allow(clippy::too_many_arguments)]
390pub async fn repo_log(
391 handle: &OrgName,
392 name: &RepoName,
393 rev: Option<&RefName>,
394 page: usize,
395 actor: &Actor,
396 orgs: &impl OrgRepository,
397 memberships: &impl MembershipRepository,
398 repos: &impl RepoRepository,
399 queries: &impl GitQuery,
400) -> Result<Option<Paged<CommitSummary>>> {
401 if visible_repo(handle, name, actor, orgs, memberships, repos)
402 .await?
403 .is_none()
404 {
405 return Ok(None);
406 }
407
408 let Some(rev) = resolve_revision(handle, name, rev, queries).await? else {
409 return Ok(Some(Paged::of(Vec::new(), 0, 1, LOG_LIMIT)));
410 };
411
412 let total = queries.count_commits(handle, name, &rev).await? as usize;
413 // Clamped before the query, so a page past the end costs the same one `git log` as
414 // any other page instead of fetching an empty window and rendering nothing.
415 let page = clamp(page, page_count(total, LOG_LIMIT));
416
417 let commits = queries
418 .log(handle, name, &rev, offset(page, LOG_LIMIT), LOG_LIMIT)
419 .await?;
420
421 Ok(Some(Paged::of(commits, total, page, LOG_LIMIT)))
422}
423
424/// One path's own history, and what the path turned out to be.
425#[derive(Debug, Clone, PartialEq, Eq)]
426pub struct PathLog {
427 pub rev: RefName,
428 pub path: RepoPath,
429 /// Whether the path is a file at this revision.
430 ///
431 /// Carried rather than recomputed by the page, because it is what decided
432 /// `--follow`: a file's history is followed through the rename that gave it its
433 /// name, and git refuses `--follow` for a directory. The page also reads it to
434 /// label what it is showing the history *of*.
435 pub is_file: bool,
436 pub commits: Paged<CommitSummary>,
437 /// Whether the count stopped at the cap, so the page says `500+` rather than
438 /// claiming a number it did not finish counting. Only a followed walk — a file's —
439 /// can be capped; a directory's count is `rev-list --count` and is exact.
440 pub capped: bool,
441}
442
443/// One page of the commits that touched a path, newest first.
444///
445/// `Ok(None)` on [`browse_repo`]'s terms, plus one of its own: a path that is not
446/// there at this revision. A history page for a path with no present is a 404 rather
447/// than an empty list — the empty list is what a path that exists and has no commits
448/// would say, and the two are worth telling apart. It also means the same URL a tree
449/// or a blob 404s at, this one 404s at too.
450///
451/// **Three `git` processes at most, and usually two**: what is at the path is asked of
452/// the kept-alive `cat-file` and costs no process at all, then the count and the page
453/// are one walk each. See [`count_commits_at_path`](super::port::GitQuery::count_commits_at_path)
454/// for why the count cannot be folded into the listing.
455#[allow(clippy::too_many_arguments)]
456pub async fn repo_path_log(
457 handle: &OrgName,
458 name: &RepoName,
459 rev: Option<&RefName>,
460 path: &RepoPath,
461 page: usize,
462 actor: &Actor,
463 orgs: &impl OrgRepository,
464 memberships: &impl MembershipRepository,
465 repos: &impl RepoRepository,
466 queries: &impl GitQuery,
467) -> Result<Option<PathLog>> {
468 if visible_repo(handle, name, actor, orgs, memberships, repos)
469 .await?
470 .is_none()
471 {
472 return Ok(None);
473 }
474
475 // A repository with no commits has no path to have a history, so it is the same
476 // 404 as a path that is not there rather than an empty page.
477 let Some(rev) = resolve_revision(handle, name, rev, queries).await? else {
478 return Ok(None);
479 };
480
481 // A directory first, because that is the cheaper question and the one that settles
482 // `--follow` — exactly the order [`browse_repo`] asks in.
483 let is_file = if queries.list_tree(handle, name, &rev, path).await?.is_some() {
484 false
485 } else {
486 // Nothing is read: a cap of zero bytes still resolves the object and reports
487 // its size, which is all this needs to know it is a file.
488 let Some(_) = queries.read_blob(handle, name, &rev, path, 0).await? else {
489 return Ok(None);
490 };
491
492 true
493 };
494
495 let counted = queries
496 .count_commits_at_path(handle, name, &rev, path, is_file)
497 .await?;
498 let total = counted.total as usize;
499 // Clamped before the query for [`repo_log`]'s reason: a page past the end costs
500 // the same one walk as any other page. A capped total pages to the cap and no
501 // further, which is the whole of what was counted — so the control stays correct
502 // rather than offering a page nothing was counted for.
503 let page = clamp(page, page_count(total, LOG_LIMIT));
504
505 let commits = queries
506 .log_at_path(
507 handle,
508 name,
509 &rev,
510 path,
511 is_file,
512 offset(page, LOG_LIMIT),
513 LOG_LIMIT,
514 )
515 .await?;
516
517 Ok(Some(PathLog {
518 rev,
519 path: path.clone(),
520 is_file,
521 commits: Paged::of(commits, total, page, LOG_LIMIT),
522 capped: counted.capped,
523 }))
524}
525
526/// The branches and tags a repository has, ready for a switcher.
527///
528/// Two lists rather than one tagged list, because that is how they are shown: a
529/// visitor picking a revision is picking from branches *or* from tags, and the same
530/// name can legitimately appear in both.
531#[derive(Debug, Clone, Default, PartialEq, Eq)]
532pub struct RefList {
533 pub branches: Vec<RefName>,
534 pub tags: Vec<RefName>,
535}
536
537impl RefList {
538 pub fn is_empty(&self) -> bool {
539 self.branches.is_empty() && self.tags.is_empty()
540 }
541
542 /// Whether a revision names one of these refs.
543 ///
544 /// What a switcher uses to decide whether the current revision is a ref it can
545 /// highlight or an object id it has to show as itself.
546 pub fn contains(&self, rev: &RefName) -> bool {
547 self.branches
548 .iter()
549 .chain(&self.tags)
550 .any(|name| name == rev)
551 }
552}
553
554/// Every branch and tag, for the revision switcher.
555///
556/// `Ok(None)` on the same terms as [`browse_repo`]: invisible and absent are one answer.
557///
558/// **This costs one extra `git` process (~14ms) on top of whatever the page already
559/// spends**, so it is called by the pages that show a switcher and by nothing else. See
560/// the port's note on [`list_refs`](super::port::GitQuery::list_refs).
561///
562/// Ordering is decided here rather than in an adapter: branches then tags, each
563/// case-insensitively by name, with ties broken by the name itself so the order is
564/// total. The default branch is not floated to the top — it is usually first
565/// alphabetically anyway, and a list that reorders itself is harder to scan than one
566/// that does not.
567pub async fn list_refs(
568 handle: &OrgName,
569 name: &RepoName,
570 actor: &Actor,
571 orgs: &impl OrgRepository,
572 memberships: &impl MembershipRepository,
573 repos: &impl RepoRepository,
574 queries: &impl GitQuery,
575) -> Result<Option<RefList>> {
576 if visible_repo(handle, name, actor, orgs, memberships, repos)
577 .await?
578 .is_none()
579 {
580 return Ok(None);
581 }
582
583 Ok(Some(organise_refs(queries.list_refs(handle, name).await?)))
584}
585
586/// Splits a raw ref list into branches and tags, each in the order a switcher shows.
587///
588/// Separate from [`list_refs`] because [`repo_summary`](super::summary::repo_summary)
589/// asks the port itself — it wants the counts *and* the switcher's list from one `git`
590/// process — and two places deciding the order is two places to change it.
591pub fn organise_refs(refs: Vec<crate::domain::GitRef>) -> RefList {
592 let mut list = RefList::default();
593
594 for git_ref in refs {
595 match git_ref.kind {
596 RefKind::Branch => list.branches.push(git_ref.name),
597 RefKind::Tag => list.tags.push(git_ref.name),
598 }
599 }
600
601 for names in [&mut list.branches, &mut list.tags] {
602 names.sort_by(|left, right| {
603 left.as_str()
604 .to_lowercase()
605 .cmp(&right.as_str().to_lowercase())
606 .then_with(|| left.as_str().cmp(right.as_str()))
607 });
608 }
609
610 list
611}
612
613/// A page of refs, and whether the repository has any history at all.
614///
615/// The second field is the distinction the branches and tags pages need but a list
616/// alone cannot make: "no tags yet" and "nothing pushed yet" are different sentences,
617/// and only the second one wants the push snippet beneath it.
618///
619/// It costs **one extra `git` process**, and only when the list came back empty — which
620/// is exactly when the page has nothing else to spend.
621#[derive(Debug, Clone, PartialEq, Eq)]
622pub struct RefPage<Row> {
623 /// One page of rows, [`REF_LIMIT`] to a page.
624 ///
625 /// Sliced here rather than in the port: `for-each-ref` hands back every ref in one
626 /// process whatever the page asks for, so a `limit` on the port would buy nothing
627 /// and cost a second call for the count. See [ui.md](../../plans/ui.md#paging).
628 pub rows: Paged<Row>,
629 /// No commits have been pushed: `HEAD` names a branch that does not exist.
630 pub repo_is_empty: bool,
631}
632
633/// Cuts the page a caller asked for, or hands the whole list back as one page.
634///
635/// `None` is not a page number nobody asked for — it is the settings form's `<select>`
636/// of default branches, which is not a list a person pages through and would silently
637/// lose its 101st option to a page size. A reader gets a page; a form gets all of them.
638fn one_page<Row>(rows: Vec<Row>, page: Option<usize>) -> Paged<Row> {
639 match page {
640 Some(page) => Paged::slice(rows, page, REF_LIMIT),
641 None => {
642 let size = rows.len().max(1);
643 Paged::slice(rows, 1, size)
644 }
645 }
646}
647
648/// Every branch, in the order the branches page shows them.
649///
650/// `Ok(None)` on the same terms as [`browse_repo`]: invisible and absent are one answer.
651///
652/// **One `git` process** — see [`branches`](super::port::GitQuery::branches) — plus one
653/// more only when there are no branches, to tell an empty repository from a repository
654/// whose refs are all tags.
655///
656/// Deliberately **no ahead/behind counts**: a count against the default branch is a
657/// `rev-list` per branch, so a repository with twenty branches would fork twenty extra
658/// processes to decorate one page. That is exactly the cost
659/// [0006](../../plans/decisions/0006-git-binary-behind-narrow-ports.md) bounds, and it
660/// stays out until something keeps git alive between questions.
661#[allow(clippy::too_many_arguments)]
662pub async fn list_branches(
663 handle: &OrgName,
664 name: &RepoName,
665 page: Option<usize>,
666 actor: &Actor,
667 orgs: &impl OrgRepository,
668 memberships: &impl MembershipRepository,
669 repos: &impl RepoRepository,
670 queries: &impl GitQuery,
671) -> Result<Option<RefPage<BranchRow>>> {
672 if visible_repo(handle, name, actor, orgs, memberships, repos)
673 .await?
674 .is_none()
675 {
676 return Ok(None);
677 }
678
679 let rows = pin_default(queries.branches(handle, name).await?);
680 let empty = rows.is_empty() && !has_commits(handle, name, queries).await?;
681
682 Ok(Some(RefPage {
683 rows: one_page(rows, page),
684 repo_is_empty: empty,
685 }))
686}
687
688/// Every tag, newest first. Authorized and costed exactly as [`list_branches`] is.
689#[allow(clippy::too_many_arguments)]
690pub async fn list_tags(
691 handle: &OrgName,
692 name: &RepoName,
693 page: Option<usize>,
694 actor: &Actor,
695 orgs: &impl OrgRepository,
696 memberships: &impl MembershipRepository,
697 repos: &impl RepoRepository,
698 queries: &impl GitQuery,
699) -> Result<Option<RefPage<TagRow>>> {
700 if visible_repo(handle, name, actor, orgs, memberships, repos)
701 .await?
702 .is_none()
703 {
704 return Ok(None);
705 }
706
707 let rows = queries.tags(handle, name).await?;
708 let empty = rows.is_empty() && !has_commits(handle, name, queries).await?;
709
710 Ok(Some(RefPage {
711 rows: one_page(rows, page),
712 repo_is_empty: empty,
713 }))
714}
715
716/// Whether anything has been pushed. One `git` process, asked only on an empty page.
717async fn has_commits(handle: &OrgName, name: &RepoName, queries: &impl GitQuery) -> Result<bool> {
718 Ok(queries.default_branch(handle, name).await?.is_some())
719}
720
721/// Moves the default branch to the front, leaving everything else in git's date order.
722///
723/// A display decision rather than the adapter's: the default branch is the one a
724/// visitor came for, and it is not reliably the most recently pushed — a repository
725/// whose work happens on feature branches would bury `main` halfway down a page
726/// otherwise. Everything below it stays newest-first, which is the ordering that
727/// answers "what is being worked on".
728///
729/// A stable partition rather than a sort, so the date order it was given survives.
730fn pin_default(rows: Vec<BranchRow>) -> Vec<BranchRow> {
731 let (default, rest): (Vec<_>, Vec<_>) = rows.into_iter().partition(|row| row.is_default);
732
733 default.into_iter().chain(rest).collect()
734}
735
736/// A file as it is served rather than rendered.
737#[derive(Debug, Clone, PartialEq, Eq)]
738pub enum RawFile {
739 Ready {
740 /// The file's own name, for the download it becomes.
741 name: String,
742 content: Vec<u8>,
743 },
744 /// Bigger than [`MAX_RAW_BYTES`]. Reported rather than served, because the port
745 /// reads bytes into memory; the size is carried so the refusal can say why.
746 TooLarge { size: u64 },
747}
748
749/// Reads a file for serving verbatim.
750///
751/// Authorized exactly as [`browse_repo`] is, through [`view_repo`], so a repository
752/// invisible on its page is invisible here too — a raw URL is not a side door.
753///
754/// `Ok(None)` for a repository that is invisible or absent, a revision that is not
755/// there, a path that is not there, and a path that is a directory. All of them are one
756/// answer for the reason [`view_repo`] gives, and a directory is included because there
757/// is no such thing as raw bytes for one.
758#[allow(clippy::too_many_arguments)]
759pub async fn read_raw_file(
760 handle: &OrgName,
761 name: &RepoName,
762 rev: Option<&RefName>,
763 path: &RepoPath,
764 actor: &Actor,
765 orgs: &impl OrgRepository,
766 memberships: &impl MembershipRepository,
767 repos: &impl RepoRepository,
768 queries: &impl GitQuery,
769) -> Result<Option<RawFile>> {
770 if visible_repo(handle, name, actor, orgs, memberships, repos)
771 .await?
772 .is_none()
773 {
774 return Ok(None);
775 }
776
777 let Some(rev) = resolve_revision(handle, name, rev, queries).await? else {
778 return Ok(None);
779 };
780
781 // Straight to the blob: unlike a browse, there is no directory case to serve, so
782 // asking `list_tree` first would spend a whole process learning that a path is not
783 // something this endpoint can answer for. `read_blob` already says `None` for a
784 // tree.
785 let Some(blob) = queries
786 .read_blob(handle, name, &rev, path, MAX_RAW_BYTES)
787 .await?
788 else {
789 return Ok(None);
790 };
791
792 let Some(content) = blob.content else {
793 return Ok(Some(RawFile::TooLarge { size: blob.size }));
794 };
795
796 Ok(Some(RawFile::Ready {
797 // A path that resolved to a blob has a last component by construction: the root
798 // is a tree, and `read_blob` refuses it.
799 name: path.file_name().unwrap_or_default().to_owned(),
800 content,
801 }))
802}
803
804/// Settles which revision is being asked about.
805///
806/// `None` out means the repository has no commits at all — not that the revision was
807/// wrong, which surfaces later as nothing being found at the path.
808pub(crate) async fn resolve_revision(
809 handle: &OrgName,
810 name: &RepoName,
811 rev: Option<&RefName>,
812 queries: &impl GitQuery,
813) -> Result<Option<RefName>> {
814 match rev {
815 Some(rev) => Ok(Some(rev.clone())),
816 None => Ok(queries.default_branch(handle, name).await?),
817 }
818}
819
820/// Decides what can be done with a blob's bytes.
821///
822/// The port carries bytes and a size; turning those into "text", "binary" or "too big"
823/// is a display decision, so it happens here rather than in the adapter.
824fn view_of(blob: Blob) -> FileView {
825 let too_large = blob.content.is_none();
826 let text = blob.content.and_then(|bytes| String::from_utf8(bytes).ok());
827
828 FileView {
829 id: blob.id,
830 size: blob.size,
831 text,
832 too_large,
833 }
834}
835
836#[cfg(test)]
837mod tests {
838 use std::time::SystemTime;
839
840 use super::*;
841 use crate::{
842 domain::{
843 EntryKind, Membership, MembershipId, OrgId, Organization, RepoId, Repository,
844 TreeEntry, UserId, Visibility,
845 },
846 infrastructure::{
847 git::InMemoryGitQuery,
848 repository::{InMemoryMembershipRepo, InMemoryOrgRepo, InMemoryRepoRepo},
849 },
850 };
851
852 struct Fixture {
853 orgs: InMemoryOrgRepo,
854 memberships: InMemoryMembershipRepo,
855 repos: InMemoryRepoRepo,
856 handle: OrgName,
857 owner: Actor,
858 stranger: Actor,
859 }
860
861 /// One organisation with an owner, and a `steid` repository of the given visibility.
862 async fn fixture(visibility: Visibility) -> Fixture {
863 let orgs = InMemoryOrgRepo::new();
864 let memberships = InMemoryMembershipRepo::new();
865 let repos = InMemoryRepoRepo::new();
866
867 let org = Organization::new(OrgId::generate(), "acme", None).expect("valid org");
868 orgs.save(&org).await.expect("save org");
869
870 let owner = UserId::generate();
871 memberships
872 .save(&Membership::new(
873 MembershipId::generate(),
874 org.id.clone(),
875 owner.clone(),
876 crate::domain::Role::Owner,
877 ))
878 .await
879 .expect("save membership");
880
881 repos
882 .save(
883 &Repository::new(
884 RepoId::generate(),
885 org.id.clone(),
886 "steid",
887 None,
888 visibility,
889 SystemTime::now(),
890 )
891 .expect("valid repository"),
892 )
893 .await
894 .expect("save repo");
895
896 Fixture {
897 orgs,
898 memberships,
899 repos,
900 handle: org.name,
901 owner: Actor::User(owner),
902 stranger: Actor::Anonymous,
903 }
904 }
905
906 fn repo_name() -> RepoName {
907 RepoName::new("steid").expect("valid repository name")
908 }
909
910 fn rev(value: &str) -> RefName {
911 RefName::new(value).expect("valid revision")
912 }
913
914 fn path(value: &str) -> RepoPath {
915 RepoPath::new(value).expect("valid path")
916 }
917
918 impl Fixture {
919 async fn refs(&self, actor: &Actor, queries: &InMemoryGitQuery) -> Result<Option<RefList>> {
920 list_refs(
921 &self.handle,
922 &repo_name(),
923 actor,
924 &self.orgs,
925 &self.memberships,
926 &self.repos,
927 queries,
928 )
929 .await
930 }
931
932 async fn raw(
933 &self,
934 actor: &Actor,
935 path: &RepoPath,
936 queries: &InMemoryGitQuery,
937 ) -> Result<Option<RawFile>> {
938 read_raw_file(
939 &self.handle,
940 &repo_name(),
941 Some(&rev("main")),
942 path,
943 actor,
944 &self.orgs,
945 &self.memberships,
946 &self.repos,
947 queries,
948 )
949 .await
950 }
951 }
952
953 // --- repo_log -------------------------------------------------------------------
954
955 /// `count` commits, newest first, each identifiable by its summary.
956 fn history(count: usize) -> Vec<CommitSummary> {
957 (0..count)
958 .map(|n| CommitSummary {
959 id: ObjectId::from_trusted(format!("{n:040x}")),
960 summary: format!("commit {n}"),
961 author_name: "Ada Lovelace".to_owned(),
962 committed_at: at(n as u64),
963 })
964 .collect()
965 }
966
967 async fn log_page(
968 f: &Fixture,
969 queries: &InMemoryGitQuery,
970 page: usize,
971 ) -> Paged<CommitSummary> {
972 repo_log(
973 &f.handle,
974 &repo_name(),
975 Some(&rev("main")),
976 page,
977 &f.owner,
978 &f.orgs,
979 &f.memberships,
980 &f.repos,
981 queries,
982 )
983 .await
984 .expect("should read")
985 .expect("visible")
986 }
987
988 #[tokio::test]
989 async fn the_second_page_of_a_log_starts_where_the_first_ended() {
990 let f = fixture(Visibility::Public).await;
991 let queries = InMemoryGitQuery::new().with_log(history(LOG_LIMIT + 10));
992
993 let first = log_page(&f, &queries, 1).await;
994 let second = log_page(&f, &queries, 2).await;
995
996 assert_eq!(first.items.len(), LOG_LIMIT);
997 assert_eq!(second.items.len(), 10);
998 assert_eq!(second.offset(), LOG_LIMIT);
999 assert_eq!(second.items[0].summary, format!("commit {LOG_LIMIT}"));
1000 assert_eq!(second.pages, 2);
1001 assert_eq!(second.total, LOG_LIMIT + 10);
1002 }
1003
1004 #[tokio::test]
1005 async fn a_log_page_past_the_end_clamps_to_the_last_one() {
1006 // The shape a link into a rewritten branch takes: the page number is still in
1007 // the URL, the history behind it is not.
1008 let f = fixture(Visibility::Public).await;
1009 let queries = InMemoryGitQuery::new().with_log(history(LOG_LIMIT + 10));
1010
1011 let page = log_page(&f, &queries, 400).await;
1012
1013 assert_eq!(page.page, 2);
1014 assert_eq!(page.items.len(), 10);
1015 }
1016
1017 #[tokio::test]
1018 async fn a_log_that_fits_on_one_page_is_not_paged() {
1019 let f = fixture(Visibility::Public).await;
1020 let queries = InMemoryGitQuery::new().with_log(history(3));
1021
1022 let page = log_page(&f, &queries, 1).await;
1023
1024 assert!(!page.is_paged());
1025 assert_eq!(page.total, 3);
1026 }
1027
1028 #[tokio::test]
1029 async fn an_empty_repository_logs_one_empty_page() {
1030 let f = fixture(Visibility::Public).await;
1031 let queries = InMemoryGitQuery::empty();
1032
1033 let page = repo_log(
1034 &f.handle,
1035 &repo_name(),
1036 None,
1037 1,
1038 &f.owner,
1039 &f.orgs,
1040 &f.memberships,
1041 &f.repos,
1042 &queries,
1043 )
1044 .await
1045 .expect("should read")
1046 .expect("visible");
1047
1048 assert!(page.items.is_empty());
1049 assert!(!page.is_paged());
1050 }
1051
1052 #[tokio::test]
1053 async fn a_log_is_invisible_to_a_stranger_when_the_repository_is() {
1054 let f = fixture(Visibility::Private).await;
1055 let queries = InMemoryGitQuery::new().with_log(history(3));
1056
1057 let seen = repo_log(
1058 &f.handle,
1059 &repo_name(),
1060 None,
1061 1,
1062 &f.stranger,
1063 &f.orgs,
1064 &f.memberships,
1065 &f.repos,
1066 &queries,
1067 )
1068 .await
1069 .expect("should read");
1070
1071 assert!(seen.is_none());
1072 }
1073
1074 // --- submodules and symlinks ----------------------------------------------------
1075
1076 /// What a listing at `at` resolves to for the owner.
1077 async fn browsed(f: &Fixture, queries: &InMemoryGitQuery, at: &str) -> Option<Browsed> {
1078 browse_repo(
1079 &f.handle,
1080 &repo_name(),
1081 Some(&rev("main")),
1082 &path(at),
1083 &f.owner,
1084 &f.orgs,
1085 &f.memberships,
1086 &f.repos,
1087 queries,
1088 )
1089 .await
1090 .expect("should read")
1091 }
1092
1093 #[test]
1094 fn a_gitmodules_gives_each_submodules_path_and_url() {
1095 let found = parse_gitmodules(
1096 "[submodule \"topcoat\"]\n\
1097 \tpath = vendor/topcoat\n\
1098 \turl = https://github.com/tokio-rs/topcoat.git\n\
1099 [submodule \"docs\"]\n\
1100 \tpath = docs/theme\n\
1101 \turl = https://example.com/theme\n",
1102 );
1103
1104 assert_eq!(
1105 found,
1106 [
1107 (
1108 "vendor/topcoat".to_owned(),
1109 "https://github.com/tokio-rs/topcoat.git".to_owned()
1110 ),
1111 (
1112 "docs/theme".to_owned(),
1113 "https://example.com/theme".to_owned()
1114 ),
1115 ]
1116 );
1117 }
1118
1119 #[test]
1120 fn a_url_a_browser_cannot_open_is_not_offered_as_a_link() {
1121 // All three are legitimate in a real `.gitmodules` and none of them is a page.
1122 for url in [
1123 "git@github.com:ada/steid.git",
1124 "ssh://git@example.com/ada/steid",
1125 "../sibling",
1126 "http://example.com/insecure",
1127 ] {
1128 let text = format!("[submodule \"x\"]\npath = vendor/x\nurl = {url}\n");
1129
1130 assert!(
1131 parse_gitmodules(&text).is_empty(),
1132 "{url} should not become a link"
1133 );
1134 }
1135 }
1136
1137 #[test]
1138 fn a_gitmodules_survives_comments_quotes_and_a_missing_half() {
1139 let found = parse_gitmodules(
1140 "# a comment\n\
1141 ; another\n\
1142 [submodule \"quoted\"]\n\
1143 path = \"vendor/quoted\"\n\
1144 url = \"https://example.com/quoted\"\n\
1145 [submodule \"no-url\"]\n\
1146 path = vendor/orphan\n\
1147 [submodule \"no-path\"]\n\
1148 url = https://example.com/orphan\n",
1149 );
1150
1151 // A section missing either half contributes nothing rather than pairing itself
1152 // with a neighbour's value.
1153 assert_eq!(
1154 found,
1155 [(
1156 "vendor/quoted".to_owned(),
1157 "https://example.com/quoted".to_owned()
1158 )]
1159 );
1160 }
1161
1162 #[test]
1163 fn a_relative_target_resolves_against_the_directory_it_is_written_in() {
1164 let at = |dir: &str, target: &str| {
1165 resolve_relative(&RepoPath::from_trusted(dir), target)
1166 .map(|path| path.as_str().to_owned())
1167 };
1168
1169 assert_eq!(at("src", "main.rs").as_deref(), Some("src/main.rs"));
1170 assert_eq!(at("src", "./main.rs").as_deref(), Some("src/main.rs"));
1171 assert_eq!(
1172 at("src/web", "../domain/id.rs").as_deref(),
1173 Some("src/domain/id.rs")
1174 );
1175 assert_eq!(at("", "README.md").as_deref(), Some("README.md"));
1176 assert_eq!(
1177 at("docs/a/b", "../../../LICENSE").as_deref(),
1178 Some("LICENSE")
1179 );
1180 }
1181
1182 #[test]
1183 fn a_target_that_leaves_the_repository_resolves_to_nothing() {
1184 let at = |dir: &str, target: &str| resolve_relative(&RepoPath::from_trusted(dir), target);
1185
1186 // Each of these is a link Steid can show and must not follow.
1187 assert!(at("src", "../../etc/passwd").is_none());
1188 assert!(at("", "/etc/passwd").is_none());
1189 assert!(at("src", "..").is_none());
1190 assert!(at("src", "").is_none());
1191 // A colon is refused by `RepoPath` itself, because git reads it as a revision
1192 // separator.
1193 assert!(at("src", "weird:name").is_none());
1194 }
1195
1196 #[tokio::test]
1197 async fn a_submodule_is_linked_to_the_upstream_gitmodules_names() {
1198 let f = fixture(Visibility::Public).await;
1199 let queries = InMemoryGitQuery::new()
1200 .with_tree(
1201 "main",
1202 "vendor",
1203 vec![TreeEntry {
1204 name: "topcoat".to_owned(),
1205 kind: EntryKind::Submodule,
1206 id: ObjectId::from_trusted("c".repeat(40)),
1207 size: None,
1208 }],
1209 )
1210 .with_blob(
1211 "main",
1212 ".gitmodules",
1213 "[submodule \"topcoat\"]\npath = vendor/topcoat\nurl = https://example.com/topcoat\n"
1214 .as_bytes()
1215 .to_vec(),
1216 );
1217
1218 let Some(Browsed::Directory { details, .. }) = browsed(&f, &queries, "vendor").await else {
1219 panic!("a directory");
1220 };
1221
1222 // Keyed by the path from the root, which is what `.gitmodules` records — the
1223 // entry's own name is only its last component.
1224 assert_eq!(
1225 details["topcoat"].url.as_deref(),
1226 Some("https://example.com/topcoat")
1227 );
1228 }
1229
1230 #[tokio::test]
1231 async fn a_symlink_carries_its_target_and_where_that_lands() {
1232 let f = fixture(Visibility::Public).await;
1233 let inside = ObjectId::from_trusted("d".repeat(40));
1234 let outside = ObjectId::from_trusted("e".repeat(40));
1235 let queries = InMemoryGitQuery::new()
1236 .with_tree(
1237 "main",
1238 "src",
1239 vec![
1240 TreeEntry {
1241 name: "here".to_owned(),
1242 kind: EntryKind::Symlink,
1243 id: inside.clone(),
1244 size: Some(9),
1245 },
1246 TreeEntry {
1247 name: "elsewhere".to_owned(),
1248 kind: EntryKind::Symlink,
1249 id: outside.clone(),
1250 size: Some(11),
1251 },
1252 ],
1253 )
1254 .with_symlink_target(&inside, "../README.md")
1255 .with_symlink_target(&outside, "/etc/passwd");
1256
1257 let Some(Browsed::Directory { details, .. }) = browsed(&f, &queries, "src").await else {
1258 panic!("a directory");
1259 };
1260
1261 assert_eq!(details["here"].target.as_deref(), Some("../README.md"));
1262 assert_eq!(
1263 details["here"].resolved.as_ref().map(RepoPath::as_str),
1264 Some("README.md")
1265 );
1266 // Shown, and not followed: the target is still worth saying.
1267 assert_eq!(details["elsewhere"].target.as_deref(), Some("/etc/passwd"));
1268 assert!(details["elsewhere"].resolved.is_none());
1269 }
1270
1271 #[tokio::test]
1272 async fn an_ordinary_directory_asks_for_no_details_at_all() {
1273 let f = fixture(Visibility::Public).await;
1274 let queries = InMemoryGitQuery::new().with_tree(
1275 "main",
1276 "src",
1277 vec![TreeEntry {
1278 name: "main.rs".to_owned(),
1279 kind: EntryKind::Blob,
1280 id: ObjectId::from_trusted("a".repeat(40)),
1281 size: Some(12),
1282 }],
1283 );
1284
1285 let Some(Browsed::Directory { details, .. }) = browsed(&f, &queries, "src").await else {
1286 panic!("a directory");
1287 };
1288
1289 assert!(details.is_empty());
1290 }
1291
1292 // --- repo_path_log --------------------------------------------------------------
1293
1294 async fn path_log(
1295 f: &Fixture,
1296 queries: &InMemoryGitQuery,
1297 at: &str,
1298 page: usize,
1299 ) -> Option<PathLog> {
1300 repo_path_log(
1301 &f.handle,
1302 &repo_name(),
1303 Some(&rev("main")),
1304 &path(at),
1305 page,
1306 &f.owner,
1307 &f.orgs,
1308 &f.memberships,
1309 &f.repos,
1310 queries,
1311 )
1312 .await
1313 .expect("should read")
1314 }
1315
1316 /// A repository whose `src` directory holds one file, both with a history.
1317 fn with_history() -> InMemoryGitQuery {
1318 InMemoryGitQuery::new()
1319 .with_tree(
1320 "main",
1321 "src",
1322 vec![TreeEntry {
1323 name: "main.rs".to_owned(),
1324 kind: EntryKind::Blob,
1325 id: ObjectId::from_trusted("a".repeat(40)),
1326 size: Some(12),
1327 }],
1328 )
1329 .with_blob("main", "src/main.rs", b"fn main() {}".to_vec())
1330 .with_path_log("main", "src", history(LOG_LIMIT + 4))
1331 .with_path_log("main", "src/main.rs", history(2))
1332 }
1333
1334 #[tokio::test]
1335 async fn a_files_history_is_followed_and_a_directorys_is_not() {
1336 let f = fixture(Visibility::Public).await;
1337 let queries = with_history();
1338
1339 // The flag the port turns into `--follow`, decided by what is at the path
1340 // rather than by the caller guessing.
1341 assert!(
1342 path_log(&f, &queries, "src/main.rs", 1)
1343 .await
1344 .expect("found")
1345 .is_file
1346 );
1347 assert!(
1348 !path_log(&f, &queries, "src", 1)
1349 .await
1350 .expect("found")
1351 .is_file
1352 );
1353 }
1354
1355 #[tokio::test]
1356 async fn a_paths_history_pages_like_every_other_list() {
1357 let f = fixture(Visibility::Public).await;
1358 let queries = with_history();
1359
1360 let second = path_log(&f, &queries, "src", 2).await.expect("found");
1361
1362 assert_eq!(second.commits.items.len(), 4);
1363 assert_eq!(second.commits.total, LOG_LIMIT + 4);
1364 assert_eq!(second.commits.offset(), LOG_LIMIT);
1365 // A page past the end clamps rather than 404s, the same as the log's.
1366 assert_eq!(
1367 path_log(&f, &queries, "src", 400)
1368 .await
1369 .expect("found")
1370 .commits
1371 .page,
1372 2
1373 );
1374 }
1375
1376 #[tokio::test]
1377 async fn a_long_followed_history_stops_counting_at_the_cap() {
1378 // `--follow` reads a tree per commit, so an uncapped count on a long history is
1379 // the read likeliest to time out. Past the cap the total is the cap and the page
1380 // says so; the paging control offers exactly the pages that were counted.
1381 use crate::infrastructure::git_query::FOLLOWED_LOG_SCAN;
1382
1383 let f = fixture(Visibility::Public).await;
1384 let queries = with_history().with_path_log(
1385 "main",
1386 "src/main.rs",
1387 history(FOLLOWED_LOG_SCAN + LOG_LIMIT),
1388 );
1389
1390 let log = path_log(&f, &queries, "src/main.rs", 1)
1391 .await
1392 .expect("found");
1393
1394 assert!(log.capped);
1395 assert_eq!(log.commits.total, FOLLOWED_LOG_SCAN);
1396 assert_eq!(log.commits.pages, FOLLOWED_LOG_SCAN / LOG_LIMIT);
1397
1398 // The last page the control offers is a page that was counted, and clamping
1399 // lands there rather than on a page beyond the cap.
1400 let last = path_log(&f, &queries, "src/main.rs", 999)
1401 .await
1402 .expect("found");
1403 assert_eq!(last.commits.page, FOLLOWED_LOG_SCAN / LOG_LIMIT);
1404 assert_eq!(last.commits.items.len(), LOG_LIMIT);
1405 }
1406
1407 #[tokio::test]
1408 async fn a_directorys_count_is_exact_because_it_is_not_followed() {
1409 let f = fixture(Visibility::Public).await;
1410
1411 assert!(
1412 !path_log(&f, &with_history(), "src", 1)
1413 .await
1414 .expect("found")
1415 .capped
1416 );
1417 }
1418
1419 #[tokio::test]
1420 async fn a_path_that_is_not_there_has_no_history_page() {
1421 // A 404 rather than an empty list: an empty list is what a path that exists and
1422 // was never touched would say, and a reader should be able to tell them apart.
1423 let f = fixture(Visibility::Public).await;
1424
1425 assert!(path_log(&f, &with_history(), "nope.rs", 1).await.is_none());
1426 }
1427
1428 #[tokio::test]
1429 async fn an_empty_repository_has_no_path_to_have_a_history() {
1430 let f = fixture(Visibility::Public).await;
1431
1432 assert!(
1433 path_log(&f, &InMemoryGitQuery::empty(), "src", 1)
1434 .await
1435 .is_none()
1436 );
1437 }
1438
1439 #[tokio::test]
1440 async fn a_paths_history_is_invisible_to_a_stranger_when_the_repository_is() {
1441 let f = fixture(Visibility::Private).await;
1442
1443 let seen = repo_path_log(
1444 &f.handle,
1445 &repo_name(),
1446 Some(&rev("main")),
1447 &path("src"),
1448 1,
1449 &f.stranger,
1450 &f.orgs,
1451 &f.memberships,
1452 &f.repos,
1453 &with_history(),
1454 )
1455 .await
1456 .expect("should read");
1457
1458 assert!(seen.is_none());
1459 }
1460
1461 // --- list_branches and list_tags ------------------------------------------------
1462
1463 fn at(offset: u64) -> SystemTime {
1464 std::time::UNIX_EPOCH + std::time::Duration::from_secs(1_700_000_000 + offset)
1465 }
1466
1467 #[tokio::test]
1468 async fn the_default_branch_is_pinned_above_the_rest() {
1469 let f = fixture(Visibility::Public).await;
1470 // Seeded in git's order — newest tip first — with the default branch stalest,
1471 // which is the case pinning exists for.
1472 let queries = InMemoryGitQuery::new()
1473 .with_branch_row("feature/login", false, at(200))
1474 .with_branch_row("spike", false, at(100))
1475 .with_branch_row("main", true, at(0));
1476
1477 let page = list_branches(
1478 &f.handle,
1479 &repo_name(),
1480 Some(1),
1481 &f.owner,
1482 &f.orgs,
1483 &f.memberships,
1484 &f.repos,
1485 &queries,
1486 )
1487 .await
1488 .expect("should read")
1489 .expect("visible");
1490
1491 assert_eq!(
1492 page.rows
1493 .items
1494 .iter()
1495 .map(|row| row.name.as_str())
1496 .collect::<Vec<_>>(),
1497 vec!["main", "feature/login", "spike"]
1498 );
1499 // Pinning must not disturb the date order of everything below it.
1500 assert!(!page.repo_is_empty);
1501 }
1502
1503 #[tokio::test]
1504 async fn a_repository_with_no_branches_says_it_is_empty() {
1505 // `InMemoryGitQuery::empty()` has no default branch, which is what "nothing has
1506 // been pushed" looks like — and what makes the page show the push snippet.
1507 let f = fixture(Visibility::Public).await;
1508
1509 let page = list_branches(
1510 &f.handle,
1511 &repo_name(),
1512 Some(1),
1513 &f.owner,
1514 &f.orgs,
1515 &f.memberships,
1516 &f.repos,
1517 &InMemoryGitQuery::empty(),
1518 )
1519 .await
1520 .expect("should read")
1521 .expect("visible");
1522
1523 assert!(page.rows.items.is_empty());
1524 assert!(page.repo_is_empty);
1525 }
1526
1527 #[tokio::test]
1528 async fn a_repository_with_commits_but_no_tags_is_not_empty() {
1529 // The distinction the page needs: "no tags yet" rather than "nothing pushed".
1530 let f = fixture(Visibility::Public).await;
1531
1532 let page = list_tags(
1533 &f.handle,
1534 &repo_name(),
1535 Some(1),
1536 &f.owner,
1537 &f.orgs,
1538 &f.memberships,
1539 &f.repos,
1540 &InMemoryGitQuery::new(),
1541 )
1542 .await
1543 .expect("should read")
1544 .expect("visible");
1545
1546 assert!(page.rows.items.is_empty());
1547 assert!(!page.repo_is_empty);
1548 }
1549
1550 #[tokio::test]
1551 async fn tags_keep_the_order_git_sorted_them_into() {
1552 let f = fixture(Visibility::Public).await;
1553 let queries = InMemoryGitQuery::new()
1554 .with_tag_row("v2.0", true, at(200))
1555 .with_tag_row("v0.9", false, at(100));
1556
1557 let page = list_tags(
1558 &f.handle,
1559 &repo_name(),
1560 Some(1),
1561 &f.owner,
1562 &f.orgs,
1563 &f.memberships,
1564 &f.repos,
1565 &queries,
1566 )
1567 .await
1568 .expect("should read")
1569 .expect("visible");
1570
1571 assert_eq!(
1572 page.rows
1573 .items
1574 .iter()
1575 .map(|row| row.name.as_str())
1576 .collect::<Vec<_>>(),
1577 vec!["v2.0", "v0.9"]
1578 );
1579 assert_eq!(page.rows.items[0].message.as_deref(), Some("release v2.0"));
1580 assert_eq!(page.rows.items[1].message, None);
1581 }
1582
1583 #[tokio::test]
1584 async fn the_second_page_of_branches_starts_where_the_first_ended() {
1585 let f = fixture(Visibility::Public).await;
1586 let mut queries = InMemoryGitQuery::new();
1587
1588 for n in 0..REF_LIMIT + 5 {
1589 queries = queries.with_branch_row(&format!("branch-{n:03}"), n == 0, at(n as u64));
1590 }
1591
1592 let first = list_branches(
1593 &f.handle,
1594 &repo_name(),
1595 Some(1),
1596 &f.owner,
1597 &f.orgs,
1598 &f.memberships,
1599 &f.repos,
1600 &queries,
1601 )
1602 .await
1603 .expect("should read")
1604 .expect("visible");
1605 let second = list_branches(
1606 &f.handle,
1607 &repo_name(),
1608 Some(2),
1609 &f.owner,
1610 &f.orgs,
1611 &f.memberships,
1612 &f.repos,
1613 &queries,
1614 )
1615 .await
1616 .expect("should read")
1617 .expect("visible");
1618
1619 assert_eq!(first.rows.items.len(), REF_LIMIT);
1620 assert_eq!(second.rows.items.len(), 5);
1621 assert_eq!(second.rows.offset(), REF_LIMIT);
1622 assert_eq!(second.rows.total, REF_LIMIT + 5);
1623 assert_eq!(first.rows.items[REF_LIMIT - 1].name.as_str(), "branch-099");
1624 assert_eq!(
1625 second.rows.items[0].name.as_str(),
1626 "branch-100",
1627 "the second page starts where the first ended"
1628 );
1629 }
1630
1631 #[tokio::test]
1632 async fn no_page_number_means_every_branch() {
1633 // What the settings form's default-branch `<select>` asks for: an option
1634 // missing from it is a branch nobody can choose.
1635 let f = fixture(Visibility::Public).await;
1636 let mut queries = InMemoryGitQuery::new();
1637
1638 for n in 0..REF_LIMIT + 5 {
1639 queries = queries.with_branch_row(&format!("branch-{n:03}"), n == 0, at(n as u64));
1640 }
1641
1642 let all = list_branches(
1643 &f.handle,
1644 &repo_name(),
1645 None,
1646 &f.owner,
1647 &f.orgs,
1648 &f.memberships,
1649 &f.repos,
1650 &queries,
1651 )
1652 .await
1653 .expect("should read")
1654 .expect("visible");
1655
1656 assert_eq!(all.rows.items.len(), REF_LIMIT + 5);
1657 assert!(!all.rows.is_paged());
1658 }
1659
1660 #[tokio::test]
1661 async fn a_private_repositorys_branches_and_tags_are_invisible_to_a_stranger() {
1662 // A branch name is content, the same way the switcher's list is.
1663 let f = fixture(Visibility::Private).await;
1664 let queries = InMemoryGitQuery::new()
1665 .with_branch_row("secret-work", true, at(0))
1666 .with_tag_row("unreleased", true, at(0));
1667
1668 assert!(
1669 list_branches(
1670 &f.handle,
1671 &repo_name(),
1672 Some(1),
1673 &f.stranger,
1674 &f.orgs,
1675 &f.memberships,
1676 &f.repos,
1677 &queries,
1678 )
1679 .await
1680 .expect("should read")
1681 .is_none()
1682 );
1683 assert!(
1684 list_tags(
1685 &f.handle,
1686 &repo_name(),
1687 Some(1),
1688 &f.stranger,
1689 &f.orgs,
1690 &f.memberships,
1691 &f.repos,
1692 &queries,
1693 )
1694 .await
1695 .expect("should read")
1696 .is_none()
1697 );
1698 }
1699
1700 // --- list_refs ----------------------------------------------------------------
1701
1702 #[tokio::test]
1703 async fn branches_and_tags_come_back_separated_and_ordered() {
1704 let f = fixture(Visibility::Public).await;
1705 let queries = InMemoryGitQuery::new()
1706 .with_branch("main")
1707 .with_branch("Feature")
1708 .with_tag("v2.0")
1709 .with_tag("v1.0");
1710
1711 let refs = f
1712 .refs(&f.owner, &queries)
1713 .await
1714 .expect("should read")
1715 .expect("visible");
1716
1717 // Case-insensitively, so `Feature` sorts next to `feature` rather than before
1718 // every lowercase name.
1719 assert_eq!(
1720 refs.branches
1721 .iter()
1722 .map(RefName::as_str)
1723 .collect::<Vec<_>>(),
1724 vec!["Feature", "main"]
1725 );
1726 assert_eq!(
1727 refs.tags.iter().map(RefName::as_str).collect::<Vec<_>>(),
1728 vec!["v1.0", "v2.0"]
1729 );
1730 }
1731
1732 #[tokio::test]
1733 async fn an_empty_repository_has_no_refs_to_switch_between() {
1734 let f = fixture(Visibility::Public).await;
1735
1736 let refs = f
1737 .refs(&f.owner, &InMemoryGitQuery::empty())
1738 .await
1739 .expect("should read")
1740 .expect("visible");
1741
1742 assert!(refs.is_empty());
1743 }
1744
1745 #[tokio::test]
1746 async fn a_private_repositorys_refs_are_invisible_to_a_stranger() {
1747 // The ref list names branches, which are content. Same answer as the page.
1748 let f = fixture(Visibility::Private).await;
1749 let queries = InMemoryGitQuery::new().with_branch("secret-work");
1750
1751 assert!(
1752 f.refs(&f.stranger, &queries)
1753 .await
1754 .expect("should read")
1755 .is_none()
1756 );
1757 assert!(
1758 f.refs(&f.owner, &queries)
1759 .await
1760 .expect("should read")
1761 .is_some()
1762 );
1763 }
1764
1765 #[test]
1766 fn a_ref_list_knows_the_revision_it_is_showing() {
1767 let refs = RefList {
1768 branches: vec![RefName::from_trusted("main")],
1769 tags: vec![RefName::from_trusted("v1.0")],
1770 };
1771
1772 assert!(refs.contains(&rev("main")));
1773 assert!(refs.contains(&rev("v1.0")));
1774 // An object id is not a ref, which is what a switcher needs to know before it
1775 // tries to highlight one.
1776 assert!(!refs.contains(&rev("0123456789abcdef0123456789abcdef01234567")));
1777 }
1778
1779 // --- read_raw_file ------------------------------------------------------------
1780
1781 #[tokio::test]
1782 async fn a_text_file_comes_back_with_its_own_name() {
1783 let f = fixture(Visibility::Public).await;
1784 let queries = InMemoryGitQuery::new().with_blob("main", "src/main.rs", b"fn main() {}\n");
1785
1786 let raw = f
1787 .raw(&f.owner, &path("src/main.rs"), &queries)
1788 .await
1789 .expect("should read")
1790 .expect("found");
1791
1792 assert_eq!(
1793 raw,
1794 RawFile::Ready {
1795 name: "main.rs".to_owned(),
1796 content: b"fn main() {}\n".to_vec(),
1797 }
1798 );
1799 }
1800
1801 #[tokio::test]
1802 async fn a_binary_file_comes_back_byte_for_byte() {
1803 // The whole point of the endpoint: no decoding, no lossy UTF-8, no truncation.
1804 let f = fixture(Visibility::Public).await;
1805 let bytes: Vec<u8> = (0..=255u8).chain(0..=255u8).collect();
1806 let queries = InMemoryGitQuery::new().with_blob("main", "logo.png", bytes.clone());
1807
1808 let raw = f
1809 .raw(&f.owner, &path("logo.png"), &queries)
1810 .await
1811 .expect("should read")
1812 .expect("found");
1813
1814 match raw {
1815 RawFile::Ready { content, .. } => assert_eq!(content, bytes),
1816 other => panic!("expected the bytes, got {other:?}"),
1817 }
1818 }
1819
1820 #[tokio::test]
1821 async fn a_file_too_large_to_hold_in_memory_is_refused_by_size() {
1822 let f = fixture(Visibility::Public).await;
1823 let size = MAX_RAW_BYTES as usize + 1;
1824 let queries = InMemoryGitQuery::new().with_blob("main", "huge.bin", vec![0u8; size]);
1825
1826 let raw = f
1827 .raw(&f.owner, &path("huge.bin"), &queries)
1828 .await
1829 .expect("should read")
1830 .expect("found");
1831
1832 assert_eq!(raw, RawFile::TooLarge { size: size as u64 });
1833 }
1834
1835 #[tokio::test]
1836 async fn a_file_larger_than_a_page_will_render_is_still_served_raw() {
1837 // The raw cap is deliberately far above `MAX_BLOB_BYTES`: nobody is reading
1838 // these bytes in a browser, so the reason for the page's limit does not apply.
1839 let f = fixture(Visibility::Public).await;
1840 let size = MAX_BLOB_BYTES as usize + 1;
1841 let queries = InMemoryGitQuery::new().with_blob("main", "big.txt", vec![b'x'; size]);
1842
1843 let raw = f
1844 .raw(&f.owner, &path("big.txt"), &queries)
1845 .await
1846 .expect("should read")
1847 .expect("found");
1848
1849 match raw {
1850 RawFile::Ready { content, .. } => assert_eq!(content.len(), size),
1851 other => panic!("expected the bytes, got {other:?}"),
1852 }
1853 }
1854
1855 #[tokio::test]
1856 async fn a_directory_has_no_raw_bytes() {
1857 // The fake answers `read_blob` only for blobs, exactly as git does — a tree is
1858 // not a file, and there is nothing to serve.
1859 let f = fixture(Visibility::Public).await;
1860 let queries = InMemoryGitQuery::new()
1861 .with_tree("main", "src", Vec::new())
1862 .with_blob("main", "src/main.rs", b"fn main() {}\n");
1863
1864 assert!(
1865 f.raw(&f.owner, &path("src"), &queries)
1866 .await
1867 .expect("should read")
1868 .is_none()
1869 );
1870 }
1871
1872 #[tokio::test]
1873 async fn a_path_that_is_not_there_is_not_found() {
1874 let f = fixture(Visibility::Public).await;
1875 let queries = InMemoryGitQuery::new();
1876
1877 assert!(
1878 f.raw(&f.owner, &path("nope.txt"), &queries)
1879 .await
1880 .expect("should read")
1881 .is_none()
1882 );
1883 }
1884
1885 #[tokio::test]
1886 async fn an_empty_repository_serves_nothing_raw() {
1887 let f = fixture(Visibility::Public).await;
1888
1889 assert!(
1890 f.raw(&f.owner, &path("README.md"), &InMemoryGitQuery::empty())
1891 .await
1892 .expect("should read")
1893 .is_none()
1894 );
1895 }
1896
1897 #[tokio::test]
1898 async fn a_private_repositorys_files_are_invisible_to_a_stranger() {
1899 // The point of the endpoint's authorization: a raw URL is not a way around the
1900 // page's answer.
1901 let f = fixture(Visibility::Private).await;
1902 let queries = InMemoryGitQuery::new().with_blob("main", "secret.txt", b"shh\n");
1903
1904 assert!(
1905 f.raw(&f.stranger, &path("secret.txt"), &queries)
1906 .await
1907 .expect("should read")
1908 .is_none()
1909 );
1910 assert!(
1911 f.raw(&f.owner, &path("secret.txt"), &queries)
1912 .await
1913 .expect("should read")
1914 .is_some()
1915 );
1916 }
1917}