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::Public,
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/// The portfolio pitch: a visitor arriving from a profile reads this before they read
498/// any code. Sections are separated by hairlines rather than boxed as cards — the same
499/// rule the profile page settled on, and the reason the page reads as one surface.
500#[component]
501async fn repo_about(repo: &RepoView, rev: &str, facts: Option<&RepoFacts>, clone: &str) -> Result {
502 let handle = repo.handle.as_str();
503 let name = repo.name.as_str();
504
505 view! {
506 <section class="text-sm">
507 <h2 class="text-xs font-medium uppercase tracking-wider text-muted-foreground">
508 "About"
509 </h2>
510 match &repo.description {
511 Some(description) => <p class="mt-2 leading-relaxed">(description)</p>,
512 // Shown rather than omitted, because an owner looking at their own
513 // portfolio should see the gap they can fill in.
514 None => <p class="mt-2 text-muted-foreground">"No description."</p>,
515 }
516 match facts.and_then(|facts| facts.licence.as_ref()) {
517 Some(licence) => <p class="mt-2">
518 <a
519 href=(tree_url(handle, name, &RefName::from_trusted(rev), &licence.path))
520 class="inline-flex items-center gap-1.5 text-xs text-muted-foreground hover:text-foreground"
521 >
522 icon(data: iconify_icon!("feather:book"), attrs: attributes! {
523 class="size-3.5"
524 })
525 // An unrecognised licence file is linked to and not named —
526 // see `Licence`. "Licence" is then the honest label.
527 (licence.name.unwrap_or("Licence"))
528 </a>
529 </p>,
530 None => "",
531 }
532 </section>
533
534 match facts {
535 Some(facts) => repo_stats(
536 handle: handle,
537 name: name,
538 facts: facts,
539 pushed: repo.updated_at,
540 ),
541 // With no commits there is nothing true to count, so the row that is still
542 // true is shown on its own.
543 None => <dl class="mt-4 space-y-1.5 border-t border-border pt-4 text-xs">
544 fact(term: "Pushed", (ago(repo.updated_at)))
545 </dl>,
546 }
547
548 clone_block(
549 handle: handle,
550 name: name,
551 rev: rev,
552 url: clone,
553 )
554 }
555}
556
557/// The numbers, as a definition list.
558///
559/// A list rather than a row of badges: every value is a different kind of thing, and
560/// the label is what makes each one readable at a glance.
561#[component]
562async fn repo_stats(handle: &str, name: &str, facts: &RepoFacts, pushed: SystemTime) -> Result {
563 view! {
564 <dl class="mt-4 space-y-1.5 border-t border-border pt-4 text-xs">
565 fact(term: "Commits", <span class="font-mono">(facts.commits.to_string())</span>)
566 // Links now that the pages exist — the sidebar is where a visitor reads
567 // how much of a repository there is, so it is also where they ask to see it.
568 fact(
569 term: "Branches",
570 <a href=(branches_url(handle, name)) class="font-mono hover:underline">
571 (facts.refs.branches.len().to_string())
572 </a>
573 )
574 fact(
575 term: "Tags",
576 <a href=(tags_url(handle, name)) class="font-mono hover:underline">
577 (facts.refs.tags.len().to_string())
578 </a>
579 )
580 match &facts.latest_tag {
581 Some(tag) => fact(
582 term: "Latest tag",
583 <span class="inline-flex items-center gap-1.5 font-mono">
584 icon(data: iconify_icon!("feather:tag"), attrs: attributes! {
585 class="size-3 text-muted-foreground"
586 })
587 (tag.name.as_str())
588 </span>
589 ),
590 // A repository with no releases says nothing rather than "none": an
591 // empty value reads as a thing that is missing.
592 None => "",
593 }
594 fact(term: "Pushed", (ago(pushed)))
595 </dl>
596 }
597}
598
599/// One label-and-value row of [`repo_stats`].
600///
601/// The parameter is `term`, not `label`: the copied-in `label` component is a unit
602/// struct in this module's scope and would shadow a binding of that name.
603#[component]
604async fn fact(term: &str, #[default] child: View) -> Result {
605 view! {
606 <div class="flex items-baseline justify-between gap-3">
607 <dt class="text-muted-foreground">(term)</dt>
608 <dd class="min-w-0 truncate">(child)</dd>
609 </div>
610 }
611}
612
613/// The clone address, ready to copy.
614///
615/// Shown for every repository a viewer can see, including an empty one — an empty
616/// repository is exactly when someone needs this, because it is what they push to.
617///
618/// The URL alone rather than `git clone <url>`: at sidebar width the command wraps or
619/// scrolls, and the address is the part being copied. It wraps rather than scrolls —
620/// a horizontally scrolled URL looks like a truncated one, and the part cut off is the
621/// repository's own name.
622///
623/// The two download links sit under it, for **the revision being viewed** rather than
624/// always the default branch: someone reading a tag wants that tag's tarball. An empty
625/// repository has no revision and gets no links — there is nothing to pack, and the
626/// clone URL above is the thing that is actually useful there.
627#[component]
628pub(super) async fn clone_block(handle: &str, name: &str, rev: &str, url: &str) -> Result {
629 view! {
630 <div class="mt-4 border-t border-border pt-4">
631 <p class="text-xs font-medium uppercase tracking-wider text-muted-foreground">
632 "Clone"
633 </p>
634 <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>
635
636 if !rev.is_empty() {
637 <p class="mt-2 flex items-center gap-2 text-xs text-muted-foreground">
638 icon(data: iconify_icon!("feather:download"), attrs: attributes! {
639 class="size-3.5"
640 })
641 "Download"
642 <a
643 href=(archive_url(handle, name, rev, ArchiveFormat::Zip))
644 class="font-mono hover:text-foreground hover:underline"
645 >"zip"</a>
646 "·"
647 <a
648 href=(archive_url(handle, name, rev, ArchiveFormat::TarGz))
649 class="font-mono hover:text-foreground hover:underline"
650 >"tar.gz"</a>
651 </p>
652 }
653 </div>
654 }
655}
656
657// --- README -----------------------------------------------------------------------
658
659/// Extensions a README may carry, in the order they are preferred.
660///
661/// Empty last: a plain `README` is a README, but a repository holding both `README.md`
662/// and `README` means the markdown one. Nothing that is not markdown is here — a
663/// `README.rst` rendered as markdown would be worse than the file listing.
664const README_EXTENSIONS: [&str; 5] = ["md", "markdown", "mdown", "mkd", ""];
665
666/// How strongly a name says "this is the README", or `None` if it does not.
667///
668/// Case-insensitive, because the file is spelled `README`, `readme` and `Readme` in the
669/// wild and all three mean the same thing.
670fn readme_rank(name: &str) -> Option<usize> {
671 let lowered = name.to_ascii_lowercase();
672 let extension = match lowered.strip_prefix("readme")? {
673 "" => "",
674 rest => rest.strip_prefix('.')?,
675 };
676
677 README_EXTENSIONS
678 .iter()
679 .position(|candidate| *candidate == extension)
680}
681
682/// The README in a listing, if there is one.
683///
684/// Chosen from the entries the page already has rather than by asking git for a file
685/// that may not exist: every `git` call is a fork of about 12ms, and a speculative one
686/// would be spent on every repository without a README. See
687/// [0006](../../../plans/decisions/0006-git-binary-behind-narrow-ports.md).
688fn readme_of(entries: &[TreeEntry]) -> Option<&TreeEntry> {
689 entries
690 .iter()
691 .filter(|entry| entry.kind == EntryKind::Blob)
692 .filter_map(|entry| Some((readme_rank(&entry.name)?, entry)))
693 .min_by_key(|(rank, _)| *rank)
694 .map(|(_, entry)| entry)
695}
696
697/// Where a relative link in a README should point.
698///
699/// A README's links are written against the repository's own files, so `./CONTRIBUTING.md`
700/// means a file in the tree and not a Steid route — left alone it would 404. Anything
701/// this cannot make sense of returns `None` and is left exactly as written, which is the
702/// same thing a plain markdown renderer would do.
703///
704/// Only links. A relative *image* is left alone deliberately: an image needs the file's
705/// bytes, and a tree URL serves a page, so rewriting one would trade a 404 for a broken
706/// image. [`markdown::render_with_links`] never offers this an image.
707fn readme_link(handle: &str, name: &str, rev: &RefName, destination: &str) -> Option<String> {
708 // A fragment names a heading in the document being linked *to*, and rendered
709 // headings carry ids — so it is carried across rather than dropped. A query means
710 // nothing to a tree URL and is left behind. A destination that is only a fragment
711 // has no path and stays exactly as written, which is what makes a link inside the
712 // same README work.
713 let (target, fragment) = split_fragment(destination);
714 let target = target.split('?').next()?;
715 let target = target.strip_prefix("./").unwrap_or(target);
716
717 // `RepoPath` refuses `..` and `.` components, so a link cannot walk out of the
718 // repository — it simply stays as it was written.
719 let path = RepoPath::new(target).ok()?;
720
721 if path.is_root() {
722 return None;
723 }
724
725 Some(format!("{}{fragment}", tree_url(handle, name, rev, &path)))
726}
727
728/// A destination split into what it points at and the `#fragment` inside it.
729///
730/// The fragment keeps its `#`, so it is either empty or ready to append.
731pub(super) fn split_fragment(destination: &str) -> (&str, &str) {
732 match destination.split_once('#') {
733 Some((target, _)) => (target, &destination[target.len()..]),
734 None => (destination, ""),
735 }
736}
737
738/// The rendered README, under the file listing.
739///
740/// Reading it costs the page one more `git` call, which is why it is the only file the
741/// page fetches beyond the listing itself.
742///
743/// A component rather than a function because `view!` needs the request context in
744/// scope — see [`browsing`](super::browse).
745#[component]
746async fn readme_card(cx: &Cx, repo: &RepoView, rev: &RefName, entry: &TreeEntry) -> Result {
747 let path = RepoPath::new(&entry.name).map_err(|_| not_found())?;
748
749 // The entry came out of a listing read moments ago, so anything but a file means
750 // the tree changed underneath this request. A vanished README is not a reason to
751 // fail the page it was going to decorate.
752 let Browsed::File { file, .. } = browsed_at(cx, repo, Some(rev), &path).await? else {
753 return view! {};
754 };
755
756 let handle = repo.handle.as_str();
757 let name = repo.name.as_str();
758
759 view! {
760 <section class="mt-6 overflow-hidden rounded-lg border border-border">
761 <div class="border-b border-border px-4 py-2.5">
762 <a
763 href=(tree_url(handle, name, rev, &path))
764 class="font-mono text-sm hover:underline"
765 >(&entry.name)</a>
766 </div>
767 readme_body(handle: handle, name: name, rev: rev, file: &file)
768 </section>
769 }
770}
771
772/// A README's contents, in the three states a file can be in.
773///
774/// Split out so the `view!` holding the rendered markdown is the only place the
775/// escape hatch is used, and it is one line long.
776#[component]
777async fn readme_body(handle: &str, name: &str, rev: &RefName, file: &FileView) -> Result {
778 view! {
779 match &file.text {
780 // The only unescaped content on any Steid page. It is safe because
781 // `markdown` writes every tag itself and never passes source HTML
782 // through — see that module's header.
783 Some(text) => <div class="px-5 py-4 text-sm [&>*:first-child]:mt-0 [&>*:last-child]:mb-0">
784 (markdown::render_with_links(
785 text,
786 Some(markdown::Crossref {
787 handle,
788 name,
789 origin: None,
790 }),
791 |destination| readme_link(handle, name, rev, destination),
792 ))
793 </div>,
794 None if file.too_large => <p class="px-4 py-6 text-center text-sm text-muted-foreground">
795 "This README is too large to render here. Open it in the file listing above."
796 </p>,
797 None => <p class="px-4 py-6 text-center text-sm text-muted-foreground">
798 "This README is not valid UTF-8, so it cannot be rendered."
799 </p>,
800 }
801 }
802}
803
804/// The creation form.
805///
806/// Values arrive as parameters rather than being read back, so a rejected submission
807/// re-renders exactly what was typed.
808#[component]
809pub(super) async fn new_repo_form(
810 handle: &str,
811 name: &str,
812 description: &str,
813 visibility: Visibility,
814 error: &str,
815 /// The import block's own state, carried through so a refused import re-renders the
816 /// page it was submitted from rather than a screen of its own. Default whenever the
817 /// create form is the one being answered — see [`web::import`](super::import).
818 import: &ImportBlock,
819) -> Result {
820 view! {
821 narrow(
822 <h1 class="text-xl font-semibold tracking-tight">"New repository"</h1>
823 <p class="mt-1 font-mono text-sm text-muted-foreground">"@" (handle)</p>
824
825 if !error.is_empty() {
826 <div class="mt-6">
827 flash(kind: FlashKind::Error, (error))
828 </div>
829 }
830
831 <form method="post" action=(format!("/{handle}/repos/new")) class="mt-6 space-y-5">
832 csrf_field()
833 <div class="space-y-2">
834 label(attrs: attributes! { for="name" }, "Name")
835 input(attrs: attributes! {
836 id="name"
837 name="name"
838 type="text"
839 value=(name)
840 placeholder="my-project"
841 required=(true)
842 maxlength=(RepoName::MAX_LEN.to_string())
843 autofocus=(true)
844 })
845 <p class="text-xs text-muted-foreground">
846 "Letters, digits, hyphens, underscores and dots. Lowercased."
847 </p>
848 </div>
849
850 <div class="space-y-2">
851 label(attrs: attributes! { for="description" }, "Description")
852 textarea(
853 attrs: attributes! {
854 id="description"
855 name="description"
856 rows="2"
857 maxlength=(Repository::MAX_DESCRIPTION_LEN.to_string())
858 placeholder="A sentence for your profile."
859 },
860 (description)
861 )
862 <p class="text-xs text-muted-foreground">
863 "Optional. At most "
864 (Repository::MAX_DESCRIPTION_LEN.to_string()) " characters."
865 </p>
866 </div>
867
868 <div class="space-y-2">
869 label(attrs: attributes! { for="visibility" }, "Visibility")
870 select(
871 attrs: attributes! { id="visibility" name="visibility" },
872 <option value="public" selected=(visibility.is_public())>"Public"</option>
873 <option value="private" selected=(!visibility.is_public())>"Private"</option>
874 )
875 <p class="text-xs text-muted-foreground">
876 "Public repositories appear on your profile to anyone."
877 </p>
878 </div>
879
880 <div class="flex items-center gap-3">
881 button(attrs: attributes! { type="submit" }, "Create repository")
882 <a
883 href=(format!("/{handle}"))
884 class="text-sm text-muted-foreground hover:text-foreground"
885 >"Cancel"</a>
886 </div>
887 </form>
888
889 import_block(handle: handle, state: import)
890 )
891 }
892}
893
894/// The Repositories section of a profile.
895///
896/// Takes the already-filtered summaries rather than fetching: which repositories a
897/// viewer may see is [`list_repos`](crate::application::list_repos)'s decision, and a
898/// component that queried for itself would be a second place that rule could live.
899///
900/// One empty state serves both "no repositories" and "none you may see" — a distinct
901/// message for the second would leak that private repositories exist.
902/// The URL to clone this repository from.
903///
904/// Built from the origin the page is being served on, so it is correct wherever the
905/// instance is deployed without anything having to be configured. A private repository
906/// gets the same URL: cloning it needs a token, not a different address.
907pub(super) fn clone_url_for(cx: &Cx, repo: &RepoView) -> String {
908 format!(
909 "{}/{}/repos/{}.git",
910 public_origin(cx),
911 repo.handle,
912 repo.name
913 )
914}
915
916#[cfg(test)]
917mod tests {
918 use crate::domain::ObjectId;
919
920 use super::*;
921
922 fn entry(name: &str, kind: EntryKind) -> TreeEntry {
923 TreeEntry {
924 name: name.to_owned(),
925 kind,
926 id: ObjectId::from_trusted("0".repeat(40)),
927 size: Some(0),
928 }
929 }
930
931 fn rev() -> RefName {
932 RefName::new("main").expect("valid revision")
933 }
934
935 #[test]
936 fn the_usual_readme_spellings_are_all_readmes() {
937 for name in [
938 "README.md",
939 "readme.md",
940 "Readme.md",
941 "README",
942 "readme",
943 "README.markdown",
944 "README.mkd",
945 ] {
946 assert!(readme_rank(name).is_some(), "{name} should be a README");
947 }
948 }
949
950 #[test]
951 fn things_that_merely_start_with_readme_are_not_readmes() {
952 for name in [
953 "READMEISH.md",
954 "readme-first.md",
955 "README.rst",
956 "README.txt",
957 "docs.md",
958 "",
959 ] {
960 assert!(readme_rank(name).is_none(), "{name} should not be a README");
961 }
962 }
963
964 #[test]
965 fn the_markdown_readme_wins_over_the_plain_one() {
966 let entries = [
967 entry("readme", EntryKind::Blob),
968 entry("README.md", EntryKind::Blob),
969 ];
970
971 assert_eq!(
972 readme_of(&entries).map(|found| found.name.as_str()),
973 Some("README.md")
974 );
975 }
976
977 #[test]
978 fn a_directory_called_readme_is_not_a_readme() {
979 // Reading it would ask git for a blob at a tree's path and get nothing.
980 let entries = [entry("readme", EntryKind::Tree)];
981
982 assert!(readme_of(&entries).is_none());
983 }
984
985 #[test]
986 fn a_listing_without_one_has_no_readme() {
987 let entries = [
988 entry("src", EntryKind::Tree),
989 entry("Cargo.toml", EntryKind::Blob),
990 ];
991
992 assert!(readme_of(&entries).is_none());
993 }
994
995 #[test]
996 fn a_relative_link_becomes_a_link_into_the_tree() {
997 assert_eq!(
998 readme_link("ada", "steid", &rev(), "./CONTRIBUTING.md").as_deref(),
999 Some("/ada/repos/steid/tree/main/-/CONTRIBUTING.md")
1000 );
1001 // The fragment comes with it: rendered headings carry ids, so the link lands
1002 // on the section it names rather than at the top of the file.
1003 assert_eq!(
1004 readme_link("ada", "steid", &rev(), "docs/design.md#why").as_deref(),
1005 Some("/ada/repos/steid/tree/main/-/docs/design.md#why")
1006 );
1007 // A query says nothing to a tree URL and is left behind.
1008 assert_eq!(
1009 readme_link("ada", "steid", &rev(), "docs/design.md?raw=1#why").as_deref(),
1010 Some("/ada/repos/steid/tree/main/-/docs/design.md#why")
1011 );
1012 }
1013
1014 #[test]
1015 fn a_link_to_a_heading_in_the_same_document_is_left_alone() {
1016 // There is no path to resolve, and the README is already the page.
1017 assert!(readme_link("ada", "steid", &rev(), "#usage").is_none());
1018 }
1019
1020 #[test]
1021 fn a_link_that_would_walk_out_of_the_repository_is_left_alone() {
1022 for destination in ["../elsewhere.md", "./", "", "a/../b.md"] {
1023 assert!(
1024 readme_link("ada", "steid", &rev(), destination).is_none(),
1025 "{destination} should not resolve"
1026 );
1027 }
1028 }
1029}