steid

@jamesgill /

1//! Repository pages — `/{handle}/repos/new` and `/{handle}/repos/{name}`.
2//!
3//! `new` is a static segment and `{name}` a parameterised one, so the router prefers
4//! `new`. [`RepoName`] reserves it as well, so the two agree rather than relying on
5//! routing order alone.
6
7use std::time::SystemTime;
8
9use serde::Deserialize;
10use topcoat::{
11 Result,
12 context::Cx,
13 icon::{icon, iconify::iconify_icon},
14 router::{
15 StatusCode,
16 content::Form,
17 error::{RouterErrorExt, not_found},
18 page, path_param,
19 },
20 view::{View, attributes, component, view},
21};
22
23use crate::{
24 application::{
25 Browsed, Error, FileView, NewRepo, RepoFacts, RepoView, Stores, create_repo,
26 port::ArchiveFormat, repo_summary, view_repo,
27 },
28 components::{
29 badge::{BadgeVariant, badge},
30 button::{ButtonSize, ButtonVariant, button, button_variants},
31 flash::{FlashKind, flash},
32 input::input,
33 label::label,
34 select::select,
35 textarea::textarea,
36 },
37 domain::{
38 CommitSummary, DomainError, EntryKind, RefName, RepoName, RepoPath, Repository, TreeEntry,
39 Visibility,
40 },
41};
42
43use super::{
44 archive::archive_url,
45 browse::{Listing, blob, browsed_at, browsed_rev, directory, empty_repo, repo_toolbar},
46 commit::commit_url,
47 context::{
48 current_actor, issues, location, memberships, orgs, owned_profile, public_origin, pulls,
49 queries, repos, server_error, storage,
50 },
51 csrf::{csrf_field, csrf_verified},
52 format::{ago, optional},
53 import::{ImportBlock, import_block, importing_page},
54 layout::{narrow, wide},
55 markdown,
56 profile::profile_for,
57 pulls::pulls_url,
58 refs::{branches_url, tags_url},
59 urls::{log_url, tree_url},
60};
61
62/// `{name}` from the path, raw — validation is [`RepoName`]'s job.
63#[path_param]
64struct Name(str);
65
66#[derive(Debug, Deserialize)]
67struct CreateForm {
68 /// The hidden field every form carries; see [`csrf`](super::csrf).
69 ///
70 /// `default` so that a submission with no token at all is refused by
71 /// `csrf_verified` — a 403 saying what happened — rather than failing
72 /// deserialization into a bare 400 that says nothing.
73 #[serde(default)]
74 csrf_token: String,
75 name: String,
76 description: String,
77 visibility: String,
78}
79
80/// Resolves `{handle}/repos/{name}` into a repository the viewer may see, or 404.
81///
82/// A repository the viewer may not see and one that does not exist are the same
83/// answer here, deliberately — see [`view_repo`].
84pub(super) async fn repo_for(cx: &Cx) -> Result<RepoView> {
85 let profile = profile_for(cx).await?;
86 let name = RepoName::new(path_param::<Name>(cx)).map_err(|_| not_found())?;
87 let actor = current_actor(cx).await?;
88
89 Ok(view_repo(
90 &profile.handle,
91 &name,
92 &actor,
93 &Stores::new(&orgs(cx), &memberships(cx), &repos(cx)),
94 &issues(cx),
95 &pulls(cx),
96 )
97 .await
98 .map_err(server_error)?
99 .ok_or_not_found()?)
100}
101
102#[page("/{handle}/repos/new")]
103async fn new_repo_page(cx: &Cx) -> Result {
104 // The use case decides this too; checking here as well keeps the form from
105 // rendering for someone whose submission would only be rejected.
106 let profile = owned_profile(cx).await?;
107
108 let import = ImportBlock::default();
109
110 view! {
111 new_repo_form(
112 handle: profile.handle.as_str(),
113 name: "",
114 description: "",
115 visibility: Visibility::default(),
116 error: "",
117 import: &import,
118 )
119 }
120}
121
122/// Creates the repository.
123///
124/// Success redirects to the new repository, using the **normalised** name from the
125/// created record — someone who typed `MyRepo` belongs at `/{handle}/repos/myrepo`.
126/// Failure re-renders with the reason and what was typed.
127///
128/// The success reply is a 303 — see [`location`] for why it is spelled this way and
129/// not with `redirect()`.
130#[page(POST "/{handle}/repos/new")]
131async fn create(cx: &Cx, Form(submitted): Form<CreateForm>) -> Result {
132 csrf_verified(cx, &submitted.csrf_token).await?;
133
134 let profile = profile_for(cx).await?;
135
136 // An unparseable value is a tampered form, not something to default: defaulting
137 // here could publish a repository the owner asked to keep private.
138 let visibility = submitted
139 .visibility
140 .parse::<Visibility>()
141 .map_err(|_| topcoat::router::error::bad_request("unknown visibility"))?;
142
143 let outcome = create_repo(
144 &current_actor(cx).await?,
145 &profile.handle,
146 &NewRepo {
147 name: submitted.name.clone(),
148 description: optional(&submitted.description),
149 visibility,
150 },
151 SystemTime::now(),
152 &Stores::new(&orgs(cx), &memberships(cx), &repos(cx)),
153 &storage(cx),
154 )
155 .await;
156
157 let message = match outcome {
158 Ok(repo) => {
159 return view! {
160 (StatusCode::SEE_OTHER)
161 (location(&format!("/{}/repos/{}", profile.handle, repo.name))?)
162 };
163 }
164 Err(Error::Domain(DomainError::Validation { field, reason })) => {
165 format!("That {field} is no good: {reason}.")
166 }
167 Err(Error::Domain(DomainError::AlreadyExists { .. })) => {
168 format!(
169 "You already have a repository called {}.",
170 submitted.name.trim()
171 )
172 }
173 Err(Error::Domain(DomainError::Forbidden)) => return Err(not_found().into()),
174 Err(other) => return Err(server_error(std::io::Error::other(other.to_string()))),
175 };
176
177 let import = ImportBlock::default();
178
179 view! {
180 new_repo_form(
181 handle: profile.handle.as_str(),
182 name: submitted.name.as_str(),
183 description: submitted.description.as_str(),
184 visibility: visibility,
185 error: message.as_str(),
186 import: &import,
187 )
188 }
189}
190
191/// The repository's own page: its default branch, at the root, beside what the
192/// repository is.
193///
194/// The only two-column page in a repository. Code on the left because the reason to
195/// open a repository is to see what is in it; the About sidebar on the right because
196/// this is the page a visitor arrives at from a profile, and "what is this and may I
197/// use it" is the question they came with. Every page below this one — a tree subpath,
198/// a file, the log — stays a single wide column, the same way GitHub narrows once you
199/// are inside the tree.
200#[page("/{handle}/repos/{name}")]
201async fn repo_page(cx: &Cx) -> Result {
202 let repo = repo_for(cx).await?;
203
204 // Before anything is asked of git. A repository being imported has a directory that
205 // is half-written or not there at all, and the five processes `facts_of` costs would
206 // all be spent learning that. See [`web::import`](super::import).
207 if let Some(status) = repo.import.clone() {
208 return view! { wide(importing_page(repo: &repo, status: &status)) };
209 }
210
211 let clone = clone_url_for(cx, &repo);
212 let browsed = browsed_at(cx, &repo, None, &RepoPath::root()).await?;
213
214 // Only a browsed root has a revision and a listing to summarise. An empty
215 // repository has neither, so it is not asked — five more `git` processes to learn
216 // that nothing is there is exactly the cost 0006 warns about.
217 let facts = match &browsed {
218 Browsed::Directory { rev, entries, .. } => Some(facts_of(cx, &repo, rev, entries).await?),
219 _ => None,
220 };
221
222 let at = browsed_rev(&browsed);
223 let refs = facts
224 .as_ref()
225 .map(|facts| facts.refs.clone())
226 .unwrap_or_default();
227
228 view! {
229 wide(
230 repo_header(repo: &repo, rev: at, active: Tab::Code)
231
232 <div class="flex flex-col lg:flex-row lg:items-start lg:gap-6">
233 <div class="min-w-0 lg:flex-1">
234 // One muted line above the code, on the landing page only: the
235 // badge in the header says the state, and this says what it means
236 // for the person about to `git push`.
237 if repo.archived {
238 <p class="mb-3 flex items-center gap-2 text-xs text-muted-foreground">
239 icon(data: iconify_icon!("feather:archive"), attrs: attributes! {
240 class="size-3.5 shrink-0"
241 })
242 "This repository is archived. It can still be read and cloned, "
243 "but it no longer accepts pushes."
244 </p>
245 }
246
247 match &browsed {
248 Browsed::Empty => empty_repo(url: clone.as_str()),
249 Browsed::Directory { rev, path, entries, history: last_commits, details } => {
250 repo_toolbar(
251 handle: repo.handle.as_str(),
252 name: repo.name.as_str(),
253 rev: rev.as_str(),
254 path: path,
255 refs: &refs,
256 )
257 match facts.as_ref().and_then(|facts| facts.latest_commit.as_ref()) {
258 Some(commit) => latest_commit(
259 handle: repo.handle.as_str(),
260 name: repo.name.as_str(),
261 commit: commit,
262 ),
263 None => "",
264 }
265 directory(
266 handle: repo.handle.as_str(),
267 name: repo.name.as_str(),
268 rev: rev,
269 path: path,
270 entries: entries,
271 listing: Listing::of(last_commits, details),
272 )
273
274 // No README means nothing here at all — an empty panel saying a
275 // repository has no README is worse than the silence.
276 match readme_of(entries) {
277 Some(entry) => readme_card(repo: &repo, rev: rev, entry: entry),
278 None => "",
279 }
280 },
281 // The root of a revision is always a directory, so this is unreachable in
282 // practice — rendered rather than errored so it can never be a 500.
283 Browsed::File { rev, path, file } => blob(
284 handle: repo.handle.as_str(),
285 name: repo.name.as_str(),
286 rev: rev,
287 path: path,
288 file: file,
289 show_source: false,
290 ),
291 }
292 </div>
293
294 // Below `lg` the sidebar is not a sidebar: it comes *first*, above the
295 // file list, with a rule under it. Ordering it after the code would bury
296 // "what is this and may I use it" below a long README — which is the one
297 // question the visitor arrived with, on the viewport with the least room
298 // to go looking for it. `order-first` is why the container is a flex
299 // column below `lg` rather than a plain block.
300 <aside class="order-first mb-6 w-full shrink-0 border-b border-border pb-6 lg:order-none lg:sticky lg:top-6 lg:mb-0 lg:w-72 lg:border-b-0 lg:pb-0">
301 repo_about(
302 repo: &repo,
303 rev: at,
304 facts: facts.as_ref(),
305 clone: clone.as_str(),
306 )
307 </aside>
308 </div>
309 )
310 }
311}
312
313/// The facts about a repository the viewer can already see, or 404.
314///
315/// **Five `git` processes**, run concurrently — see
316/// [`repo_summary`](crate::application::repo_summary) and this step's note in
317/// `plans/progress.md`. Only the landing page calls it.
318async fn facts_of(
319 cx: &Cx,
320 repo: &RepoView,
321 rev: &RefName,
322 entries: &[TreeEntry],
323) -> Result<RepoFacts> {
324 Ok(repo_summary(
325 &repo.handle,
326 &repo.name,
327 rev,
328 entries,
329 &current_actor(cx).await?,
330 &Stores::new(&orgs(cx), &memberships(cx), &repos(cx)),
331 &queries(cx),
332 )
333 .await
334 .map_err(server_error)?
335 .ok_or_not_found()?)
336}
337
338// --- The repository frame ---------------------------------------------------------
339
340/// Which repository page is being looked at.
341///
342/// One variant per tab, which is the point of the strip being a component: Issues and
343/// Pull requests each cost one variant and one line here.
344#[derive(Debug, Clone, Copy, PartialEq, Eq)]
345pub(super) enum Tab {
346 Code,
347 Commits,
348 Issues,
349 Pulls,
350}
351
352/// The header every repository page carries: whose it is, what it is, and what else
353/// there is.
354///
355/// Shared so a tree, a file and a log read as one place rather than as three unrelated
356/// pages. Deliberately one line of title: the description lives in the About sidebar
357/// and nowhere else, because two homes for it means the header grows on exactly the
358/// repositories that have the most to say.
359#[component]
360pub(super) async fn repo_header(
361 repo: &RepoView,
362 rev: &str,
363 active: Tab,
364 /// The revision control, on the pages that carry it here. The landing page does
365 /// not: its switcher belongs in the toolbar above the file list.
366 #[default]
367 child: View,
368) -> Result {
369 let handle = repo.handle.as_str();
370 let name = repo.name.as_str();
371
372 // The primary colour marks the tab you are on. Nothing else on the strip is
373 // coloured, so it reads as position rather than as decoration.
374 let tab = |current| {
375 if current {
376 "border-primary text-foreground"
377 } else {
378 "border-transparent text-muted-foreground hover:text-foreground"
379 }
380 };
381
382 view! {
383 <header class="mb-4">
384 <p class="font-mono text-xs text-muted-foreground">
385 <a href=(format!("/{handle}")) class="hover:text-foreground">"@" (handle)</a>
386 " /"
387 </p>
388
389 <div class="mt-0.5 flex items-center gap-2.5">
390 <h1 class="text-2xl font-semibold tracking-tight">
391 <a href=(format!("/{handle}/repos/{name}"))>(name)</a>
392 </h1>
393 if !repo.visibility.is_public() {
394 badge(variant: BadgeVariant::Outline, "Private")
395 }
396 // Outline, like Private: both are states of the repository rather than
397 // things to act on, and a filled badge beside the title would read as
398 // the liveliest thing on a page whose point is that it is finished.
399 if repo.archived {
400 badge(variant: BadgeVariant::Outline, "Archived")
401 }
402 // Only the owner can change a repository, so only the owner is offered
403 // the way in. The settings page enforces this again — this is the link
404 // not being a dead end, not the authorization.
405 if repo.viewer_is_owner {
406 <a
407 href=(format!("/{handle}/repos/{name}/settings"))
408 class=(format!(
409 "ml-auto {}",
410 button_variants(ButtonVariant::Outline, ButtonSize::Sm)
411 ))
412 >"Settings"</a>
413 }
414 </div>
415
416 <nav class="mt-3 flex items-center gap-5 border-b border-border text-sm">
417 <a
418 href=(format!("/{handle}/repos/{name}"))
419 class=(format!("-mb-px border-b-2 pb-2 {}", tab(active == Tab::Code)))
420 >"Code"</a>
421 <a
422 href=(log_url(handle, name, rev))
423 class=(format!("-mb-px border-b-2 pb-2 {}", tab(active == Tab::Commits)))
424 >"Commits"</a>
425 <a
426 href=(format!("/{handle}/repos/{name}/issues"))
427 class=(format!(
428 "-mb-px flex items-center gap-1.5 border-b-2 pb-2 {}",
429 tab(active == Tab::Issues)
430 ))
431 >
432 "Issues"
433 // Zero is left out rather than drawn: a repository with no issues
434 // has nothing to report, and a mono `0` beside the tab reads as a
435 // measurement somebody took.
436 if repo.open_issues > 0 {
437 <span class="font-mono text-xs text-muted-foreground">
438 (repo.open_issues)
439 </span>
440 }
441 </a>
442 // After Issues, where ui.md's entry-point table put it. The count is
443 // read the same way and left out at zero for the same reason.
444 <a
445 href=(pulls_url(handle, name))
446 class=(format!(
447 "-mb-px flex items-center gap-1.5 border-b-2 pb-2 {}",
448 tab(active == Tab::Pulls)
449 ))
450 >
451 "Pull requests"
452 if repo.open_pulls > 0 {
453 <span class="font-mono text-xs text-muted-foreground">
454 (repo.open_pulls)
455 </span>
456 }
457 </a>
458
459 <span class="ml-auto pb-2">(child)</span>
460 </nav>
461 </header>
462 }
463}
464
465/// The most recent commit, on one line above the listing.
466///
467/// This is what a per-file last-commit column would say if there were one, said once —
468/// the column itself is deferred until a kept-alive `cat-file --batch` exists, per the
469/// Milestone 5 amendment to
470/// [0006](../../../plans/decisions/0006-git-binary-behind-narrow-ports.md). The dot is
471/// the primary colour, which is the only mark on the row: a commit is the thing that
472/// changed most recently, and the eye should land on it.
473#[component]
474async fn latest_commit(handle: &str, name: &str, commit: &CommitSummary) -> Result {
475 view! {
476 <div class="mb-2 flex items-center gap-2.5 rounded-lg border border-border px-4 py-2 text-sm">
477 <span class="size-1.5 shrink-0 rounded-full bg-primary"></span>
478 <span class="truncate">(&commit.summary)</span>
479 <span class="ml-auto flex shrink-0 items-center gap-3 text-xs text-muted-foreground">
480 // Straight to the commit rather than to the log: the commit page is
481 // where what it changed lives, and the log is one click further on the
482 // Commits tab.
483 <a
484 href=(commit_url(handle, name, commit.id.as_str()))
485 class="font-mono hover:text-foreground"
486 >(commit.id.short())</a>
487 <span>(ago(commit.committed_at))</span>
488 </span>
489 </div>
490 }
491}
492
493// --- The About sidebar ------------------------------------------------------------
494
495/// What the repository is, in the column beside what is in it.
496///
497/// What the repository is for: a visitor arriving from the owner's home page reads this
498/// before they read any code. Sections are separated by hairlines rather than boxed as
499/// cards — the same rule the home page settled on, and the reason the page reads as one
500/// surface.
501#[component]
502async fn repo_about(repo: &RepoView, rev: &str, facts: Option<&RepoFacts>, clone: &str) -> Result {
503 let handle = repo.handle.as_str();
504 let name = repo.name.as_str();
505
506 view! {
507 <section class="text-sm">
508 <h2 class="text-xs font-medium uppercase tracking-wider text-muted-foreground">
509 "About"
510 </h2>
511 match &repo.description {
512 Some(description) => <p class="mt-2 leading-relaxed">(description)</p>,
513 // Shown rather than omitted, because an owner looking at their own
514 // repository should see the gap they can fill in.
515 None => <p class="mt-2 text-muted-foreground">"No description."</p>,
516 }
517 match facts.and_then(|facts| facts.licence.as_ref()) {
518 Some(licence) => <p class="mt-2">
519 <a
520 href=(tree_url(handle, name, &RefName::from_trusted(rev), &licence.path))
521 class="inline-flex items-center gap-1.5 text-xs text-muted-foreground hover:text-foreground"
522 >
523 icon(data: iconify_icon!("feather:book"), attrs: attributes! {
524 class="size-3.5"
525 })
526 // An unrecognised licence file is linked to and not named —
527 // see `Licence`. "Licence" is then the honest label.
528 (licence.name.unwrap_or("Licence"))
529 </a>
530 </p>,
531 None => "",
532 }
533 </section>
534
535 match facts {
536 Some(facts) => repo_stats(
537 handle: handle,
538 name: name,
539 facts: facts,
540 pushed: repo.updated_at,
541 ),
542 // With no commits there is nothing true to count, so the row that is still
543 // true is shown on its own.
544 None => <dl class="mt-4 space-y-1.5 border-t border-border pt-4 text-xs">
545 fact(term: "Pushed", (ago(repo.updated_at)))
546 </dl>,
547 }
548
549 clone_block(
550 handle: handle,
551 name: name,
552 rev: rev,
553 url: clone,
554 )
555 }
556}
557
558/// The numbers, as a definition list.
559///
560/// A list rather than a row of badges: every value is a different kind of thing, and
561/// the label is what makes each one readable at a glance.
562#[component]
563async fn repo_stats(handle: &str, name: &str, facts: &RepoFacts, pushed: SystemTime) -> Result {
564 view! {
565 <dl class="mt-4 space-y-1.5 border-t border-border pt-4 text-xs">
566 fact(term: "Commits", <span class="font-mono">(facts.commits.to_string())</span>)
567 // Links now that the pages exist — the sidebar is where a visitor reads
568 // how much of a repository there is, so it is also where they ask to see it.
569 fact(
570 term: "Branches",
571 <a href=(branches_url(handle, name)) class="font-mono hover:underline">
572 (facts.refs.branches.len().to_string())
573 </a>
574 )
575 fact(
576 term: "Tags",
577 <a href=(tags_url(handle, name)) class="font-mono hover:underline">
578 (facts.refs.tags.len().to_string())
579 </a>
580 )
581 match &facts.latest_tag {
582 Some(tag) => fact(
583 term: "Latest tag",
584 <span class="inline-flex items-center gap-1.5 font-mono">
585 icon(data: iconify_icon!("feather:tag"), attrs: attributes! {
586 class="size-3 text-muted-foreground"
587 })
588 (tag.name.as_str())
589 </span>
590 ),
591 // A repository with no releases says nothing rather than "none": an
592 // empty value reads as a thing that is missing.
593 None => "",
594 }
595 fact(term: "Pushed", (ago(pushed)))
596 </dl>
597 }
598}
599
600/// One label-and-value row of [`repo_stats`].
601///
602/// The parameter is `term`, not `label`: the copied-in `label` component is a unit
603/// struct in this module's scope and would shadow a binding of that name.
604#[component]
605async fn fact(term: &str, #[default] child: View) -> Result {
606 view! {
607 <div class="flex items-baseline justify-between gap-3">
608 <dt class="text-muted-foreground">(term)</dt>
609 <dd class="min-w-0 truncate">(child)</dd>
610 </div>
611 }
612}
613
614/// The clone address, ready to copy.
615///
616/// Shown for every repository a viewer can see, including an empty one — an empty
617/// repository is exactly when someone needs this, because it is what they push to.
618///
619/// The URL alone rather than `git clone <url>`: at sidebar width the command wraps or
620/// scrolls, and the address is the part being copied. It wraps rather than scrolls —
621/// a horizontally scrolled URL looks like a truncated one, and the part cut off is the
622/// repository's own name.
623///
624/// The two download links sit under it, for **the revision being viewed** rather than
625/// always the default branch: someone reading a tag wants that tag's tarball. An empty
626/// repository has no revision and gets no links — there is nothing to pack, and the
627/// clone URL above is the thing that is actually useful there.
628#[component]
629pub(super) async fn clone_block(handle: &str, name: &str, rev: &str, url: &str) -> Result {
630 view! {
631 <div class="mt-4 border-t border-border pt-4">
632 <p class="text-xs font-medium uppercase tracking-wider text-muted-foreground">
633 "Clone"
634 </p>
635 <pre class="mt-2 rounded-lg border border-border bg-surface px-3 py-2 font-mono text-xs break-all whitespace-pre-wrap">(url)</pre>
636
637 if !rev.is_empty() {
638 <p class="mt-2 flex items-center gap-2 text-xs text-muted-foreground">
639 icon(data: iconify_icon!("feather:download"), attrs: attributes! {
640 class="size-3.5"
641 })
642 "Download"
643 <a
644 href=(archive_url(handle, name, rev, ArchiveFormat::Zip))
645 class="font-mono hover:text-foreground hover:underline"
646 >"zip"</a>
647 "·"
648 <a
649 href=(archive_url(handle, name, rev, ArchiveFormat::TarGz))
650 class="font-mono hover:text-foreground hover:underline"
651 >"tar.gz"</a>
652 </p>
653 }
654 </div>
655 }
656}
657
658// --- README -----------------------------------------------------------------------
659
660/// Extensions a README may carry, in the order they are preferred.
661///
662/// Empty last: a plain `README` is a README, but a repository holding both `README.md`
663/// and `README` means the markdown one. Nothing that is not markdown is here — a
664/// `README.rst` rendered as markdown would be worse than the file listing.
665const README_EXTENSIONS: [&str; 5] = ["md", "markdown", "mdown", "mkd", ""];
666
667/// How strongly a name says "this is the README", or `None` if it does not.
668///
669/// Case-insensitive, because the file is spelled `README`, `readme` and `Readme` in the
670/// wild and all three mean the same thing.
671fn readme_rank(name: &str) -> Option<usize> {
672 let lowered = name.to_ascii_lowercase();
673 let extension = match lowered.strip_prefix("readme")? {
674 "" => "",
675 rest => rest.strip_prefix('.')?,
676 };
677
678 README_EXTENSIONS
679 .iter()
680 .position(|candidate| *candidate == extension)
681}
682
683/// The README in a listing, if there is one.
684///
685/// Chosen from the entries the page already has rather than by asking git for a file
686/// that may not exist: every `git` call is a fork of about 12ms, and a speculative one
687/// would be spent on every repository without a README. See
688/// [0006](../../../plans/decisions/0006-git-binary-behind-narrow-ports.md).
689fn readme_of(entries: &[TreeEntry]) -> Option<&TreeEntry> {
690 entries
691 .iter()
692 .filter(|entry| entry.kind == EntryKind::Blob)
693 .filter_map(|entry| Some((readme_rank(&entry.name)?, entry)))
694 .min_by_key(|(rank, _)| *rank)
695 .map(|(_, entry)| entry)
696}
697
698/// Where a relative link in a README should point.
699///
700/// A README's links are written against the repository's own files, so `./CONTRIBUTING.md`
701/// means a file in the tree and not a Steid route — left alone it would 404. Anything
702/// this cannot make sense of returns `None` and is left exactly as written, which is the
703/// same thing a plain markdown renderer would do.
704///
705/// Only links. A relative *image* is left alone deliberately: an image needs the file's
706/// bytes, and a tree URL serves a page, so rewriting one would trade a 404 for a broken
707/// image. [`markdown::render_with_links`] never offers this an image.
708fn readme_link(handle: &str, name: &str, rev: &RefName, destination: &str) -> Option<String> {
709 // A fragment names a heading in the document being linked *to*, and rendered
710 // headings carry ids — so it is carried across rather than dropped. A query means
711 // nothing to a tree URL and is left behind. A destination that is only a fragment
712 // has no path and stays exactly as written, which is what makes a link inside the
713 // same README work.
714 let (target, fragment) = split_fragment(destination);
715 let target = target.split('?').next()?;
716 let target = target.strip_prefix("./").unwrap_or(target);
717
718 // `RepoPath` refuses `..` and `.` components, so a link cannot walk out of the
719 // repository — it simply stays as it was written.
720 let path = RepoPath::new(target).ok()?;
721
722 if path.is_root() {
723 return None;
724 }
725
726 Some(format!("{}{fragment}", tree_url(handle, name, rev, &path)))
727}
728
729/// A destination split into what it points at and the `#fragment` inside it.
730///
731/// The fragment keeps its `#`, so it is either empty or ready to append.
732pub(super) fn split_fragment(destination: &str) -> (&str, &str) {
733 match destination.split_once('#') {
734 Some((target, _)) => (target, &destination[target.len()..]),
735 None => (destination, ""),
736 }
737}
738
739/// The rendered README, under the file listing.
740///
741/// Reading it costs the page one more `git` call, which is why it is the only file the
742/// page fetches beyond the listing itself.
743///
744/// A component rather than a function because `view!` needs the request context in
745/// scope — see [`browsing`](super::browse).
746#[component]
747async fn readme_card(cx: &Cx, repo: &RepoView, rev: &RefName, entry: &TreeEntry) -> Result {
748 let path = RepoPath::new(&entry.name).map_err(|_| not_found())?;
749
750 // The entry came out of a listing read moments ago, so anything but a file means
751 // the tree changed underneath this request. A vanished README is not a reason to
752 // fail the page it was going to decorate.
753 let Browsed::File { file, .. } = browsed_at(cx, repo, Some(rev), &path).await? else {
754 return view! {};
755 };
756
757 let handle = repo.handle.as_str();
758 let name = repo.name.as_str();
759
760 view! {
761 <section class="mt-6 overflow-hidden rounded-lg border border-border">
762 <div class="border-b border-border px-4 py-2.5">
763 <a
764 href=(tree_url(handle, name, rev, &path))
765 class="font-mono text-sm hover:underline"
766 >(&entry.name)</a>
767 </div>
768 readme_body(handle: handle, name: name, rev: rev, file: &file)
769 </section>
770 }
771}
772
773/// A README's contents, in the three states a file can be in.
774///
775/// Split out so the `view!` holding the rendered markdown is the only place the
776/// escape hatch is used, and it is one line long.
777#[component]
778async fn readme_body(handle: &str, name: &str, rev: &RefName, file: &FileView) -> Result {
779 view! {
780 match &file.text {
781 // The only unescaped content on any Steid page. It is safe because
782 // `markdown` writes every tag itself and never passes source HTML
783 // through — see that module's header.
784 Some(text) => <div class="px-5 py-4 text-sm [&>*:first-child]:mt-0 [&>*:last-child]:mb-0">
785 (markdown::render_with_links(
786 text,
787 Some(markdown::Crossref {
788 handle,
789 name,
790 origin: None,
791 }),
792 |destination| readme_link(handle, name, rev, destination),
793 ))
794 </div>,
795 None if file.too_large => <p class="px-4 py-6 text-center text-sm text-muted-foreground">
796 "This README is too large to render here. Open it in the file listing above."
797 </p>,
798 None => <p class="px-4 py-6 text-center text-sm text-muted-foreground">
799 "This README is not valid UTF-8, so it cannot be rendered."
800 </p>,
801 }
802 }
803}
804
805/// The creation form.
806///
807/// Values arrive as parameters rather than being read back, so a rejected submission
808/// re-renders exactly what was typed.
809#[component]
810pub(super) async fn new_repo_form(
811 handle: &str,
812 name: &str,
813 description: &str,
814 visibility: Visibility,
815 error: &str,
816 /// The import block's own state, carried through so a refused import re-renders the
817 /// page it was submitted from rather than a screen of its own. Default whenever the
818 /// create form is the one being answered — see [`web::import`](super::import).
819 import: &ImportBlock,
820) -> Result {
821 view! {
822 narrow(
823 <h1 class="text-xl font-semibold tracking-tight">"New repository"</h1>
824 <p class="mt-1 font-mono text-sm text-muted-foreground">"@" (handle)</p>
825
826 if !error.is_empty() {
827 <div class="mt-6">
828 flash(kind: FlashKind::Error, (error))
829 </div>
830 }
831
832 <form method="post" action=(format!("/{handle}/repos/new")) class="mt-6 space-y-5">
833 csrf_field()
834 <div class="space-y-2">
835 label(attrs: attributes! { for="name" }, "Name")
836 input(attrs: attributes! {
837 id="name"
838 name="name"
839 type="text"
840 value=(name)
841 placeholder="my-project"
842 required=(true)
843 maxlength=(RepoName::MAX_LEN.to_string())
844 autofocus=(true)
845 })
846 <p class="text-xs text-muted-foreground">
847 "Letters, digits, hyphens, underscores and dots. Lowercased."
848 </p>
849 </div>
850
851 <div class="space-y-2">
852 label(attrs: attributes! { for="description" }, "Description")
853 textarea(
854 attrs: attributes! {
855 id="description"
856 name="description"
857 rows="2"
858 maxlength=(Repository::MAX_DESCRIPTION_LEN.to_string())
859 placeholder="A sentence for your profile."
860 },
861 (description)
862 )
863 <p class="text-xs text-muted-foreground">
864 "Optional. At most "
865 (Repository::MAX_DESCRIPTION_LEN.to_string()) " characters."
866 </p>
867 </div>
868
869 <div class="space-y-2">
870 label(attrs: attributes! { for="visibility" }, "Visibility")
871 select(
872 attrs: attributes! { id="visibility" name="visibility" },
873 <option value="public" selected=(visibility.is_public())>"Public"</option>
874 <option value="private" selected=(!visibility.is_public())>"Private"</option>
875 )
876 <p class="text-xs text-muted-foreground">
877 "Private is the default. A public repository appears on your "
878 "home page to anyone, and can be cloned without a token."
879 </p>
880 </div>
881
882 <div class="flex items-center gap-3">
883 button(attrs: attributes! { type="submit" }, "Create repository")
884 <a
885 href=(format!("/{handle}"))
886 class="text-sm text-muted-foreground hover:text-foreground"
887 >"Cancel"</a>
888 </div>
889 </form>
890
891 import_block(handle: handle, state: import)
892 )
893 }
894}
895
896/// The Repositories section of a profile.
897///
898/// Takes the already-filtered summaries rather than fetching: which repositories a
899/// viewer may see is [`list_repos`](crate::application::list_repos)'s decision, and a
900/// component that queried for itself would be a second place that rule could live.
901///
902/// One empty state serves both "no repositories" and "none you may see" — a distinct
903/// message for the second would leak that private repositories exist.
904/// The URL to clone this repository from.
905///
906/// Built from the origin the page is being served on, so it is correct wherever the
907/// instance is deployed without anything having to be configured. A private repository
908/// gets the same URL: cloning it needs a token, not a different address.
909pub(super) fn clone_url_for(cx: &Cx, repo: &RepoView) -> String {
910 format!(
911 "{}/{}/repos/{}.git",
912 public_origin(cx),
913 repo.handle,
914 repo.name
915 )
916}
917
918#[cfg(test)]
919mod tests {
920 use crate::domain::ObjectId;
921
922 use super::*;
923
924 fn entry(name: &str, kind: EntryKind) -> TreeEntry {
925 TreeEntry {
926 name: name.to_owned(),
927 kind,
928 id: ObjectId::from_trusted("0".repeat(40)),
929 size: Some(0),
930 }
931 }
932
933 fn rev() -> RefName {
934 RefName::new("main").expect("valid revision")
935 }
936
937 #[test]
938 fn the_usual_readme_spellings_are_all_readmes() {
939 for name in [
940 "README.md",
941 "readme.md",
942 "Readme.md",
943 "README",
944 "readme",
945 "README.markdown",
946 "README.mkd",
947 ] {
948 assert!(readme_rank(name).is_some(), "{name} should be a README");
949 }
950 }
951
952 #[test]
953 fn things_that_merely_start_with_readme_are_not_readmes() {
954 for name in [
955 "READMEISH.md",
956 "readme-first.md",
957 "README.rst",
958 "README.txt",
959 "docs.md",
960 "",
961 ] {
962 assert!(readme_rank(name).is_none(), "{name} should not be a README");
963 }
964 }
965
966 #[test]
967 fn the_markdown_readme_wins_over_the_plain_one() {
968 let entries = [
969 entry("readme", EntryKind::Blob),
970 entry("README.md", EntryKind::Blob),
971 ];
972
973 assert_eq!(
974 readme_of(&entries).map(|found| found.name.as_str()),
975 Some("README.md")
976 );
977 }
978
979 #[test]
980 fn a_directory_called_readme_is_not_a_readme() {
981 // Reading it would ask git for a blob at a tree's path and get nothing.
982 let entries = [entry("readme", EntryKind::Tree)];
983
984 assert!(readme_of(&entries).is_none());
985 }
986
987 #[test]
988 fn a_listing_without_one_has_no_readme() {
989 let entries = [
990 entry("src", EntryKind::Tree),
991 entry("Cargo.toml", EntryKind::Blob),
992 ];
993
994 assert!(readme_of(&entries).is_none());
995 }
996
997 #[test]
998 fn a_relative_link_becomes_a_link_into_the_tree() {
999 assert_eq!(
1000 readme_link("ada", "steid", &rev(), "./CONTRIBUTING.md").as_deref(),
1001 Some("/ada/repos/steid/tree/main/-/CONTRIBUTING.md")
1002 );
1003 // The fragment comes with it: rendered headings carry ids, so the link lands
1004 // on the section it names rather than at the top of the file.
1005 assert_eq!(
1006 readme_link("ada", "steid", &rev(), "docs/design.md#why").as_deref(),
1007 Some("/ada/repos/steid/tree/main/-/docs/design.md#why")
1008 );
1009 // A query says nothing to a tree URL and is left behind.
1010 assert_eq!(
1011 readme_link("ada", "steid", &rev(), "docs/design.md?raw=1#why").as_deref(),
1012 Some("/ada/repos/steid/tree/main/-/docs/design.md#why")
1013 );
1014 }
1015
1016 #[test]
1017 fn a_link_to_a_heading_in_the_same_document_is_left_alone() {
1018 // There is no path to resolve, and the README is already the page.
1019 assert!(readme_link("ada", "steid", &rev(), "#usage").is_none());
1020 }
1021
1022 #[test]
1023 fn a_link_that_would_walk_out_of_the_repository_is_left_alone() {
1024 for destination in ["../elsewhere.md", "./", "", "a/../b.md"] {
1025 assert!(
1026 readme_link("ada", "steid", &rev(), destination).is_none(),
1027 "{destination} should not resolve"
1028 );
1029 }
1030 }
1031}