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