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