steid

@jamesgill /

Rust14.5 KBCode·Blame·History·Raw
1//! Importing a repository from a URL — the second way to create one.
2//!
3//! The form lives on `/{handle}/repos/new` beside the create form, but everything it
4//! needs is here: its own POST route at `/{handle}/repos/import` (a static segment, and
5//! `RepoName` reserves `import` so the two agree), the background task, and the two
6//! panels the repository page shows while a copy is running or after it failed.
7
8use serde::Deserialize;
9use topcoat::{
10 Result,
11 context::{Cx, app_context},
12 icon::{icon, iconify::iconify_icon},
13 router::{StatusCode, content::Form, error::forbidden, page},
14 view::{attributes, component, view},
15};
16
17use crate::{
18 application::{
19 AppConfig, Error, ImportStatus, NewImport, RepoView, import_failure_message, import_repo,
20 run_import,
21 },
22 components::{
23 button::{ButtonVariant, button},
24 flash::{FlashKind, flash},
25 input::input,
26 label::label,
27 },
28 domain::{DomainError, ImportSource, RepoName, Visibility},
29 infrastructure::{
30 git::{DiskGitImport, DiskGitStorage},
31 repository::SqliteRepoRepo,
32 },
33};
34
35use super::{
36 context::{current_actor, location, memberships, orgs, pool, repos, server_error},
37 profile::profile_for,
38 repo::{Tab, clone_block, clone_url_for, new_repo_form, repo_header},
39};
40
41#[derive(Debug, Deserialize)]
42struct ImportForm {
43 name: String,
44 source: String,
45}
46
47/// Starts an import, then hands the work to a background task.
48///
49/// Success redirects to the repository, which already exists as a row and renders the
50/// importing panel — so the owner watches it from the page they would have landed on
51/// anyway rather than from a screen that exists only during an import.
52///
53/// **The task is spawned here, not in the use case.** The application layer has no
54/// business owning a runtime, and a use case that starts a task cannot be tested
55/// without waiting for one. What it needs is cloned in: a pool handle and the data
56/// directory, both cheap to clone and neither borrowing the request.
57#[page(POST "/{handle}/repos/import")]
58async fn start_import(cx: &Cx, Form(submitted): Form<ImportForm>) -> Result {
59 let profile = profile_for(cx).await?;
60
61 let outcome = import_repo(
62 &current_actor(cx).await?,
63 &profile.handle,
64 &NewImport {
65 name: submitted.name.clone(),
66 source: submitted.source.clone(),
67 },
68 &orgs(cx),
69 &memberships(cx),
70 &repos(cx),
71 )
72 .await;
73
74 let repo = match outcome {
75 Ok(repo) => repo,
76 Err(Error::Domain(DomainError::Forbidden)) => return Err(forbidden().into()),
77 Err(error) => {
78 let Some(message) = import_failure_message(&error, &submitted.name) else {
79 return Err(server_error(std::io::Error::other(error.to_string())));
80 };
81
82 // Re-rendered rather than redirected, so the URL that was typed is still in
83 // the box beside the reason it was refused.
84 let state = ImportBlock {
85 name: submitted.name,
86 source: submitted.source,
87 error: message,
88 };
89
90 return view! {
91 new_repo_form(
92 handle: profile.handle.as_str(),
93 name: "",
94 description: "",
95 visibility: Visibility::Public,
96 error: "",
97 import: &state,
98 )
99 };
100 }
101 };
102
103 let data_dir = app_context::<AppConfig>(cx).data_dir.clone();
104 let pool = pool(cx).clone();
105 let handle = profile.handle.clone();
106 let id = repo.id.clone();
107 let name = repo.name.clone();
108
109 tokio::spawn(async move {
110 if let Err(error) = run_import(
111 &id,
112 &handle,
113 &SqliteRepoRepo::new(pool),
114 &DiskGitImport::new(data_dir.clone()),
115 &DiskGitStorage::new(data_dir),
116 )
117 .await
118 {
119 // The import's own failure is recorded on the repository. Reaching here
120 // means the *recording* failed, which leaves a row stuck at `importing`
121 // until the next restart sweeps it — worth a log line, and nothing else can
122 // be done about it from in here.
123 eprintln!("steid: import of {handle}/{name} could not be recorded: {error}");
124 }
125 });
126
127 view! {
128 (StatusCode::SEE_OTHER)
129 (location(&format!("/{}/repos/{}", profile.handle, repo.name))?)
130 }
131}
132
133/// What the import block is showing.
134///
135/// Grouped rather than passed as three more parameters to
136/// [`new_repo_form`](super::repo::new_repo_form), which already carries the create
137/// form's own three: past about seven, an argument list stops being readable and starts
138/// being a place to put a value in the wrong slot.
139///
140/// Owned rather than borrowed because it is built once per render out of values with
141/// different lifetimes — a submitted form, or nothing at all.
142#[derive(Debug, Default, Clone)]
143pub(super) struct ImportBlock {
144 pub name: String,
145 pub source: String,
146 /// Empty when there is nothing to complain about.
147 pub error: String,
148}
149
150/// The second block on the new-repository page.
151///
152/// Clearly secondary: a rule above it, a quieter heading, and two fields instead of
153/// four. Creating an empty repository is what most visits are for, and an import that
154/// looked equally weighted would make the page read as a choice rather than a default
155/// with an alternative.
156///
157/// No JavaScript, so the name is not filled in from the URL as it is typed. The field
158/// may be left blank instead and the last path segment is used — which is the same
159/// answer a script would have given, arrived at on the server.
160#[component]
161pub(super) async fn import_block(handle: &str, state: &ImportBlock) -> Result {
162 let ImportBlock {
163 name,
164 source,
165 error,
166 } = state;
167 view! {
168 <section class="mt-10 border-t border-border pt-8">
169 <h2 class="text-sm font-medium">"Or import an existing repository"</h2>
170 <p class="mt-1 text-xs text-muted-foreground">
171 "Copies every branch and tag from a public "
172 <span class="font-mono">"https://"</span>
173 " repository. It runs in the background."
174 </p>
175
176 if !error.is_empty() {
177 <div class="mt-4">
178 flash(kind: FlashKind::Error, (error.as_str()))
179 </div>
180 }
181
182 <form method="post" action=(format!("/{handle}/repos/import")) class="mt-4 space-y-5">
183 <div class="space-y-2">
184 label(attrs: attributes! { for="source" }, "URL")
185 input(attrs: attributes! {
186 id="source"
187 name="source"
188 type="url"
189 value=(source.as_str())
190 placeholder="https://github.com/owner/project.git"
191 required=(true)
192 maxlength=(ImportSource::MAX_LEN.to_string())
193 })
194 <p class="text-xs text-muted-foreground">
195 "Public repositories only. Steid will not send credentials."
196 </p>
197 </div>
198
199 <div class="space-y-2">
200 label(attrs: attributes! { for="import-name" }, "Name")
201 input(attrs: attributes! {
202 id="import-name"
203 name="name"
204 type="text"
205 value=(name.as_str())
206 placeholder="taken from the URL"
207 maxlength=(RepoName::MAX_LEN.to_string())
208 })
209 <p class="text-xs text-muted-foreground">
210 "Optional. Blank uses the last part of the URL, without "
211 <span class="font-mono">".git"</span> "."
212 </p>
213 </div>
214
215 // Outline, where the create form's is solid. Two identical buttons on
216 // one page make it read as a choice between equals; the heading and the
217 // rule above say this is the alternative, and the button should agree.
218 button(
219 attrs: attributes! { type="submit" },
220 variant: ButtonVariant::Outline,
221 "Import repository"
222 )
223 </form>
224 </section>
225 }
226}
227
228/// The repository page, for a repository whose contents have not arrived.
229///
230/// Stands where the file listing would, so the page is the same page — header, tabs,
231/// sidebar — with the one part that cannot be true yet replaced. A screen of its own
232/// would mean the owner watching a URL they then have to leave.
233#[component]
234pub(super) async fn import_state_panel(repo: &RepoView, status: &ImportStatus) -> Result {
235 let source = status
236 .source
237 .as_ref()
238 .map(ImportSource::as_str)
239 .unwrap_or("its source");
240
241 view! {
242 if status.is_running() {
243 <div class="rounded-lg border border-border px-4 py-5">
244 // The sentence is one child of the flex row, not three. As siblings the
245 // icon, the words and the address become flex items, and at 800px a
246 // long URL turns the line into three ragged columns.
247 <p class="flex items-start gap-2 text-sm">
248 // The one live thing on the page, so it carries the primary colour
249 // — the same rule as the latest-commit dot.
250 icon(data: iconify_icon!("feather:download-cloud"), attrs: attributes! {
251 class="mt-0.5 size-4 shrink-0 text-primary"
252 })
253 <span class="min-w-0">
254 "Importing from "
255 // The ellipsis is inside the span so it sits against the
256 // address rather than a word-space away from it.
257 <span class="font-mono break-all">(format!("{source}…"))</span>
258 </span>
259 </p>
260 <p class="mt-2 text-xs text-muted-foreground">
261 "Every branch and tag is being copied. Refresh this page to check — "
262 "there is nothing to wait on here."
263 </p>
264 </div>
265 } else {
266 <div class="rounded-lg border border-border px-4 py-5">
267 <p class="flex items-start gap-2 text-sm">
268 icon(data: iconify_icon!("feather:alert-triangle"), attrs: attributes! {
269 class="mt-0.5 size-4 shrink-0 text-muted-foreground"
270 })
271 <span class="min-w-0">
272 "The import from "
273 <span class="font-mono break-all">(source)</span>
274 " did not finish."
275 </span>
276 </p>
277 match &status.error {
278 // git's own words. The owner supplied the address, so the reason is
279 // theirs to read — usually "repository not found" or a name that
280 // does not resolve.
281 Some(reason) => <pre class="mt-3 overflow-x-auto rounded-lg border border-border bg-surface px-4 py-3 font-mono text-xs whitespace-pre-wrap">(reason)</pre>,
282 None => "",
283 }
284 if repo.viewer_is_owner {
285 <p class="mt-4 text-xs text-muted-foreground">
286 "Nothing was kept. Delete this repository from its "
287 <a
288 href=(format!("/{}/repos/{}/settings", repo.handle, repo.name))
289 class="underline hover:text-foreground"
290 >"settings"</a>
291 " to free the name and try again."
292 </p>
293 }
294 </div>
295 }
296 }
297}
298
299/// The About sidebar, for a repository that has no contents to count.
300///
301/// The same shape as the ready one — description, a definition list, the clone address
302/// — with every number an em dash. Leaving the rows out would make the sidebar change
303/// height when the import lands; a zero would be a claim that the repository is empty.
304#[component]
305pub(super) async fn import_about(repo: &RepoView, clone: &str) -> Result {
306 view! {
307 <section class="text-sm">
308 <h2 class="text-xs font-medium uppercase tracking-wider text-muted-foreground">
309 "About"
310 </h2>
311 match &repo.description {
312 Some(description) => <p class="mt-2 leading-relaxed">(description)</p>,
313 None => <p class="mt-2 text-muted-foreground">"No description."</p>,
314 }
315 </section>
316
317 <dl class="mt-4 space-y-1.5 border-t border-border pt-4 text-xs">
318 for term in ["Commits", "Branches", "Tags", "Pushed"] {
319 <div class="flex items-baseline justify-between gap-3">
320 <dt class="text-muted-foreground">(term)</dt>
321 <dd class="font-mono text-muted-foreground">"—"</dd>
322 </div>
323 }
324 </dl>
325
326 clone_block(
327 handle: repo.handle.as_str(),
328 name: repo.name.as_str(),
329 // No revision, so no archive links: there is nothing to pack yet. Empty is
330 // exactly what an empty repository passes, and `clone_block` already treats
331 // it that way.
332 rev: "",
333 url: clone,
334 )
335 }
336}
337
338/// The whole repository page while an import is running or after it failed.
339///
340/// A component rather than a branch inside `repo_page`, so the landing page keeps one
341/// shape: resolve the repository, and if it has not arrived, render this instead of
342/// asking git five questions about an empty directory.
343#[component]
344pub(super) async fn importing_page(cx: &Cx, repo: &RepoView, status: &ImportStatus) -> Result {
345 let clone = clone_url_for(cx, repo);
346
347 view! {
348 repo_header(repo: repo, rev: "", active: Tab::Code)
349
350 <div class="flex flex-col lg:flex-row lg:items-start lg:gap-6">
351 <div class="min-w-0 lg:flex-1">
352 import_state_panel(repo: repo, status: status)
353 </div>
354 <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">
355 import_about(repo: repo, clone: clone.as_str())
356 </aside>
357 </div>
358 }
359}