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