steid

@jamesgill /

Rust29.7 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::access::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 access::{Stores, visible_repo},
17 error::Result,
18 paging::{Paged, clamp, offset, page_count},
19 port::{Blob, GitQuery},
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::access::visible_repo) gives.
145pub async fn browse_repo(
146 handle: &OrgName,
147 name: &RepoName,
148 rev: Option<&RefName>,
149 path: &RepoPath,
150 actor: &Actor,
151 stores: &Stores<'_, impl OrgRepository, impl MembershipRepository, impl RepoRepository>,
152 queries: &impl GitQuery,
153) -> Result<Option<Browsed>> {
154 if visible_repo(actor, handle, name, stores).await?.is_none() {
155 return Ok(None);
156 }
157
158 let Some(rev) = resolve_revision(handle, name, rev, queries).await? else {
159 return Ok(Some(Browsed::Empty));
160 };
161
162 // A directory first, because that is the common case and the cheaper question.
163 if let Some(mut entries) = queries.list_tree(handle, name, &rev, path).await? {
164 entries.sort_by_key(crate::domain::TreeEntry::ordering_key);
165
166 // One `git` process for the whole listing, and only for a listing: a blob path
167 // never gets here. It cannot run beside the tree read — it needs the names the
168 // tree read produces — so this is the one place a browse costs two round trips
169 // in sequence.
170 let names: Vec<String> = entries.iter().map(|entry| entry.name.clone()).collect();
171 let history = queries
172 .last_commits(handle, name, &rev, path, &names)
173 .await?;
174
175 let details = entry_details(handle, name, &rev, path, &entries, queries).await?;
176
177 return Ok(Some(Browsed::Directory {
178 rev,
179 path: path.clone(),
180 entries,
181 history,
182 details,
183 }));
184 }
185
186 let Some(blob) = queries
187 .read_blob(handle, name, &rev, path, MAX_BLOB_BYTES)
188 .await?
189 else {
190 return Ok(None);
191 };
192
193 Ok(Some(Browsed::File {
194 rev,
195 path: path.clone(),
196 file: view_of(blob),
197 }))
198}
199
200/// The submodule and symlink facts a listing needs, and nothing when it needs none.
201///
202/// **Costs nothing for an ordinary directory.** A listing with no submodule never opens
203/// `.gitmodules`, and one with no symlink never asks what a link points at — and
204/// neither read is a `git` process, since both go to the kept-alive `cat-file`.
205async fn entry_details(
206 handle: &OrgName,
207 name: &RepoName,
208 rev: &RefName,
209 path: &RepoPath,
210 entries: &[crate::domain::TreeEntry],
211 queries: &impl GitQuery,
212) -> Result<HashMap<String, EntryDetail>> {
213 use crate::domain::EntryKind;
214
215 let mut details: HashMap<String, EntryDetail> = HashMap::new();
216
217 if entries
218 .iter()
219 .any(|entry| entry.kind == EntryKind::Submodule)
220 {
221 // `.gitmodules` lives at the root of the revision, whatever directory is being
222 // listed, and is read once for the whole listing.
223 let modules = RepoPath::from_trusted(".gitmodules");
224 let text = queries
225 .read_blob(handle, name, rev, &modules, MAX_GITMODULES_BYTES)
226 .await?
227 .and_then(|blob| blob.content)
228 .and_then(|bytes| String::from_utf8(bytes).ok())
229 .unwrap_or_default();
230
231 let urls = parse_gitmodules(&text);
232
233 for entry in entries
234 .iter()
235 .filter(|entry| entry.kind == EntryKind::Submodule)
236 {
237 // Keyed by the submodule's path from the repository root, which is what
238 // `.gitmodules` records — the entry's own name is only its last component.
239 let full = path.join(&entry.name);
240
241 if let Some((_, url)) = urls.iter().find(|(at, _)| at == full.as_str()) {
242 details.entry(entry.name.clone()).or_default().url = Some(url.clone());
243 }
244 }
245 }
246
247 let links: Vec<&crate::domain::TreeEntry> = entries
248 .iter()
249 .filter(|entry| entry.kind == EntryKind::Symlink)
250 .collect();
251
252 if !links.is_empty() && links.len() <= MAX_SYMLINK_TARGETS {
253 let ids: Vec<ObjectId> = links.iter().map(|entry| entry.id.clone()).collect();
254 let targets = queries.symlink_targets(handle, name, &ids).await?;
255
256 for entry in links {
257 let Some(target) = targets.get(&entry.id) else {
258 continue;
259 };
260
261 let detail = details.entry(entry.name.clone()).or_default();
262
263 // A link resolves against the directory it is *in*, which is where the
264 // relative path in its own bytes is written from.
265 detail.resolved = resolve_relative(path, target);
266 detail.target = Some(target.clone());
267 }
268 }
269
270 Ok(details)
271}
272
273/// The `path = …` and `url = …` of every submodule in a `.gitmodules`, paired.
274///
275/// A deliberately small reading of git's config format rather than a parser for it:
276/// section headers and `key = value` lines, `#` and `;` comments, and nothing else. A
277/// value it cannot make sense of is skipped, because the consequence of misreading one
278/// is a link to somewhere a reader did not ask to go.
279///
280/// **Only `https://` URLs come back.** An `ssh://`, a `git@host:owner/repo` and a
281/// relative `../sibling` are all legitimate in the file and none of them is something a
282/// browser can open.
283pub fn parse_gitmodules(text: &str) -> Vec<(String, String)> {
284 let mut found: Vec<(String, String)> = Vec::new();
285 let mut path: Option<String> = None;
286 let mut url: Option<String> = None;
287
288 // A section ends the one before it, so what was collected is banked here as well as
289 // at the end of the file.
290 fn bank(
291 found: &mut Vec<(String, String)>,
292 path: &mut Option<String>,
293 url: &mut Option<String>,
294 ) {
295 if let (Some(path), Some(url)) = (path.take(), url.take())
296 && url.starts_with("https://")
297 && !path.is_empty()
298 {
299 found.push((path, url));
300 }
301 }
302
303 for line in text.lines() {
304 let line = line.trim();
305
306 if line.is_empty() || line.starts_with('#') || line.starts_with(';') {
307 continue;
308 }
309
310 if line.starts_with('[') {
311 bank(&mut found, &mut path, &mut url);
312 continue;
313 }
314
315 let Some((key, value)) = line.split_once('=') else {
316 continue;
317 };
318
319 // Trailing comments are not stripped: git does not treat `#` inside a value as
320 // one, and a URL may legitimately end in a fragment.
321 let value = value.trim().trim_matches('"').to_owned();
322
323 match key.trim().to_ascii_lowercase().as_str() {
324 "path" => path = Some(value.trim_matches('/').to_owned()),
325 "url" => url = Some(value),
326 _ => {}
327 }
328 }
329
330 bank(&mut found, &mut path, &mut url);
331
332 found
333}
334
335/// Where a relative reference written inside `dir` points, if it points inside the
336/// repository at all.
337///
338/// Shared by symlinks and by the links in a rendered markdown file, because they are
339/// the same question asked twice: a path written relative to the file it appears in.
340///
341/// `None` for an absolute path, for one that walks out through `..`, and for one that
342/// resolves to the root itself — none of which is a file this repository can show.
343/// `RepoPath` refuses `.` and `..` outright, which is why they are resolved here rather
344/// than handed to it.
345pub fn resolve_relative(dir: &RepoPath, target: &str) -> Option<RepoPath> {
346 let target = target.trim();
347
348 if target.is_empty() || target.starts_with('/') {
349 return None;
350 }
351
352 let mut parts: Vec<&str> = dir.components().collect();
353
354 for component in target.split('/') {
355 match component {
356 "" | "." => {}
357 ".." => {
358 // Nothing left to walk out of is a link that leaves the repository.
359 parts.pop()?;
360 }
361 name => parts.push(name),
362 }
363 }
364
365 if parts.is_empty() {
366 return None;
367 }
368
369 RepoPath::new(parts.join("/")).ok()
370}
371
372/// One page of the commit log for a revision, newest first.
373///
374/// `Ok(None)` on the same terms as [`browse_repo`]. An empty repository logs nothing
375/// rather than failing, and so does a page number past the end — which clamps to the
376/// last page there is, so a link into a branch that has since been rewritten shows
377/// history rather than a 500.
378///
379/// **Two `git` processes** rather than one: the count is what tells the page how many
380/// pages there are, and it is the same `rev-list --count` the repository page already
381/// spends on itself. Asking the log for one row past the limit would say only whether
382/// there is *a* next page, which is not enough to render "3 of 7".
383pub async fn repo_log(
384 handle: &OrgName,
385 name: &RepoName,
386 rev: Option<&RefName>,
387 page: usize,
388 actor: &Actor,
389 stores: &Stores<'_, impl OrgRepository, impl MembershipRepository, impl RepoRepository>,
390 queries: &impl GitQuery,
391) -> Result<Option<Paged<CommitSummary>>> {
392 if visible_repo(actor, handle, name, stores).await?.is_none() {
393 return Ok(None);
394 }
395
396 let Some(rev) = resolve_revision(handle, name, rev, queries).await? else {
397 return Ok(Some(Paged::of(Vec::new(), 0, 1, LOG_LIMIT)));
398 };
399
400 let total = queries.count_commits(handle, name, &rev).await? as usize;
401 // Clamped before the query, so a page past the end costs the same one `git log` as
402 // any other page instead of fetching an empty window and rendering nothing.
403 let page = clamp(page, page_count(total, LOG_LIMIT));
404
405 let commits = queries
406 .log(handle, name, &rev, offset(page, LOG_LIMIT), LOG_LIMIT)
407 .await?;
408
409 Ok(Some(Paged::of(commits, total, page, LOG_LIMIT)))
410}
411
412/// One path's own history, and what the path turned out to be.
413#[derive(Debug, Clone, PartialEq, Eq)]
414pub struct PathLog {
415 pub rev: RefName,
416 pub path: RepoPath,
417 /// Whether the path is a file at this revision.
418 ///
419 /// Carried rather than recomputed by the page, because it is what decided
420 /// `--follow`: a file's history is followed through the rename that gave it its
421 /// name, and git refuses `--follow` for a directory. The page also reads it to
422 /// label what it is showing the history *of*.
423 pub is_file: bool,
424 pub commits: Paged<CommitSummary>,
425 /// Whether the count stopped at the cap, so the page says `500+` rather than
426 /// claiming a number it did not finish counting. Only a followed walk — a file's —
427 /// can be capped; a directory's count is `rev-list --count` and is exact.
428 pub capped: bool,
429}
430
431/// One page of the commits that touched a path, newest first.
432///
433/// `Ok(None)` on [`browse_repo`]'s terms, plus one of its own: a path that is not
434/// there at this revision. A history page for a path with no present is a 404 rather
435/// than an empty list — the empty list is what a path that exists and has no commits
436/// would say, and the two are worth telling apart. It also means the same URL a tree
437/// or a blob 404s at, this one 404s at too.
438///
439/// **Three `git` processes at most, and usually two**: what is at the path is asked of
440/// the kept-alive `cat-file` and costs no process at all, then the count and the page
441/// are one walk each. See [`count_commits_at_path`](super::port::GitQuery::count_commits_at_path)
442/// for why the count cannot be folded into the listing.
443#[allow(clippy::too_many_arguments)]
444pub async fn repo_path_log(
445 handle: &OrgName,
446 name: &RepoName,
447 rev: Option<&RefName>,
448 path: &RepoPath,
449 page: usize,
450 actor: &Actor,
451 stores: &Stores<'_, impl OrgRepository, impl MembershipRepository, impl RepoRepository>,
452 queries: &impl GitQuery,
453) -> Result<Option<PathLog>> {
454 if visible_repo(actor, handle, name, stores).await?.is_none() {
455 return Ok(None);
456 }
457
458 // A repository with no commits has no path to have a history, so it is the same
459 // 404 as a path that is not there rather than an empty page.
460 let Some(rev) = resolve_revision(handle, name, rev, queries).await? else {
461 return Ok(None);
462 };
463
464 // A directory first, because that is the cheaper question and the one that settles
465 // `--follow` — exactly the order [`browse_repo`] asks in.
466 let is_file = if queries.list_tree(handle, name, &rev, path).await?.is_some() {
467 false
468 } else {
469 // Nothing is read: a cap of zero bytes still resolves the object and reports
470 // its size, which is all this needs to know it is a file.
471 let Some(_) = queries.read_blob(handle, name, &rev, path, 0).await? else {
472 return Ok(None);
473 };
474
475 true
476 };
477
478 let counted = queries
479 .count_commits_at_path(handle, name, &rev, path, is_file)
480 .await?;
481 let total = counted.total as usize;
482 // Clamped before the query for [`repo_log`]'s reason: a page past the end costs
483 // the same one walk as any other page. A capped total pages to the cap and no
484 // further, which is the whole of what was counted — so the control stays correct
485 // rather than offering a page nothing was counted for.
486 let page = clamp(page, page_count(total, LOG_LIMIT));
487
488 let commits = queries
489 .log_at_path(
490 handle,
491 name,
492 &rev,
493 path,
494 is_file,
495 offset(page, LOG_LIMIT),
496 LOG_LIMIT,
497 )
498 .await?;
499
500 Ok(Some(PathLog {
501 rev,
502 path: path.clone(),
503 is_file,
504 commits: Paged::of(commits, total, page, LOG_LIMIT),
505 capped: counted.capped,
506 }))
507}
508
509/// The branches and tags a repository has, ready for a switcher.
510///
511/// Two lists rather than one tagged list, because that is how they are shown: a
512/// visitor picking a revision is picking from branches *or* from tags, and the same
513/// name can legitimately appear in both.
514#[derive(Debug, Clone, Default, PartialEq, Eq)]
515pub struct RefList {
516 pub branches: Vec<RefName>,
517 pub tags: Vec<RefName>,
518}
519
520impl RefList {
521 pub fn is_empty(&self) -> bool {
522 self.branches.is_empty() && self.tags.is_empty()
523 }
524
525 /// Whether a revision names one of these refs.
526 ///
527 /// What a switcher uses to decide whether the current revision is a ref it can
528 /// highlight or an object id it has to show as itself.
529 pub fn contains(&self, rev: &RefName) -> bool {
530 self.branches
531 .iter()
532 .chain(&self.tags)
533 .any(|name| name == rev)
534 }
535}
536
537/// Every branch and tag, for the revision switcher.
538///
539/// `Ok(None)` on the same terms as [`browse_repo`]: invisible and absent are one answer.
540///
541/// **This costs one extra `git` process (~14ms) on top of whatever the page already
542/// spends**, so it is called by the pages that show a switcher and by nothing else. See
543/// the port's note on [`list_refs`](super::port::GitQuery::list_refs).
544///
545/// Ordering is decided here rather than in an adapter: branches then tags, each
546/// case-insensitively by name, with ties broken by the name itself so the order is
547/// total. The default branch is not floated to the top — it is usually first
548/// alphabetically anyway, and a list that reorders itself is harder to scan than one
549/// that does not.
550pub async fn list_refs(
551 handle: &OrgName,
552 name: &RepoName,
553 actor: &Actor,
554 stores: &Stores<'_, impl OrgRepository, impl MembershipRepository, impl RepoRepository>,
555 queries: &impl GitQuery,
556) -> Result<Option<RefList>> {
557 if visible_repo(actor, handle, name, stores).await?.is_none() {
558 return Ok(None);
559 }
560
561 Ok(Some(organise_refs(queries.list_refs(handle, name).await?)))
562}
563
564/// Splits a raw ref list into branches and tags, each in the order a switcher shows.
565///
566/// Separate from [`list_refs`] because [`repo_summary`](super::summary::repo_summary)
567/// asks the port itself — it wants the counts *and* the switcher's list from one `git`
568/// process — and two places deciding the order is two places to change it.
569pub fn organise_refs(refs: Vec<crate::domain::GitRef>) -> RefList {
570 let mut list = RefList::default();
571
572 for git_ref in refs {
573 match git_ref.kind {
574 RefKind::Branch => list.branches.push(git_ref.name),
575 RefKind::Tag => list.tags.push(git_ref.name),
576 }
577 }
578
579 for names in [&mut list.branches, &mut list.tags] {
580 names.sort_by(|left, right| {
581 left.as_str()
582 .to_lowercase()
583 .cmp(&right.as_str().to_lowercase())
584 .then_with(|| left.as_str().cmp(right.as_str()))
585 });
586 }
587
588 list
589}
590
591/// A page of refs, and whether the repository has any history at all.
592///
593/// The second field is the distinction the branches and tags pages need but a list
594/// alone cannot make: "no tags yet" and "nothing pushed yet" are different sentences,
595/// and only the second one wants the push snippet beneath it.
596///
597/// It costs **one extra `git` process**, and only when the list came back empty — which
598/// is exactly when the page has nothing else to spend.
599#[derive(Debug, Clone, PartialEq, Eq)]
600pub struct RefPage<Row> {
601 /// One page of rows, [`REF_LIMIT`] to a page.
602 ///
603 /// Sliced here rather than in the port: `for-each-ref` hands back every ref in one
604 /// process whatever the page asks for, so a `limit` on the port would buy nothing
605 /// and cost a second call for the count. See [ui.md](../../plans/ui.md#paging).
606 pub rows: Paged<Row>,
607 /// No commits have been pushed: `HEAD` names a branch that does not exist.
608 pub repo_is_empty: bool,
609}
610
611/// Cuts the page a caller asked for, or hands the whole list back as one page.
612///
613/// `None` is not a page number nobody asked for — it is the settings form's `<select>`
614/// of default branches, which is not a list a person pages through and would silently
615/// lose its 101st option to a page size. A reader gets a page; a form gets all of them.
616fn one_page<Row>(rows: Vec<Row>, page: Option<usize>) -> Paged<Row> {
617 match page {
618 Some(page) => Paged::slice(rows, page, REF_LIMIT),
619 None => {
620 let size = rows.len().max(1);
621 Paged::slice(rows, 1, size)
622 }
623 }
624}
625
626/// Every branch, in the order the branches page shows them.
627///
628/// `Ok(None)` on the same terms as [`browse_repo`]: invisible and absent are one answer.
629///
630/// **One `git` process** — see [`branches`](super::port::GitQuery::branches) — plus one
631/// more only when there are no branches, to tell an empty repository from a repository
632/// whose refs are all tags.
633///
634/// Deliberately **no ahead/behind counts**: a count against the default branch is a
635/// `rev-list` per branch, so a repository with twenty branches would fork twenty extra
636/// processes to decorate one page. That is exactly the cost
637/// [0006](../../plans/decisions/0006-git-binary-behind-narrow-ports.md) bounds, and it
638/// stays out until something keeps git alive between questions.
639pub async fn list_branches(
640 handle: &OrgName,
641 name: &RepoName,
642 page: Option<usize>,
643 actor: &Actor,
644 stores: &Stores<'_, impl OrgRepository, impl MembershipRepository, impl RepoRepository>,
645 queries: &impl GitQuery,
646) -> Result<Option<RefPage<BranchRow>>> {
647 if visible_repo(actor, handle, name, stores).await?.is_none() {
648 return Ok(None);
649 }
650
651 let rows = pin_default(queries.branches(handle, name).await?);
652 let empty = rows.is_empty() && !has_commits(handle, name, queries).await?;
653
654 Ok(Some(RefPage {
655 rows: one_page(rows, page),
656 repo_is_empty: empty,
657 }))
658}
659
660/// Every tag, newest first. Authorized and costed exactly as [`list_branches`] is.
661pub async fn list_tags(
662 handle: &OrgName,
663 name: &RepoName,
664 page: Option<usize>,
665 actor: &Actor,
666 stores: &Stores<'_, impl OrgRepository, impl MembershipRepository, impl RepoRepository>,
667 queries: &impl GitQuery,
668) -> Result<Option<RefPage<TagRow>>> {
669 if visible_repo(actor, handle, name, stores).await?.is_none() {
670 return Ok(None);
671 }
672
673 let rows = queries.tags(handle, name).await?;
674 let empty = rows.is_empty() && !has_commits(handle, name, queries).await?;
675
676 Ok(Some(RefPage {
677 rows: one_page(rows, page),
678 repo_is_empty: empty,
679 }))
680}
681
682/// Whether anything has been pushed. One `git` process, asked only on an empty page.
683async fn has_commits(handle: &OrgName, name: &RepoName, queries: &impl GitQuery) -> Result<bool> {
684 Ok(queries.default_branch(handle, name).await?.is_some())
685}
686
687/// Moves the default branch to the front, leaving everything else in git's date order.
688///
689/// A display decision rather than the adapter's: the default branch is the one a
690/// visitor came for, and it is not reliably the most recently pushed — a repository
691/// whose work happens on feature branches would bury `main` halfway down a page
692/// otherwise. Everything below it stays newest-first, which is the ordering that
693/// answers "what is being worked on".
694///
695/// A stable partition rather than a sort, so the date order it was given survives.
696fn pin_default(rows: Vec<BranchRow>) -> Vec<BranchRow> {
697 let (default, rest): (Vec<_>, Vec<_>) = rows.into_iter().partition(|row| row.is_default);
698
699 default.into_iter().chain(rest).collect()
700}
701
702/// A file as it is served rather than rendered.
703#[derive(Debug, Clone, PartialEq, Eq)]
704pub enum RawFile {
705 Ready {
706 /// The file's own name, for the download it becomes.
707 name: String,
708 content: Vec<u8>,
709 },
710 /// Bigger than [`MAX_RAW_BYTES`]. Reported rather than served, because the port
711 /// reads bytes into memory; the size is carried so the refusal can say why.
712 TooLarge { size: u64 },
713}
714
715/// Reads a file for serving verbatim.
716///
717/// Authorized exactly as [`browse_repo`] is, through [`view_repo`], so a repository
718/// invisible on its page is invisible here too — a raw URL is not a side door.
719///
720/// `Ok(None)` for a repository that is invisible or absent, a revision that is not
721/// there, a path that is not there, and a path that is a directory. All of them are one
722/// answer for the reason [`view_repo`] gives, and a directory is included because there
723/// is no such thing as raw bytes for one.
724pub async fn read_raw_file(
725 handle: &OrgName,
726 name: &RepoName,
727 rev: Option<&RefName>,
728 path: &RepoPath,
729 actor: &Actor,
730 stores: &Stores<'_, impl OrgRepository, impl MembershipRepository, impl RepoRepository>,
731 queries: &impl GitQuery,
732) -> Result<Option<RawFile>> {
733 if visible_repo(actor, handle, name, stores).await?.is_none() {
734 return Ok(None);
735 }
736
737 let Some(rev) = resolve_revision(handle, name, rev, queries).await? else {
738 return Ok(None);
739 };
740
741 // Straight to the blob: unlike a browse, there is no directory case to serve, so
742 // asking `list_tree` first would spend a whole process learning that a path is not
743 // something this endpoint can answer for. `read_blob` already says `None` for a
744 // tree.
745 let Some(blob) = queries
746 .read_blob(handle, name, &rev, path, MAX_RAW_BYTES)
747 .await?
748 else {
749 return Ok(None);
750 };
751
752 let Some(content) = blob.content else {
753 return Ok(Some(RawFile::TooLarge { size: blob.size }));
754 };
755
756 Ok(Some(RawFile::Ready {
757 // A path that resolved to a blob has a last component by construction: the root
758 // is a tree, and `read_blob` refuses it.
759 name: path.file_name().unwrap_or_default().to_owned(),
760 content,
761 }))
762}
763
764/// Settles which revision is being asked about.
765///
766/// `None` out means the repository has no commits at all — not that the revision was
767/// wrong, which surfaces later as nothing being found at the path.
768pub(crate) async fn resolve_revision(
769 handle: &OrgName,
770 name: &RepoName,
771 rev: Option<&RefName>,
772 queries: &impl GitQuery,
773) -> Result<Option<RefName>> {
774 match rev {
775 Some(rev) => Ok(Some(rev.clone())),
776 None => Ok(queries.default_branch(handle, name).await?),
777 }
778}
779
780/// Decides what can be done with a blob's bytes.
781///
782/// The port carries bytes and a size; turning those into "text", "binary" or "too big"
783/// is a display decision, so it happens here rather than in the adapter.
784fn view_of(blob: Blob) -> FileView {
785 let too_large = blob.content.is_none();
786 let text = blob.content.and_then(|bytes| String::from_utf8(bytes).ok());
787
788 FileView {
789 id: blob.id,
790 size: blob.size,
791 text,
792 too_large,
793 }
794}
795
796#[cfg(test)]
797#[path = "browse_tests.rs"]
798mod tests;