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.

359 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
89 .getAll("repo")
90 .map(Number)
91 .filter((id) => Number.isSafeInteger(id) && id > 0)
92 .slice(0, 20);
93 if (chosen.length === 0) return { error: "Choose at least one repository.", results: [] };
94 const issues = form.get("issues") === "on";
95 // One at a time: each is a copy of a whole repository.
96 const results: { id: number; ok: boolean; repo?: string; error?: string }[] = [];
97 for (const githubRepoId of chosen) {
98 const imported = await githubApp.import(user, workspace, { installationId, githubRepoId, issues });
99 results.push(imported.ok ? { id: githubRepoId, ok: true, repo: imported.value.repo } : { id: githubRepoId, ok: false, error: imported.error.message });
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 which repositories it can see on
121 GitHub; nothing else is read.
122 </p>
123
124 {!linked ? (
125 <Card asChild tone="plain" radius="lg" className="mt-8 p-6">
126 <section>
127 <h2 className="font-medium">Connect GitHub</h2>
128 <p className="mt-1.5 text-sm text-muted">
129 {owner
130 ? `GitHub asks once who you are and which repositories g1t may see, then brings you back here to choose what to import into ${workspaceName}.`
131 : "g1t lists the repositories you can reach on GitHub as you, so it needs your GitHub account linked first."}
132 </p>
133 <div className="mt-4">
134 <a
135 href={owner ? `/integrations/github/install?workspace=${workspace}` : `/auth/github?link=1&next=${encodeURIComponent(here)}`}
136 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"
137 >
138 <GithubMark /> Connect GitHub
139 </a>
140 </div>
141 </section>
142 </Card>
143 ) : (
144 <>
145 <section className="mt-8">
146 <div className="flex items-center justify-between gap-4">
147 <h2 className="font-medium">GitHub accounts</h2>
148 {owner && (
149 <a
150 href={`/integrations/github/install?workspace=${workspace}&another=1`}
151 className="inline-flex items-center gap-1.5 text-sm text-muted hover:text-fg"
152 >
153 <Plus size={14} /> Add a GitHub account
154 </a>
155 )}
156 </div>
157 {loaderData.requested && (
158 <p className="mt-3 text-sm text-muted">
159 Your request went to the organization's owners on GitHub. Once one approves it, add the account here again.
160 </p>
161 )}
162 {loaderData.claimableUnknown && (
163 <div className="mt-3">
164 <Unavailable what="Accounts the app is already installed on" compact />
165 </div>
166 )}
167 {claimable.length > 0 && (
168 <div className="mt-3 rounded-lg border border-accent/30 bg-accent/5 p-4">
169 <h3 className="text-sm font-medium">Already installed on GitHub</h3>
170 <p className="mt-1 text-sm text-muted">
171 {owner
172 ? `The app is installed on ${these}, but not added to ${workspaceName} yet.`
173 : `The app is installed on ${these}. An owner of ${workspaceName} can add ${claimable.length === 1 ? "it" : "them"} here.`}
174 </p>
175 <ul className="mt-3 divide-y divide-line rounded-md border border-line bg-bg">
176 {claimable.map((item) => (
177 <li key={item.id} className="flex flex-wrap items-center gap-x-3 gap-y-2 px-4 py-2.5 text-sm">
178 <GithubMark className="size-4 shrink-0 text-muted" />
179 <span className="font-mono">{item.account}</span>
180 <span className="whitespace-nowrap text-xs text-faint">{item.summary}</span>
181 {item.suspended && <Badge size="md">Suspended</Badge>}
182 {owner && (
183 <Form method="post" className="ml-auto">
184 <input type="hidden" name="intent" value="add-installation" />
185 <input type="hidden" name="workspace" value={workspace} />
186 <input type="hidden" name="installation" value={item.id} />
187 <SubmitButton pending="Adding…" match={{ intent: "add-installation", installation: String(item.id) }}>
188 Add to {workspaceName}
189 </SubmitButton>
190 </Form>
191 )}
192 </li>
193 ))}
194 </ul>
195 <ErrorText>{actionData && "addError" in actionData ? actionData.addError : null}</ErrorText>
196 </div>
197 )}
198 {installations.length === 0 ? (
199 <Card tone="plain" radius="lg" className="mt-3 border-dashed p-6 text-sm text-muted">
200 {owner ? (
201 <>
202 <p>
203 {claimable.length > 0
204 ? "Or install g1t's GitHub App on another GitHub account or organization, and choose the repositories it may see."
205 : "Install g1t's GitHub App on your GitHub account or an organization, and choose the repositories it may see."}
206 </p>
207 <div className="mt-4">
208 <a
209 href={`/integrations/github/install?workspace=${workspace}${claimable.length > 0 ? "&another=1" : ""}`}
210 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"
211 >
212 <GithubMark /> Install on GitHub
213 </a>
214 </div>
215 </>
216 ) : (
217 <p>No GitHub account is connected to this workspace yet. Ask one of its owners to add one.</p>
218 )}
219 </Card>
220 ) : (
221 <ul className="mt-3 divide-y divide-line rounded-md border border-line">
222 {installations.map((item) => (
223 <li key={item.id} className="flex flex-wrap items-center gap-x-3 gap-y-1 px-4 py-2.5 text-sm">
224 <Link
225 to={`${here}?installation=${item.id}`}
226 className={`whitespace-nowrap ${item.id === installation?.id ? "font-medium text-fg" : "text-muted hover:text-fg"}`}
227 >
228 {item.account}
229 </Link>
230 <span className="whitespace-nowrap text-xs text-faint">
231 {item.accountType === "Organization" ? "Organization" : "Personal"} ·{" "}
232 {item.repositorySelection === "all" ? "all repositories" : "selected repositories"}
233 </span>
234 {item.suspended && <Badge size="md">Suspended</Badge>}
235 <span className="ml-auto flex items-center gap-3">
236 <a href={item.settingsUrl} className="whitespace-nowrap text-xs text-muted hover:text-fg">
237 Choose repositories on GitHub
238 </a>
239 {owner && (
240 <Form method="post">
241 <input type="hidden" name="intent" value="remove-installation" />
242 <input type="hidden" name="workspace" value={workspace} />
243 <input type="hidden" name="installation" value={item.id} />
244 <SubmitButton
245 pending="Removing…"
246 match={{ intent: "remove-installation", installation: String(item.id) }}
247 variant="link"
248 size="inline"
249 className="gap-1 text-xs text-faint hover:text-danger"
250 >
251 Remove
252 </SubmitButton>
253 </Form>
254 )}
255 </span>
256 </li>
257 ))}
258 </ul>
259 )}
260 <ErrorText>{actionData && "removeError" in actionData ? actionData.removeError : null}</ErrorText>
261 </section>
262
263 {installation && (
264 <Form method="post" className="mt-10 space-y-8">
265 <input type="hidden" name="intent" value="import" />
266 <input type="hidden" name="workspace" value={workspace} />
267 <input type="hidden" name="installation" value={installation.id} />
268 <FieldSet>
269 <FieldLegend>Repositories on {installation.account}</FieldLegend>
270 <ErrorText>{loaderData.error}</ErrorText>
271 {repositories && repositories.repositories.length === 0 && (
272 <p className="text-sm text-muted">
273 The app cannot see any repositories here yet.{" "}
274 <a href={installation.settingsUrl} className="text-fg underline underline-offset-4">
275 Choose some on GitHub
276 </a>
277 .
278 </p>
279 )}
280 <div className="divide-y divide-line rounded-md border border-line empty:hidden">
281 {(repositories?.repositories ?? []).map((repo) => (
282 <div key={repo.id} className="px-4 py-3">
283 <CheckboxOption
284 name="repo"
285 value={String(repo.id)}
286 disabled={repo.linkedTo != null}
287 label={
288 <span className="flex flex-wrap items-center gap-2">
289 <span className="font-mono">{repo.fullName}</span>
290 {repo.private && (
291 <span className="inline-flex items-center gap-1 text-xs text-faint">
292 <Lock size={11} /> Private
293 </span>
294 )}
295 {repo.linkedTo && <Badge size="md">On g1t as {repo.linkedTo}</Badge>}
296 </span>
297 }
298 description={repo.description ?? undefined}
299 />
300 </div>
301 ))}
302 </div>
303 {repositories && repositories.total > repositories.perPage && (
304 <div className="flex justify-between text-sm">
305 {repositories.page > 1 ? (
306 <Link to={`${here}?installation=${installation.id}&page=${repositories.page - 1}`} className="text-muted hover:text-fg">
307 Previous
308 </Link>
309 ) : (
310 <span />
311 )}
312 {repositories.page * repositories.perPage < repositories.total && (
313 <Link to={`${here}?installation=${installation.id}&page=${repositories.page + 1}`} className="text-muted hover:text-fg">
314 Next
315 </Link>
316 )}
317 </div>
318 )}
319 </FieldSet>
320
321 <CheckboxOption
322 name="issues"
323 defaultChecked
324 label="Copy its issues too, as work items"
325 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."
326 />
327
328 {actionData?.results && actionData.results.length > 0 && (
329 <ul className="space-y-1 rounded-md border border-line p-4 text-sm">
330 {actionData.results.map((result) => (
331 <li key={result.id}>
332 <span className="font-mono">{names.get(result.id) ?? result.id}</span>:{" "}
333 {result.ok ? (
334 <Link to={`/${result.repo}`} className="text-accent underline underline-offset-4">
335 {result.repo}
336 </Link>
337 ) : (
338 <span className="text-danger">{result.error}</span>
339 )}
340 </li>
341 ))}
342 </ul>
343 )}
344 <ErrorText>{actionData?.error}</ErrorText>
345 <div className="flex items-center gap-3">
346 <SubmitButton variant="accent" pending="Bringing them across…" match={{ intent: "import" }}>
347 Bring to g1t
348 </SubmitButton>
349 <ButtonLink to="/new" variant="outline">
350 Cancel
351 </ButtonLink>
352 </div>
353 </Form>
354 )}
355 </>
356 )}
357 </main>
358 );
359}