steid

@jamesgill /

steid/src/infrastructure/web/repo_settings.rs
Rust26.8 KBCode·Blame·History·Raw
1//! Repository settings — `/{handle}/repos/{name}/settings`.
2//!
3//! Owner-only: change the description, change visibility, choose the default branch,
4//! archive, rename, delete.
5//!
6//! `settings` sits in the verb position after `{name}`, where nothing user-controlled
7//! ever appears, so unlike `new` it needs no reservation in
8//! [`RepoName`](crate::domain::RepoName).
9//!
10//! **A non-owner gets a 404, not a 403.** That is the rule
11//! [`view_repo`](crate::application::view_repo) already sets for repositories: a 403
12//! would confirm that a private repository by that name exists, and there is no reason
13//! for the settings page to be more talkative than the repository page it belongs to.
14
15use serde::Deserialize;
16use topcoat::{
17 Result,
18 context::Cx,
19 router::{StatusCode, content::Form, error::not_found, page, query_params},
20 view::{attributes, component, view},
21};
22
23use crate::{
24 application::{
25 Error, RepoView, list_branches,
26 repo::{
27 RepoEdit, delete_repo, rename_repo, set_default_branch, set_repo_archived, update_repo,
28 },
29 },
30 components::{
31 button::{ButtonVariant, button},
32 flash::{FlashKind, flash},
33 input::input,
34 label::label,
35 select::select,
36 textarea::textarea,
37 },
38 domain::{BranchRow, DomainError, RepoName, Repository, Visibility},
39};
40
41use super::{
42 context::{current_actor, location, memberships, orgs, queries, repos, server_error, storage},
43 layout::narrow,
44 repo::repo_for,
45};
46
47#[derive(Debug, Deserialize)]
48struct SettingsForm {
49 description: String,
50 visibility: String,
51 /// A checkbox: present when ticked, absent entirely when not. `Option` is the shape
52 /// the browser actually sends, so it is the shape parsed.
53 pinned: Option<String>,
54}
55
56/// Which way the archive button is pointing. A hidden field rather than two routes,
57/// so the form that renders the button also states what it does.
58#[derive(Debug, Deserialize)]
59struct ArchiveForm {
60 archived: String,
61}
62
63#[derive(Debug, Deserialize)]
64struct DefaultBranchForm {
65 branch: String,
66}
67
68#[derive(Debug, Deserialize)]
69struct RenameForm {
70 name: String,
71}
72
73#[derive(Debug, Deserialize)]
74struct DeleteForm {
75 confirm: String,
76}
77
78/// Set after a successful save so the confirmation survives the redirect.
79///
80/// Post-redirect-get: reloading after a save must not resubmit it.
81#[query_params(error = bad_request)]
82struct Saved {
83 saved: Option<String>,
84}
85
86/// Blank input means "clear this field", which the domain treats as unset.
87fn optional(value: &str) -> Option<String> {
88 Some(value.trim().to_owned()).filter(|value| !value.is_empty())
89}
90
91/// Resolves the repository in the path, or 404 for anyone who does not own it.
92///
93/// [`repo_for`] already 404s for a repository the viewer may not see; this adds the
94/// stronger half. The use cases decide this too — the guard here only keeps a page from
95/// rendering for someone whose submission would be refused anyway.
96async fn owned_repo(cx: &Cx) -> Result<RepoView> {
97 let repo = repo_for(cx).await?;
98
99 if !repo.viewer_is_owner {
100 return Err(not_found().into());
101 }
102
103 Ok(repo)
104}
105
106/// The repository's branches, for the default-branch control.
107///
108/// **One `git` process** — two on an empty repository, which is the case that spends
109/// the least elsewhere. The rows already say which branch `HEAD` names, so nothing has
110/// to ask `symbolic-ref` as well.
111///
112/// An empty list means an empty repository, and the control is left out rather than
113/// rendered with nothing in it.
114async fn branches_of(cx: &Cx, repo: &RepoView) -> Result<Vec<BranchRow>> {
115 Ok(list_branches(
116 &repo.handle,
117 &repo.name,
118 &current_actor(cx).await?,
119 &orgs(cx),
120 &memberships(cx),
121 &repos(cx),
122 &queries(cx),
123 )
124 .await
125 .map_err(server_error)?
126 .map(|page| page.rows)
127 .unwrap_or_default())
128}
129
130#[page("/{handle}/repos/{name}/settings")]
131async fn repo_settings_page(cx: &Cx) -> Result {
132 let repo = owned_repo(cx).await?;
133 let saved = query_params::<Saved>(cx)?.saved.is_some();
134 let branches = branches_of(cx, &repo).await?;
135
136 view! {
137 settings_view(
138 handle: repo.handle.as_str(),
139 name: repo.name.as_str(),
140 fields: Fields {
141 description: repo.description.as_deref().unwrap_or(""),
142 visibility: repo.visibility,
143 pinned: repo.pinned,
144 rename_to: repo.name.as_str(),
145 archived: repo.archived,
146 },
147 branches: &branches,
148 saved: saved,
149 error: "",
150 )
151 }
152}
153
154/// Saves the description and visibility.
155///
156/// Success replies 303 so a reload cannot resubmit — see
157/// [`location`](super::context::location) for why it is spelled this way rather than
158/// with `redirect()`, which is a 307 and would re-POST this form to itself.
159///
160/// Failure re-renders with the reason and **what was typed**, rather than bouncing back
161/// to the stored values and hiding what went wrong.
162#[page(POST "/{handle}/repos/{name}/settings")]
163async fn save(cx: &Cx, Form(submitted): Form<SettingsForm>) -> Result {
164 let repo = owned_repo(cx).await?;
165
166 // An unparseable value is a tampered form, not something to default: defaulting
167 // here could publish a repository the owner asked to keep private.
168 let visibility = submitted
169 .visibility
170 .parse::<Visibility>()
171 .map_err(|_| topcoat::router::error::bad_request("unknown visibility"))?;
172
173 let outcome = update_repo(
174 &current_actor(cx).await?,
175 &repo.handle,
176 &repo.name,
177 &RepoEdit {
178 description: optional(&submitted.description),
179 visibility,
180 pinned: submitted.pinned.is_some(),
181 },
182 &orgs(cx),
183 &memberships(cx),
184 &repos(cx),
185 )
186 .await;
187
188 let message = match outcome {
189 Ok(_) => {
190 return view! {
191 (StatusCode::SEE_OTHER)
192 (location(&format!(
193 "/{}/repos/{}/settings?saved",
194 repo.handle, repo.name
195 ))?)
196 };
197 }
198 // The visitor's to fix, so it is shown.
199 Err(Error::Domain(DomainError::Validation { field, reason })) => {
200 format!("That {field} is no good: {reason}.")
201 }
202 // Both mean "not yours" here, and both look like a page that is not there.
203 Err(Error::Domain(DomainError::Forbidden | DomainError::NotFound { .. })) => {
204 return Err(not_found().into());
205 }
206 // Ours, so it is logged and answered generically.
207 Err(other) => return Err(server_error(std::io::Error::other(other.to_string()))),
208 };
209
210 let branches = branches_of(cx, &repo).await?;
211
212 view! {
213 settings_view(
214 handle: repo.handle.as_str(),
215 name: repo.name.as_str(),
216 fields: Fields {
217 description: submitted.description.as_str(),
218 visibility,
219 pinned: submitted.pinned.is_some(),
220 rename_to: repo.name.as_str(),
221 archived: repo.archived,
222 },
223 branches: &branches,
224 saved: false,
225 error: message.as_str(),
226 )
227 }
228}
229
230/// Archives or unarchives the repository.
231///
232/// Both directions through one route, because they are one state with two values and
233/// splitting them would put the rule in the router rather than in the use case.
234#[page(POST "/{handle}/repos/{name}/settings/archive")]
235async fn archive(cx: &Cx, Form(submitted): Form<ArchiveForm>) -> Result {
236 let repo = owned_repo(cx).await?;
237
238 // An unparseable value is a tampered form, not something to default: defaulting
239 // here could reopen a repository its owner closed.
240 let archived = match submitted.archived.as_str() {
241 "true" => true,
242 "false" => false,
243 _ => return Err(topcoat::router::error::bad_request("unknown archive state").into()),
244 };
245
246 match set_repo_archived(
247 &current_actor(cx).await?,
248 &repo.handle,
249 &repo.name,
250 archived,
251 &orgs(cx),
252 &memberships(cx),
253 &repos(cx),
254 )
255 .await
256 {
257 Ok(_) => {}
258 Err(Error::Domain(DomainError::Forbidden | DomainError::NotFound { .. })) => {
259 return Err(not_found().into());
260 }
261 Err(other) => return Err(server_error(std::io::Error::other(other.to_string()))),
262 }
263
264 view! {
265 (StatusCode::SEE_OTHER)
266 (location(&format!(
267 "/{}/repos/{}/settings?saved",
268 repo.handle, repo.name
269 ))?)
270 }
271}
272
273/// Points `HEAD` at the chosen branch.
274///
275/// No column is written — see
276/// [`set_default_branch`](crate::application::repo::set_default_branch). The landing
277/// page follows `HEAD` on the next request.
278#[page(POST "/{handle}/repos/{name}/settings/default-branch")]
279async fn default_branch(cx: &Cx, Form(submitted): Form<DefaultBranchForm>) -> Result {
280 let repo = owned_repo(cx).await?;
281
282 let outcome = set_default_branch(
283 &current_actor(cx).await?,
284 &repo.handle,
285 &repo.name,
286 &submitted.branch,
287 &orgs(cx),
288 &memberships(cx),
289 &repos(cx),
290 &queries(cx),
291 &storage(cx),
292 )
293 .await;
294
295 let message = match outcome {
296 Ok(_) => {
297 return view! {
298 (StatusCode::SEE_OTHER)
299 (location(&format!(
300 "/{}/repos/{}/settings?saved",
301 repo.handle, repo.name
302 ))?)
303 };
304 }
305 // A branch that is gone is the one failure a visitor can act on: the select was
306 // rendered from a list that has since changed under them.
307 Err(Error::Domain(DomainError::NotFound { entity: "branch" })) => format!(
308 "{} is not a branch of this repository any more. Nothing changed.",
309 submitted.branch.trim()
310 ),
311 Err(Error::Domain(DomainError::Validation { field, reason })) => {
312 format!("That {field} is no good: {reason}.")
313 }
314 Err(Error::Domain(DomainError::Forbidden | DomainError::NotFound { .. })) => {
315 return Err(not_found().into());
316 }
317 Err(other) => return Err(server_error(std::io::Error::other(other.to_string()))),
318 };
319
320 let branches = branches_of(cx, &repo).await?;
321
322 view! {
323 settings_view(
324 handle: repo.handle.as_str(),
325 name: repo.name.as_str(),
326 fields: Fields {
327 description: repo.description.as_deref().unwrap_or(""),
328 visibility: repo.visibility,
329 pinned: repo.pinned,
330 rename_to: repo.name.as_str(),
331 archived: repo.archived,
332 },
333 branches: &branches,
334 saved: false,
335 error: message.as_str(),
336 )
337 }
338}
339
340/// Renames the repository, then sends the owner to the new settings URL.
341///
342/// The old URL is gone rather than redirected — see
343/// [`rename_repo`](crate::application::repo::rename_repo) — so the 303 has to name the
344/// new one or the owner lands on their own 404.
345#[page(POST "/{handle}/repos/{name}/settings/rename")]
346async fn rename(cx: &Cx, Form(submitted): Form<RenameForm>) -> Result {
347 let repo = owned_repo(cx).await?;
348
349 let outcome = rename_repo(
350 &current_actor(cx).await?,
351 &repo.handle,
352 &repo.name,
353 &submitted.name,
354 &orgs(cx),
355 &memberships(cx),
356 &repos(cx),
357 &storage(cx),
358 )
359 .await;
360
361 let message = match outcome {
362 // The **returned** name, not what was typed: it normalised on the way in, and
363 // sending someone to `/MyForge/settings` would 404 on their own repository.
364 Ok(renamed) => {
365 return view! {
366 (StatusCode::SEE_OTHER)
367 (location(&format!(
368 "/{}/repos/{}/settings?saved",
369 repo.handle, renamed.name
370 ))?)
371 };
372 }
373 Err(Error::Domain(DomainError::Validation { field, reason })) => {
374 format!("That {field} is no good: {reason}.")
375 }
376 Err(Error::Domain(DomainError::AlreadyExists { .. })) => {
377 format!(
378 "You already have a repository called {}. Nothing was renamed.",
379 submitted.name.trim()
380 )
381 }
382 Err(Error::Domain(DomainError::Forbidden | DomainError::NotFound { .. })) => {
383 return Err(not_found().into());
384 }
385 Err(other) => return Err(server_error(std::io::Error::other(other.to_string()))),
386 };
387
388 let branches = branches_of(cx, &repo).await?;
389
390 view! {
391 settings_view(
392 handle: repo.handle.as_str(),
393 name: repo.name.as_str(),
394 fields: Fields {
395 description: repo.description.as_deref().unwrap_or(""),
396 visibility: repo.visibility,
397 pinned: repo.pinned,
398 rename_to: submitted.name.as_str(),
399 archived: repo.archived,
400 },
401 branches: &branches,
402 saved: false,
403 error: message.as_str(),
404 )
405 }
406}
407
408/// Deletes the repository, then sends the owner back to their profile.
409///
410/// The repository page no longer exists, so there is nowhere else to go.
411///
412/// **Guarded by typing the name.** Deletion takes the git history with it and there is
413/// no undo; a single button is too easy to hit by accident for something unrecoverable.
414/// The typed value goes through [`RepoName::new`], so it is compared the same way the
415/// name was normalised on the way in — `MyRepo` confirms `myrepo`, and stray whitespace
416/// is not a reason to refuse.
417#[page(POST "/{handle}/repos/{name}/settings/delete")]
418async fn delete(cx: &Cx, Form(submitted): Form<DeleteForm>) -> Result {
419 let repo = owned_repo(cx).await?;
420
421 let confirmed = RepoName::new(&submitted.confirm).is_ok_and(|typed| typed == repo.name);
422
423 if !confirmed {
424 let message = format!(
425 "Type {} exactly to confirm. Nothing was deleted.",
426 repo.name
427 );
428
429 let branches = branches_of(cx, &repo).await?;
430
431 return view! {
432 settings_view(
433 handle: repo.handle.as_str(),
434 name: repo.name.as_str(),
435 fields: Fields {
436 description: repo.description.as_deref().unwrap_or(""),
437 visibility: repo.visibility,
438 pinned: repo.pinned,
439 rename_to: repo.name.as_str(),
440 archived: repo.archived,
441 },
442 branches: &branches,
443 saved: false,
444 error: message.as_str(),
445 )
446 };
447 }
448
449 match delete_repo(
450 &current_actor(cx).await?,
451 &repo.handle,
452 &repo.name,
453 &orgs(cx),
454 &memberships(cx),
455 &repos(cx),
456 &storage(cx),
457 )
458 .await
459 {
460 Ok(()) => {}
461 Err(Error::Domain(DomainError::Forbidden | DomainError::NotFound { .. })) => {
462 return Err(not_found().into());
463 }
464 Err(other) => return Err(server_error(std::io::Error::other(other.to_string()))),
465 }
466
467 view! {
468 (StatusCode::SEE_OTHER)
469 (location(&format!("/{}", repo.handle))?)
470 }
471}
472
473/// The values the forms edit, grouped so the view takes one argument for them rather
474/// than four that must be kept in the same order at five call sites.
475#[derive(Debug, Clone, Copy)]
476struct Fields<'a> {
477 description: &'a str,
478 visibility: Visibility,
479 pinned: bool,
480 /// What the rename field holds. The stored name almost always, and what was typed
481 /// when a rename was refused — a form that discards the attempt hides the reason.
482 rename_to: &'a str,
483 /// Whether the repository is archived. Read-only here: the control is a button that
484 /// flips it, not a field the description form can carry along.
485 archived: bool,
486}
487
488/// The settings page.
489///
490/// Values arrive as parameters rather than being read back from storage, so a rejected
491/// submission can re-render exactly what was typed.
492#[component]
493async fn settings_view(
494 handle: &str,
495 name: &str,
496 fields: Fields<'_>,
497 /// Every branch, the default first. Empty for a repository with nothing pushed.
498 branches: &[BranchRow],
499 saved: bool,
500 error: &str,
501) -> Result {
502 let Fields {
503 description,
504 visibility,
505 pinned,
506 rename_to,
507 archived,
508 } = fields;
509
510 view! {
511 narrow(
512 <h1 class="text-xl font-semibold tracking-tight">"Repository settings"</h1>
513 <p class="mt-1 font-mono text-sm text-muted-foreground">
514 "@" (handle) " / " (name)
515 </p>
516
517 // The section list. One entry today, and the slot a second lands in — the
518 // page is otherwise a single form and a new feature would have nowhere to
519 // announce itself.
520 <nav class="mt-4 flex items-center gap-4 border-b border-border pb-2 text-sm">
521 <span class="border-b-2 border-primary -mb-2.5 pb-2">"General"</span>
522 <a
523 href=(format!("/{handle}/repos/{name}/settings/hooks"))
524 class="text-muted-foreground hover:text-foreground"
525 >"Webhooks"</a>
526 </nav>
527
528 if saved {
529 <div class="mt-6">
530 flash(kind: FlashKind::Success, "Repository updated.")
531 </div>
532 }
533
534 if !error.is_empty() {
535 <div class="mt-6">
536 flash(kind: FlashKind::Error, (error))
537 </div>
538 }
539
540 <form
541 method="post"
542 action=(format!("/{handle}/repos/{name}/settings"))
543 class="mt-6 space-y-5"
544 >
545 <div class="space-y-2">
546 label(attrs: attributes! { for="description" }, "Description")
547 textarea(
548 attrs: attributes! {
549 id="description"
550 name="description"
551 rows="2"
552 maxlength=(Repository::MAX_DESCRIPTION_LEN.to_string())
553 placeholder="A sentence for your profile."
554 },
555 (description)
556 )
557 <p class="text-xs text-muted-foreground">
558 "Optional. At most "
559 (Repository::MAX_DESCRIPTION_LEN.to_string()) " characters."
560 </p>
561 </div>
562
563 <div class="space-y-2">
564 label(attrs: attributes! { for="visibility" }, "Visibility")
565 select(
566 attrs: attributes! { id="visibility" name="visibility" },
567 <option value="public" selected=(visibility.is_public())>"Public"</option>
568 <option value="private" selected=(!visibility.is_public())>"Private"</option>
569 )
570 <p class="text-xs text-muted-foreground">
571 "A private repository is hidden from your profile and needs a token "
572 "to clone."
573 </p>
574 </div>
575
576 <div class="space-y-2">
577 <div class="flex items-start gap-2">
578 <input
579 id="pinned"
580 name="pinned"
581 type="checkbox"
582 value="on"
583 checked=(pinned)
584 class="mt-0.5"
585 />
586 label(attrs: attributes! { for="pinned" }, "Lead my profile with this")
587 </div>
588 <p class="text-xs text-muted-foreground">
589 "One repository at a time. Choosing this one lets go of whichever "
590 "was chosen before."
591 </p>
592 </div>
593
594 <div class="flex items-center gap-3">
595 button(attrs: attributes! { type="submit" }, "Save")
596 <a
597 href=(format!("/{handle}/repos/{name}"))
598 class="text-sm text-muted-foreground hover:text-foreground"
599 >"Back to repository"</a>
600 </div>
601 </form>
602
603 <section class="mt-8 border-t border-border pt-6">
604 <h2 class="text-xs font-medium uppercase tracking-wider text-muted-foreground">
605 "Default branch"
606 </h2>
607
608 if branches.is_empty() {
609 <p class="mt-2 text-sm text-muted-foreground">
610 "Nothing has been pushed yet, so there is no branch to choose. "
611 "The first branch you push becomes the default."
612 </p>
613 } else {
614 <form
615 method="post"
616 action=(format!("/{handle}/repos/{name}/settings/default-branch"))
617 class="mt-3 flex flex-wrap items-center gap-3"
618 >
619 select(
620 attrs: attributes! {
621 id="branch"
622 name="branch"
623 class="font-mono sm:w-64"
624 aria-label="Default branch"
625 },
626 for branch in branches {
627 <option
628 value=(branch.name.as_str())
629 selected=(branch.is_default)
630 >(branch.name.as_str())</option>
631 }
632 )
633 button(
634 attrs: attributes! { type="submit" },
635 variant: ButtonVariant::Outline,
636 "Update"
637 )
638 </form>
639 <p class="mt-2 text-xs text-muted-foreground">
640 "What the repository opens at, and what a fresh clone checks out. "
641 "Stored in git as "<code class="font-mono">"HEAD"</code>", not in Steid."
642 </p>
643 }
644 </section>
645
646 <section class="mt-8 border-t border-border pt-6">
647 <h2 class="text-xs font-medium uppercase tracking-wider text-muted-foreground">
648 if archived { "Archived" } else { "Archive this repository" }
649 </h2>
650 <p class="mt-2 text-sm text-muted-foreground">
651 if archived {
652 "Pushes are refused. Everything that reads still works — browsing, "
653 "cloning, search and downloads."
654 } else {
655 "Marks it finished. Pushes are refused with a message; browsing, "
656 "cloning, search and downloads carry on unchanged. Reversible."
657 }
658 </p>
659
660 <form
661 method="post"
662 action=(format!("/{handle}/repos/{name}/settings/archive"))
663 class="mt-3"
664 >
665 <input
666 type="hidden"
667 name="archived"
668 value=(if archived { "false" } else { "true" })
669 />
670 button(
671 attrs: attributes! { type="submit" },
672 variant: ButtonVariant::Outline,
673 if archived { "Unarchive repository" } else { "Archive repository" }
674 )
675 </form>
676 </section>
677
678 <section class="mt-10 rounded-lg border border-border p-4">
679 <h2 class="text-xs font-medium uppercase tracking-wider text-muted-foreground">
680 "Rename this repository"
681 </h2>
682 <p class="mt-2 text-sm text-muted-foreground">
683 "The old URL stops working straight away — nothing redirects from it. "
684 "Existing clones must update their remote with "
685 <code class="font-mono text-xs">"git remote set-url origin …"</code>"."
686 </p>
687
688 <form
689 method="post"
690 action=(format!("/{handle}/repos/{name}/settings/rename"))
691 class="mt-4 space-y-2"
692 >
693 label(attrs: attributes! { for="rename" }, "New name")
694 input(attrs: attributes! {
695 id="rename"
696 name="name"
697 type="text"
698 value=(rename_to)
699 maxlength=(RepoName::MAX_LEN.to_string())
700 required=(true)
701 autocomplete="off"
702 class="font-mono"
703 })
704 <div class="pt-1">
705 button(
706 attrs: attributes! { type="submit" },
707 variant: ButtonVariant::Outline,
708 "Rename repository"
709 )
710 </div>
711 </form>
712 </section>
713
714 <section class="mt-10 rounded-lg border border-destructive/30 p-4">
715 <h2 class="text-xs font-medium uppercase tracking-wider text-destructive">
716 "Delete this repository"
717 </h2>
718 <p class="mt-2 text-sm text-muted-foreground">
719 "This cannot be undone. The commits, branches and tags go with it, and "
720 "anyone with a clone keeps their copy while this instance keeps nothing."
721 </p>
722
723 <form
724 method="post"
725 action=(format!("/{handle}/repos/{name}/settings/delete"))
726 class="mt-4 space-y-2"
727 >
728 label(
729 attrs: attributes! { for="confirm" },
730 "Type " (name) " to confirm"
731 )
732 input(attrs: attributes! {
733 id="confirm"
734 name="confirm"
735 type="text"
736 value=""
737 placeholder=(name)
738 required=(true)
739 autocomplete="off"
740 })
741 <div class="pt-1">
742 button(
743 attrs: attributes! { type="submit" },
744 variant: ButtonVariant::Destructive,
745 "Delete repository"
746 )
747 </div>
748 </form>
749 </section>
750 )
751 }
752}