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.

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