Public: anyone can read this; the crew can change it.

/migrate's first field is the repository URL, and with no account connected the page is that field and Connect GitHub #6415

Closed opened this
Closed without merging

scout/forge:scout/6406-migrate-s-first-field-is-the-repository → main 4 commits fork 1 thread · 1 unresolved

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
5 files changed +199 −22
docs/ORIGINS.md +2
@@ -640,6 +640,8 @@ rights on GitHub: without them the migration still succeeds and says the
640640 repository was not archived, so you can do it there yourself. Only repositories
641641 read through a connected origin have an original to change; a pasted URL does not.
642642
643 **Migrate on the web.** `/migrate` opens on one field, "Paste a repository URL (GitHub, GitLab, any git URL)"; Enter migrates it, and the line under it names the host and `owner/name` the URL points at as you type (one pattern, `URL_TARGET` in `src/web/pages/migrate.ts`, serves the server and the page script). With no account connected the page is that field and Connect GitHub; with one, your repositories are listed below it. No dependency added.
644
643645 **Migrate from the terminal.** Press `M` on the dashboard (or pick "Migrate a
644646 repository" in the palette, `ctrl+k`). The list is your connected origins'
645647 repositories, private ones marked; `/` filters it and `u` pastes a URL instead.
docs/design/areas/forms.md +1
@@ -4,3 +4,4 @@ A form's fields and its buttons sit in two rows, one for what you fill in and on
44
55 - `.field-row` — a row of `.field`s side by side that wraps on a narrow screen, each at least 160px wide and aligned to the bottom so a labelled input and the button beside it share a baseline. Styled in `style/components.ts`; written by `createForm` in `pages/branches.ts` (the new-branch form), the graph filter in `pages/fleet-graph.ts`, the freeze form in `pages/frozen.ts` and the new-pull form in `pages/pulls.ts`.
66 - `.form-actions` — the row of a form's buttons under its fields: 16px above, 8px apart, wrapping. Styled in `style/components.ts`, and in `style/content.ts` for a thread's close reason and "close into" input and for `.comment-form` on a narrow screen; written by nearly every form in `src/web/pages/` (`account.ts`, `settings.ts`, `crew.ts`, `edit.ts`, `issues.ts`, `pulls.ts`, `oauth.ts`, `teams.ts`, `chain.ts`, `everyday.ts`) and by the review comment form in `diff-view.ts`; `client.ts` finds its `.muted` note to report a save.
7 - `.input-lg` — a text input that is the page's one first act: 48px tall, 16px type. Styled in `style/components.ts`; written by the repository URL field on `/migrate` (`pages/migrate.ts`), which is the first input in `<main>` and joins the migrate form by its `form` attribute.
src/web/pages/migrate.ts +62 −22
@@ -266,10 +266,12 @@ function accounts(ctx: Ctx, origins: readonly OriginChoices[]): Html {
266266 )}
267267 </ul>`}
268268 ${connect}`,
269 {
270 head: html`${icon("globe")}
271 <h2>Your accounts</h2>`,
272 },
269 origins.length === 0
270 ? {}
271 : {
272 head: html`${icon("globe")}
273 <h2>Your accounts</h2>`,
274 },
273275 );
274276 }
275277
@@ -284,13 +286,14 @@ function picker(
284286 values: MigrateValues,
285287 withCrew: boolean,
286288 branches: BranchChoices | undefined,
287 ): Html {
289 ): Html | null {
288290 const listed = origins.filter((o) => o.repos.length > 0);
291 if (origins.length === 0) return null;
289292 if (listed.length === 0)
290293 return html`<p class="muted small mb">
291 ${icon("globe")} Connect an account above — or another forge under
292 <a href="/settings/origins">Settings → Origins</a> — to pick from your
293 repositories there, private ones included.
294 ${icon("globe")} None of your accounts lists a repository — connect
295 another forge under <a href="/settings/origins">Settings → Origins</a> to
296 pick from its repositories, private ones included.
294297 </p>`;
295298 return html`<div class="field" id="migrate-picker">
296299 <label for="f-q">Your repositories</label>
@@ -363,6 +366,45 @@ function parsePick(value: string): MigrateSource | undefined {
363366 return { originId: value.slice(0, slash), fullName: value.slice(slash + 1) };
364367 }
365368
369 /** The one pattern for a pasted URL's host and owner/name; the page script embeds its source. */
370 const URL_TARGET =
371 /^[A-Za-z][A-Za-z0-9+.-]*:\/\/(?:[^@/]*@)?([^/:?#]+)(?::[0-9]+)?\/([^/?#]+)\/([^/?#]+?)(?:\.git)?\/?(?:[?#].*)?$/;
372
373 /** Host and `owner/name` a pasted URL points at; undefined when it names neither. */
374 export function urlTarget(raw: string): { host: string; repo: string } | undefined {
375 const m = URL_TARGET.exec(raw.trim());
376 return m ? { host: m[1]!, repo: `${m[2]}/${m[3]}` } : undefined;
377 }
378
379 const URL_SAYS = "Names the host and owner/name it points at.";
380
outdated

This regex is duplicated in migrateJs (about line 586). Ship one source, for example embed urlTarget's pattern source into the script, so the server and client lines cannot disagree.

381 /**
382 * The first field on the page: a pasted URL, large, in the migrate form by
383 * its `form` attribute (the accounts card sits between and forms do not nest).
384 */
385 function urlField(value: string): Html {
386 const target = urlTarget(value);
387 return html`<div class="field">
388 <label for="f-url">Paste a repository URL (GitHub, GitLab, any git URL)</label>
389 <input
390 class="input input-lg mono"
391 type="text"
392 id="f-url"
393 name="url"
394 form="migrate-form"
395 value="${value}"
396 placeholder="https://github.com/owner/name"
397 autocomplete="off"
398 spellcheck="false"
399 autofocus
400 aria-describedby="f-url-says"
401 />
402 <span class="hint" id="f-url-says" aria-live="polite"
403 >${target ? `${target.host} — ${target.repo}` : URL_SAYS}</span
404 >
405 </div>`;
406 }
407
366408 function migrateForm(
367409 ctx: Ctx,
368410 values: MigrateValues,
@@ -395,24 +437,14 @@ function migrateForm(
395437 ${icon("globe")} Ignored, nothing here matches:
396438 ${unmatched.join(", ")}
397439 </p>`}
440 ${urlField(values.url)}
398441 ${accounts(ctx, origins)}
399442 <form method="get" action="/migrate" id="migrate-search"></form>
400443 ${card(
401 html`<form method="post" action="/migrate">
402 <h3 class="mb">Source</h3>
444 html`<form method="post" action="/migrate" id="migrate-form">
445 <button type="submit" hidden tabindex="-1" aria-hidden="true"></button>
446 ${origins.length === 0 ? null : html`<h3 class="mb">Source</h3>`}
403447 ${picker(origins, values, crew.length > 0, branches)}
404 ${formField({
405 label: origins.every((o) => o.repos.length === 0)
406 ? "Repository URL"
407 : "Or a URL",
408 name: "url",
409 value: values.url,
410 placeholder: "https://github.com/owner/name",
411 autocomplete: "off",
412 mono: true,
413 autofocus: origins.every((o) => o.repos.length === 0),
414 hint: "Any public repository over https, http or git. It is cloned anonymously.",
415 })}
416448 <h3 class="mb mt">Destination</h3>
417449 ${selectField({
418450 label: "Owner",
@@ -549,6 +581,14 @@ const migrateJs = /* js */ `
549581 name.value = url ? fromUrl(url.value) : '';
550582 }
551583 if (url) url.addEventListener('input', follow);
584 var says = document.getElementById('f-url-says');
585 if (url && says) {
586 var idle = says.textContent;
587 url.addEventListener('input', function () {
588 var m = new RegExp(${JSON.stringify(URL_TARGET.source)}).exec(url.value.trim());
589 says.textContent = m ? m[1] + ' — ' + m[2] + '/' + m[3] : idle;
590 });
591 }
552592 })();
553593 `;
554594
src/web/style/components.ts +1
@@ -90,6 +90,7 @@ export const components = /* css */ `
9090 box-shadow: 0 0 0 3px color-mix(in srgb, var(--danger) 14%, transparent);
9191 }
9292 .input[readonly] { background: var(--muted); color: var(--muted-fg); }
93 .input-lg { min-height: 48px; padding: 10px 14px; font-size: 16px; }
9394 .input[data-size="sm"] { min-height: 28px; padding: 4px 8px; font-size: 13px; }
9495 textarea.input {
9596 resize: vertical; min-height: 88px; line-height: 1.55; font-family: inherit;
test/migrate-layout.test.ts added +133
@@ -0,0 +1,133 @@
1 /**
2 * /migrate leads with the repository URL field: first input in <main>, with
3 * or without a connected origin, and no empty picker when none is connected.
4 */
5 import { afterAll, beforeAll, expect, test } from "bun:test";
6 import { mkdtemp, rm } from "node:fs/promises";
7 import { tmpdir } from "node:os";
8 import { join } from "node:path";
9 import { createApp, type App } from "../src/app.ts";
10 import { serve, type Servers } from "../src/http/server.ts";
11 import { urlTarget } from "../src/web/pages/migrate.ts";
12 import { forgetProviders } from "../src/origins/providers/index.ts";
13 import { newFakeState, serveFakeForge } from "./fake-origin.ts";
14 import { adminCookie } from "./helpers/admin.ts";
15 import { quietLogs } from "./helpers/globals.ts";
16
17 quietLogs();
18
19 let dataDir: string;
20 let app: App;
21 let servers: Servers;
22 let cookie: string;
23
24 beforeAll(async () => {
25 dataDir = await mkdtemp(join(tmpdir(), "forge-migrate-layout-"));
26 app = createApp({ dataDir, port: 0, host: "forge.test" });
27 servers = await serve(app);
28 cookie = await adminCookie(app, { username: "olive", email: "[email protected]", password: "a-good-passphrase" });
29 });
30
31 afterAll(async () => {
32 await servers.stop();
33 await rm(dataDir, { recursive: true, force: true });
34 });
35
36 const get = async (path: string) =>
37 (await fetch(`${servers.url}${path}`, { headers: { cookie }, redirect: "manual" })).text();
38
39 const firstInput = (html: string): string => {
40 const main = html.slice(html.indexOf("<main"));
41 return /<input\b[^>]*>/.exec(main)?.[0] ?? "";
42 };
43
44 test("with no account connected the URL field leads, and no picker or empty accounts card is drawn", async () => {
45 const html = await get("/migrate");
46 const first = firstInput(html);
47 expect(first).toContain('name="url"');
48 expect(html).toContain("Paste a repository URL (GitHub, GitLab, any git URL)");
49 expect(html).not.toMatch(/<ul[^>]*data-pick-rows/);
50 expect(html).not.toContain("Your accounts");
51 expect(html).not.toContain("migrate-picker");
52 });
53
54 test("the line under the field names host and owner/name after a refused submit", async () => {
55 const html = await get("/migrate?url=" + encodeURIComponent("https://gitlab.com/acme/widgets.git"));
56 expect(html).toMatch(/id="f-url-says"[^>]*>\s*gitlab\.com — acme\/widgets/);
57 expect(html).toContain("f-url-says");
58 });
59
60 test("with an origin connected the URL field still leads", async () => {
61 const { connectOrigin } = await import("../src/actions/origins.ts");
62 const { getUserByName } = await import("../src/core/users.ts");
63 const user = getUserByName(app.db, "olive")!;
64 const state = newFakeState("github", "octo", "layout-secret");
65 state.repos.push({
66 id: 501,
67 fullName: "octo/gadgets",
68 description: "small machines",
69 cloneUrl: "http://127.0.0.1/octo/gadgets.git",
70 htmlUrl: "https://github.com/octo/gadgets",
71 defaultBranch: "main",
72 private: false,
73 sizeKb: 10,
74 });
75 const fake = serveFakeForge(state);
76 forgetProviders(dataDir);
77 try {
78 const made = await connectOrigin(app, user, { host: fake.url, kind: "github", token: "layout-secret" });
79 if (!made.ok) throw new Error(String(made.error));
80 const html = await get("/migrate");
81 expect(html).toMatch(/<ul[^>]*data-pick-rows/);
82 expect(firstInput(html)).toContain('name="url"');
83 } finally {
84 fake.stop();
85 }
86 });
87
88 test("urlTarget reads host and owner/name, and nothing from a bare word", () => {
89 expect(urlTarget("https://github.com/o/n")).toEqual({ host: "github.com", repo: "o/n" });
90 expect(urlTarget("https://[email protected]:8443/o/n.git/")).toEqual({ host: "host.example", repo: "o/n" });
91 expect(urlTarget("nonsense")).toBeUndefined();
92 });
93
94 test("the typing-time line runs the server's pattern: the script updates the line as the URL changes", async () => {
95 const html = await get("/migrate");
96 const script = [...html.matchAll(/<script\b[^>]*>([\s\S]*?)<\/script>/g)]
97 .map((m) => m[1]!)
98 .find((s) => s.includes("f-url-says"));
99 expect(script).toBeDefined();
100 const els: Record<string, { value: string; textContent: string; listeners: Record<string, () => void>; addEventListener(t: string, f: () => void): void }> = {};
101 const el = (value: string, textContent: string) => ({
102 value,
103 textContent,
104 listeners: {} as Record<string, () => void>,
105 addEventListener(t: string, f: () => void) {
106 this.listeners[t] = f;
107 },
108 });
109 els["f-name"] = el("", "");
110 els["f-url"] = el("", "");
111 els["f-url-says"] = el("", "idle");
112 new Function("document", script!)({
113 addEventListener: (_t: string, f: () => void) => f(),
114 getElementById: (id: string) => els[id] ?? null,
115 querySelectorAll: () => [],
116 });
117 const url = els["f-url"]!;
118 const says = els["f-url-says"]!;
119 for (const raw of ["https://github.com/o/n", "https://[email protected]:8443/o/n.git/", "nonsense"]) {
120 url.value = raw;
121 url.listeners.input!();
122 const t = urlTarget(raw);
123 expect(says.textContent).toBe(t ? `${t.host} — ${t.repo}` : "idle");
124 }
125 });
126
127 test("Enter in the URL field cannot press a picker row: the form's first submit button is the plain one", async () => {
128 const html = await get("/migrate");
129 const form = html.slice(html.indexOf('id="migrate-form"'));
130 const first = /<button\b[^>]*type="submit"[^>]*>/.exec(form)?.[0] ?? "";
131 expect(first).toContain("hidden");
132 expect(first).not.toContain('name="pick"');
133 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs