Skip to content

Where people and agents ship software together. The open-source git platform for the whole job: issues, agents, checks and deploys to the edge.

363 linesCodeBlameRaw
1import { ArrowLeft, Lock, Plus } from "lucide-react";
2import { Form, Link, redirect } from "react-router";
3
4import type { Route } from "./+types/new-github";
5import { GithubMark } from "../components/github";
6import { ButtonLink, ErrorText, SubmitButton } from "../components/ui";
7import { Badge } from "../components/ui/badge";
8import { Card } from "../components/ui/card";
9import { CheckboxOption } from "../components/ui/checkbox";
10import { FieldLegend, FieldSet } from "../components/ui/field";
11import { installationSummary, notYetAdded } from "../lib/github";
12import { githubApp } from "../lib/github.server";
13import { page } from "../lib/meta";
14import { assertSameOrigin, requireUser, roleIn } from "../lib/session.server";
15import { currentWorkspace } from "../lib/current-workspace.server";
16import { Unavailable } from "../components/boundary";
17import { isFailed, part } from "../lib/partial";
18
19export function meta(args: Route.MetaArgs) {
20 return page(args, { title: "Import from GitHub · g1t" });
21}
22
23export async function loader({ request, context }: Route.LoaderArgs) {
24 const user = requireUser(context, request);
25 const url = new URL(request.url);
26 const current = currentWorkspace(user, request);
27 if (!current) throw redirect("/workspaces/new");
28 const workspace = current.slug;
29 const workspaceName = current.name?.trim() || current.slug;
30 // What the person can see on GitHub is asked for alongside the status:
31 // an installation made there directly is offered here to be added.
32 const [status, visible] = await Promise.all([
33 githubApp.status(user, workspace),
34 part(githubApp.visibleInstallations(user), "Accounts the app is already installed on"),
35 ]);
36 if (!status.ok || !status.value.configured) throw redirect("/new");
37 const { installations, linked } = status.value;
38 const recorded = new Set(installations.map((item) => item.id));
39 const claimable =
40 linked && !isFailed(visible) && visible.ok
41 ? notYetAdded(visible.value, workspace)
42 .filter((item) => !recorded.has(item.id))
43 .map((item) => ({ ...item, summary: installationSummary(item) }))
44 : [];
45 const wanted = Number(url.searchParams.get("installation"));
46 const installation = installations.find((item) => item.id === wanted) ?? installations[0] ?? null;
47 const pageNumber = Math.max(1, Number(url.searchParams.get("page")) || 1);
48 let repositories = null;
49 let error: string | null = null;
50 if (linked && installation) {
51 const listed = await githubApp.repositories(user, workspace, installation.id, pageNumber);
52 if (listed.ok) repositories = listed.value;
53 else error = listed.error.message;
54 }
55 return {
56 workspace,
57 workspaceName,
58 owner: roleIn(user, workspace) === "owner",
59 linked,
60 installations,
61 claimable,
62 // Not asked is not "none": the page says so where they would be offered.
63 claimableUnknown: linked && isFailed(visible),
64 installation,
65 repositories,
66 error,
67 requested: url.searchParams.get("requested") === "1",
68 };
69}
70
71export async function action({ request, context }: Route.ActionArgs) {
72 assertSameOrigin(request);
73 const user = requireUser(context, request);
74 const form = await request.formData();
75 const workspace = String(form.get("workspace") ?? "");
76 const installationId = Number(form.get("installation"));
77 if (form.get("intent") === "add-installation") {
78 const added = await githubApp.addInstallation(user, workspace, installationId);
79 if (!added.ok) return { error: null, addError: added.error.message, results: [] };
80 throw redirect(`/new/github?installation=${installationId}`);
81 }
82 if (form.get("intent") === "remove-installation") {
83 const removed = await githubApp.removeInstallation(user, workspace, installationId);
84 // Shown by the list it was removed from, which is there with or without an account chosen.
85 if (!removed.ok) return { error: null, removeError: removed.error.message, results: [] };
86 throw redirect("/new/github");
87 }
88 const chosen = form.getAll("repo").map(Number).filter((id) => Number.isSafeInteger(id) && id > 0).slice(0, 20);
89 if (chosen.length === 0) return { error: "Choose at least one repository.", results: [] };
90 const issues = form.get("issues") === "on";
91 // One at a time: each is a copy of a whole repository.
92 const results: { id: number; ok: boolean; repo?: string; error?: string }[] = [];
93 for (const githubRepoId of chosen) {
94 const imported = await githubApp.import(user, workspace, { installationId, githubRepoId, issues });
95 results.push(
96 imported.ok
97 ? { id: githubRepoId, ok: true, repo: imported.value.repo }
98 : { id: githubRepoId, ok: false, error: imported.error.message },
99 );
100 }
101 if (results.length === 1 && results[0].ok) throw redirect(`/${results[0].repo}`);
102 return { error: null, results };
103}
104
105export default function NewFromGithub({ loaderData, actionData }: Route.ComponentProps) {
106 const { workspace, workspaceName, installations, claimable, installation, repositories, linked, owner } = loaderData;
107 const these = claimable.length === 1 ? "this account" : "these accounts";
108 const here = "/new/github";
109 const names = new Map((repositories?.repositories ?? []).map((repo) => [repo.id, repo.fullName]));
110 return (
111 <main className="mx-auto max-w-2xl px-4 py-12">
112 <Link to="/new" className="inline-flex items-center gap-1.5 text-sm text-muted hover:text-fg">
113 <ArrowLeft size={14} /> New project
114 </Link>
115 <span className="mt-6 flex size-10 items-center justify-center rounded-xl bg-accent/10 text-accent ring-1 ring-accent/30">
116 <GithubMark className="size-4.5" />
117 </span>
118 <h1 className="mt-4 text-2xl font-semibold tracking-tight">Import from GitHub</h1>
119 <p className="mt-1.5 text-sm text-muted">
120 Bring repositories into <span className="font-mono text-fg">{workspace}</span> through g1t's GitHub App. You choose
121 which repositories it can see on GitHub; nothing else is read.
122 </p>
123
124
125 {!linked ? (
126 <Card asChild tone="plain" radius="lg" className="mt-8 p-6">
127 <section>
128 <h2 className="font-medium">Connect GitHub</h2>
129 <p className="mt-1.5 text-sm text-muted">
130 {owner
131 ? `GitHub asks once who you are and which repositories g1t may see, then brings you back here to choose what to import into ${workspaceName}.`
132 : "g1t lists the repositories you can reach on GitHub as you, so it needs your GitHub account linked first."}
133 </p>
134 <div className="mt-4">
135 <a
136 href={owner ? `/integrations/github/install?workspace=${workspace}` : `/auth/github?link=1&next=${encodeURIComponent(here)}`}
137 className="inline-flex items-center gap-2 rounded-md bg-fg px-3.5 py-2 text-sm font-medium text-bg hover:bg-fg-hover"
138 >
139 <GithubMark /> Connect GitHub
140 </a>
141 </div>
142 </section>
143 </Card>
144 ) : (
145 <>
146 <section className="mt-8">
147 <div className="flex items-center justify-between gap-4">
148 <h2 className="font-medium">GitHub accounts</h2>
149 {owner && (
150 <a
151 href={`/integrations/github/install?workspace=${workspace}&another=1`}
152 className="inline-flex items-center gap-1.5 text-sm text-muted hover:text-fg"
153 >
154 <Plus size={14} /> Add a GitHub account
155 </a>
156 )}
157 </div>
158 {loaderData.requested && (
159 <p className="mt-3 text-sm text-muted">
160 Your request went to the organization's owners on GitHub. Once one approves it, add the account here again.
161 </p>
162 )}
163 {loaderData.claimableUnknown && (
164 <div className="mt-3">
165 <Unavailable what="Accounts the app is already installed on" compact />
166 </div>
167 )}
168 {claimable.length > 0 && (
169 <div className="mt-3 rounded-lg border border-accent/30 bg-accent/5 p-4">
170 <h3 className="text-sm font-medium">Already installed on GitHub</h3>
171 <p className="mt-1 text-sm text-muted">
172 {owner
173 ? `The app is installed on ${these}, but not added to ${workspaceName} yet.`
174 : `The app is installed on ${these}. An owner of ${workspaceName} can add ${claimable.length === 1 ? "it" : "them"} here.`}
175 </p>
176 <ul className="mt-3 divide-y divide-line rounded-md border border-line bg-bg">
177 {claimable.map((item) => (
178 <li key={item.id} className="flex flex-wrap items-center gap-x-3 gap-y-2 px-4 py-2.5 text-sm">
179 <GithubMark className="size-4 shrink-0 text-muted" />
180 <span className="font-mono">{item.account}</span>
181 <span className="whitespace-nowrap text-xs text-faint">{item.summary}</span>
182 {item.suspended && <Badge size="md">Suspended</Badge>}
183 {owner && (
184 <Form method="post" className="ml-auto">
185 <input type="hidden" name="intent" value="add-installation" />
186 <input type="hidden" name="workspace" value={workspace} />
187 <input type="hidden" name="installation" value={item.id} />
188 <SubmitButton
189 pending="Adding…"
190 match={{ intent: "add-installation", installation: String(item.id) }}
191 >
192 Add to {workspaceName}
193 </SubmitButton>
194 </Form>
195 )}
196 </li>
197 ))}
198 </ul>
199 <ErrorText>{actionData && "addError" in actionData ? actionData.addError : null}</ErrorText>
200 </div>
201 )}
202 {installations.length === 0 ? (
203 <Card tone="plain" radius="lg" className="mt-3 border-dashed p-6 text-sm text-muted">
204 {owner ? (
205 <>
206 <p>
207 {claimable.length > 0
208 ? "Or install g1t's GitHub App on another GitHub account or organization, and choose the repositories it may see."
209 : "Install g1t's GitHub App on your GitHub account or an organization, and choose the repositories it may see."}
210 </p>
211 <div className="mt-4">
212 <a
213 href={`/integrations/github/install?workspace=${workspace}${claimable.length > 0 ? "&another=1" : ""}`}
214 className="inline-flex items-center gap-2 rounded-md bg-fg px-3.5 py-2 text-sm font-medium text-bg hover:bg-fg-hover"
215 >
216 <GithubMark /> Install on GitHub
217 </a>
218 </div>
219 </>
220 ) : (
221 <p>No GitHub account is connected to this workspace yet. Ask one of its owners to add one.</p>
222 )}
223 </Card>
224 ) : (
225 <ul className="mt-3 divide-y divide-line rounded-md border border-line">
226 {installations.map((item) => (
227 <li key={item.id} className="flex flex-wrap items-center gap-x-3 gap-y-1 px-4 py-2.5 text-sm">
228 <Link
229 to={`${here}?installation=${item.id}`}
230 className={`whitespace-nowrap ${item.id === installation?.id ? "font-medium text-fg" : "text-muted hover:text-fg"}`}
231 >
232 {item.account}
233 </Link>
234 <span className="whitespace-nowrap text-xs text-faint">
235 {item.accountType === "Organization" ? "Organization" : "Personal"} ·{" "}
236 {item.repositorySelection === "all" ? "all repositories" : "selected repositories"}
237 </span>
238 {item.suspended && <Badge size="md">Suspended</Badge>}
239 <span className="ml-auto flex items-center gap-3">
240 <a href={item.settingsUrl} className="whitespace-nowrap text-xs text-muted hover:text-fg">
241 Choose repositories on GitHub
242 </a>
243 {owner && (
244 <Form method="post">
245 <input type="hidden" name="intent" value="remove-installation" />
246 <input type="hidden" name="workspace" value={workspace} />
247 <input type="hidden" name="installation" value={item.id} />
248 <SubmitButton
249 pending="Removing…"
250 match={{ intent: "remove-installation", installation: String(item.id) }}
251 variant="link"
252 size="inline"
253 className="gap-1 text-xs text-faint hover:text-danger"
254 >
255 Remove
256 </SubmitButton>
257 </Form>
258 )}
259 </span>
260 </li>
261 ))}
262 </ul>
263 )}
264 <ErrorText>{actionData && "removeError" in actionData ? actionData.removeError : null}</ErrorText>
265 </section>
266
267 {installation && (
268 <Form method="post" className="mt-10 space-y-8">
269 <input type="hidden" name="intent" value="import" />
270 <input type="hidden" name="workspace" value={workspace} />
271 <input type="hidden" name="installation" value={installation.id} />
272 <FieldSet>
273 <FieldLegend>Repositories on {installation.account}</FieldLegend>
274 <ErrorText>{loaderData.error}</ErrorText>
275 {repositories && repositories.repositories.length === 0 && (
276 <p className="text-sm text-muted">
277 The app cannot see any repositories here yet.{" "}
278 <a href={installation.settingsUrl} className="text-fg underline underline-offset-4">
279 Choose some on GitHub
280 </a>
281 .
282 </p>
283 )}
284 <div className="divide-y divide-line rounded-md border border-line empty:hidden">
285 {(repositories?.repositories ?? []).map((repo) => (
286 <div key={repo.id} className="px-4 py-3">
287 <CheckboxOption
288 name="repo"
289 value={String(repo.id)}
290 disabled={repo.linkedTo != null}
291 label={
292 <span className="flex flex-wrap items-center gap-2">
293 <span className="font-mono">{repo.fullName}</span>
294 {repo.private && (
295 <span className="inline-flex items-center gap-1 text-xs text-faint">
296 <Lock size={11} /> Private
297 </span>
298 )}
299 {repo.linkedTo && <Badge size="md">On g1t as {repo.linkedTo}</Badge>}
300 </span>
301 }
302 description={repo.description ?? undefined}
303 />
304 </div>
305 ))}
306 </div>
307 {repositories && repositories.total > repositories.perPage && (
308 <div className="flex justify-between text-sm">
309 {repositories.page > 1 ? (
310 <Link to={`${here}?installation=${installation.id}&page=${repositories.page - 1}`} className="text-muted hover:text-fg">
311 Previous
312 </Link>
313 ) : (
314 <span />
315 )}
316 {repositories.page * repositories.perPage < repositories.total && (
317 <Link to={`${here}?installation=${installation.id}&page=${repositories.page + 1}`} className="text-muted hover:text-fg">
318 Next
319 </Link>
320 )}
321 </div>
322 )}
323 </FieldSet>
324
325 <CheckboxOption
326 name="issues"
327 defaultChecked
328 label="Copy issues too"
329 description="Up to 200 per repository, with their labels and whether they are open; a milestone is noted in the description. Pull requests stay on GitHub; their branches come across."
330 />
331
332 {actionData?.results && actionData.results.length > 0 && (
333 <ul className="space-y-1 rounded-md border border-line p-4 text-sm">
334 {actionData.results.map((result) => (
335 <li key={result.id}>
336 <span className="font-mono">{names.get(result.id) ?? result.id}</span>:{" "}
337 {result.ok ? (
338 <Link to={`/${result.repo}`} className="text-accent underline underline-offset-4">
339 {result.repo}
340 </Link>
341 ) : (
342 <span className="text-danger">{result.error}</span>
343 )}
344 </li>
345 ))}
346 </ul>
347 )}
348 <ErrorText>{actionData?.error}</ErrorText>
349 <div className="flex items-center gap-3">
350 <SubmitButton variant="accent" pending="Bringing them across…" match={{ intent: "import" }}>
351 Bring to g1t
352 </SubmitButton>
353 <ButtonLink to="/new" variant="outline">
354 Cancel
355 </ButtonLink>
356 </div>
357 </Form>
358 )}
359 </>
360 )}
361 </main>
362 );
363}