Skip to content
355 linesCodeBlameRaw
1import { ExternalLink, Globe, Rocket, RotateCw, Trash2 } from "lucide-react";
2import type { ReactNode } from "react";
3import { Form, Link } from "react-router";
4
5import type { Deployment, FeatureState } from "@g1t/contracts";
6
7import { host, StatusDot } from "../../components/deploy";
8
9import type { Route } from "./+types/deployments";
10import { page } from "../../lib/meta";
11import { ButtonLink, ComputeNote, EmptyState, ErrorText, SubmitButton, TimeAgo } from "../../components/ui";
12import { computeNoteFor } from "../../lib/compute.server";
13import { billing, deployments, projects } from "../../lib/services.server";
14import { assertSameOrigin, getViewer, requireUser, unwrap } from "../../lib/session.server";
15import { refusal, requireRepo } from "../../lib/access.server";
16import { whyNot } from "../../lib/access";
17import { buildError, groupBuilds, type BuildGroup } from "../../lib/deployments";
18
19export function meta({ params, ...args }: Route.MetaArgs) {
20 return page(args, { title: `Deployments · ${params.owner}/${params.repo} · g1t` });
21}
22
23export async function loader({ params, context }: Route.LoaderArgs) {
24 const viewer = getViewer(context);
25 // Anyone who can read the repository: a public one's to anyone, a private one's to people with a role.
26 const { access } = await requireRepo(context, params, "read");
27 const ref = { workspace: params.owner, slug: params.repo };
28 const [settings, list, features, computeNote, project] = await Promise.all([
29 deployments.settings(ref, viewer),
30 deployments.list(ref, viewer),
31 billing.features(params.owner, viewer),
32 // Builds are compute: said before a deploy is refused for it.
33 computeNoteFor(params.owner, "deploy"),
34 projects.get(params.owner, params.repo, viewer).catch(() => null),
35 ]);
36 // Set not to deploy, in General settings: turning them on waits for that to change.
37 const notDeploying = project?.ok ? project.value.deploys === "no" : false;
38 // Deployments come with the g1t plan. Someone outside the workspace does
39 // not see its plans; the page works without, and the deployments service
40 // refuses a deploy the plan does not cover.
41 const plan = features.ok
42 ? (features.value.find((state) => state.plan.feature === "plan" || state.plan.feature === "deployments") ?? null)
43 : null;
44 return { can: access.can, settings: unwrap(settings), ...unwrap(list), plan, computeNote, notDeploying };
45}
46
47export async function action({ request, params, context }: Route.ActionArgs) {
48 assertSameOrigin(request);
49 const user = requireUser(context, request);
50 const form = await request.formData();
51 const ref = { workspace: params.owner, slug: params.repo };
52 const intent = form.get("intent");
53 const branch = form.get("branch") ? String(form.get("branch")) : null;
54 // Deploying is compute (Write); turning deployments on or off is a deployment setting (Admin).
55 const refused = await refusal(context, params, intent === "enable" || intent === "disable" ? "manage_integrations" : "run");
56 if (refused) return { error: refused };
57 if (intent === "redeploy") {
58 const started = await deployments.redeploy(user, ref, branch);
59 return started.ok ? { notice: "Build started." } : { error: started.error.message };
60 }
61 if (intent === "take-down") {
62 const done = await deployments.takeDown(user, ref, branch);
63 return done.ok ? { notice: "Taken down." } : { error: done.error.message };
64 }
65 if (intent === "enable" || intent === "disable") {
66 const saved = await deployments.updateSettings(user, ref, { enabled: intent === "enable" });
67 return saved.ok
68 ? { notice: intent === "enable" ? "Deployments are on. Production is building." : "Deployments are off, and every app is down." }
69 : { error: saved.error.message };
70 }
71 return { error: "Unknown request." };
72}
73
74export default function RepoDeployments({ loaderData, actionData, params }: Route.ComponentProps) {
75 const { settings, deployments: builds, live, plan, can } = loaderData;
76 const base = `/${params.owner}/${params.repo}`;
77 const production = live.find((app) => app.kind === "production");
78 const previews = live.filter((app) => app.kind === "preview");
79
80 return (
81 <div className="mx-auto max-w-5xl">
82 <header className="flex flex-wrap items-start justify-between gap-4">
83 <div>
84 <h1 className="flex items-center gap-2 text-xl font-semibold tracking-tight">
85 <Rocket size={18} className="text-accent" />
86 Deployments
87 </h1>
88 <p className="mt-1 max-w-2xl text-sm text-muted">
89 Every pull request gets a live preview on g1t.page, and the default branch goes to production on each push.
90 Apps run on Cloudflare only while someone visits them.{" "}
91 <a href="https://docs.g1t.sh/guides/deployments/" className="text-fg hover:underline">
92 How it works
93 </a>
94 </p>
95 </div>
96 {settings.enabled && (
97 <a
98 href={settings.primaryDomain ? `https://${settings.primaryDomain}` : settings.productionUrl}
99 className="inline-flex items-center gap-1.5 rounded-md border border-line px-3 py-1.5 font-mono text-xs text-muted hover:border-line-strong hover:text-fg"
100 >
101 <Globe size={13} />
102 {settings.primaryDomain ?? host(settings.productionUrl)}
103 </a>
104 )}
105 </header>
106
107 <div className="mt-4 min-h-6">
108 {actionData && "notice" in actionData && <p className="text-sm text-accent">{actionData.notice}</p>}
109 <ErrorText>{actionData && "error" in actionData ? actionData.error : null}</ErrorText>
110 {!actionData && <ComputeNote note={loaderData.computeNote} />}
111 </div>
112
113 {plan != null && !plan.on && !plan.included && live.length === 0 ? (
114 <PlanNeeded plan={plan} owner={params.owner} />
115 ) : !settings.enabled ? (
116 <section className="mt-2 rounded-xl border border-accent/30 bg-accent/5 p-6">
117 <h2 className="font-medium">Deployments are off</h2>
118 <p className="mt-1 max-w-2xl text-sm text-muted">
119 Each project turns deployments on for itself; until then nothing builds or runs. Once on, production goes
120 up at <span className="font-mono text-fg">{host(settings.productionUrl)}</span> and every open pull request
121 gets its own preview. Workers projects (a <code className="font-mono text-fg">wrangler.jsonc</code>) and
122 static sites deploy without configuration.
123 </p>
124 {loaderData.notDeploying ? (
125 <p className="mt-4 max-w-2xl text-sm text-muted">
126 This project is set as one that doesn't deploy, a library or a tool. To deploy it, choose Deploys or Detect
127 automatically in{" "}
128 <Link to={`/${params.owner}/${params.repo}/settings#deploys`} className="text-fg underline underline-offset-4">
129 its settings
130 </Link>{" "}
131 first.
132 </p>
133 ) : (
134 <Form method="post" className="mt-4">
135 <SubmitButton
136 variant="accent"
137 name="intent"
138 value="enable"
139 pending="Turning on…"
140 disabled={!can.manage_integrations}
141 title={whyNot(can, "manage_integrations")}
142 >
143 <Rocket size={14} />
144 Turn on deployments
145 </SubmitButton>
146 </Form>
147 )}
148 </section>
149 ) : (
150 <>
151 <section className="mt-2 grid gap-4 md:grid-cols-2">
152 <LiveCard
153 title="Production"
154 hint="The default branch, on every push."
155 app={production}
156 off={!settings.production}
157 actions={
158 can.run ? <AppActions branch={null} up={!!production} /> : null
159 }
160 />
161 <div className="rounded-xl border border-line bg-surface p-5">
162 <h2 className="text-sm font-medium">Previews</h2>
163 <p className="mt-0.5 text-xs text-faint">
164 {settings.previews
165 ? `One per branch with an open pull request; down when it closes or after ${settings.idleDays} days without a visit.`
166 : "Off for this repository."}
167 </p>
168 {previews.length === 0 ? (
169 <p className="mt-4 text-sm text-muted">No previews are up.</p>
170 ) : (
171 <ul className="mt-3 divide-y divide-line">
172 {previews.map((app) => (
173 <li key={app.url} className="flex items-center gap-3 py-2 text-sm">
174 <span className="shrink-0">
175 <span className="font-medium">{app.branch}</span>
176 {app.number != null && (
177 <Link to={`${base}/pull/${app.number}`} className="ml-1.5 text-xs text-muted hover:underline">
178 #{app.number}
179 </Link>
180 )}
181 </span>
182 <a href={app.url} className="min-w-0 truncate font-mono text-xs text-muted hover:text-fg">
183 {host(app.url)}
184 </a>
185 <span className="ml-auto shrink-0">
186 {can.run && <AppActions branch={app.branch} up compact />}
187 </span>
188 </li>
189 ))}
190 </ul>
191 )}
192 </div>
193 </section>
194
195 <h2 className="mt-10 text-sm font-medium text-muted">Recent builds</h2>
196 <div className="mt-3">
197 {builds.length === 0 ? (
198 <EmptyState title="No builds yet">Push to the default branch or open a pull request.</EmptyState>
199 ) : (
200 <ul className="divide-y divide-line overflow-hidden rounded-xl border border-line">
201 {groupBuilds(builds).map((group) => (
202 <BuildRow key={group.build.id} group={group} base={base} />
203 ))}
204 </ul>
205 )}
206 </div>
207
208 <p className="mt-10 text-sm text-muted">
209 Build command, output directory, idle days, and turning deployments off are under{" "}
210 <Link to={`${base}/settings/deployments`} className="text-fg hover:underline">
211 Settings → Deployments
212 </Link>
213 . Secrets and config for builds and running apps are under{" "}
214 <Link to={`${base}/settings/secrets`} className="text-fg hover:underline">
215 Settings → Secrets and variables
216 </Link>
217 , and production's own domains under{" "}
218 <Link to={`${base}/settings/domains`} className="text-fg hover:underline">
219 Settings → Domains
220 </Link>
221 .
222 </p>
223 </>
224 )}
225 </div>
226 );
227}
228
229function PlanNeeded({ plan, owner }: { plan: FeatureState | null; owner: string }) {
230 return (
231 <section className="mt-2 rounded-xl border border-accent/30 bg-accent/5 p-6">
232 <h2 className="font-medium">Deployments are part of a paid plan</h2>
233 <p className="mt-1 max-w-2xl text-sm text-muted">
234 Turn on Deployments for the {owner} workspace and every project in it can have a preview for each pull
235 request and production on g1t.page.
236 {plan && ` $${(plan.plan.monthlyCents / 100).toFixed(0)} a month, including:`}
237 </p>
238 {plan && (
239 <ul className="mt-3 grid gap-1.5 text-sm text-muted sm:grid-cols-2">
240 {plan.plan.includes.map((line) => (
241 <li key={line} className="flex gap-2">
242 <span className="text-accent">✓</span>
243 {line}
244 </li>
245 ))}
246 </ul>
247 )}
248 {plan && <p className="mt-3 text-xs text-faint">{plan.plan.overage}</p>}
249 <div className="mt-4">
250 <ButtonLink variant="accent" to={`/${owner}/-/billing`}>
251 See the plan under Billing
252 </ButtonLink>
253 </div>
254 </section>
255 );
256}
257
258function LiveCard({
259 title,
260 hint,
261 app,
262 off,
263 actions,
264}: {
265 title: string;
266 hint: string;
267 app: { url: string; commit: string; deployedAt: string } | undefined;
268 off: boolean;
269 actions: ReactNode;
270}) {
271 return (
272 <div className="rounded-xl border border-line bg-surface p-5">
273 <h2 className="text-sm font-medium">{title}</h2>
274 <p className="mt-0.5 text-xs text-faint">{off ? "Off for this repository." : hint}</p>
275 {app ? (
276 <>
277 <a href={app.url} className="mt-3 flex items-center gap-1.5 font-mono text-sm text-accent hover:underline">
278 {host(app.url)}
279 <ExternalLink size={12} />
280 </a>
281 <p className="mt-1 text-xs text-faint">
282 <span className="font-mono">{app.commit.slice(0, 8)}</span> · deployed <TimeAgo at={app.deployedAt} />
283 </p>
284 </>
285 ) : (
286 <p className="mt-4 text-sm text-muted">Not up.</p>
287 )}
288 {!off && <div className="mt-4">{actions}</div>}
289 </div>
290 );
291}
292
293function AppActions({ branch, up, compact }: { branch: string | null; up: boolean; compact?: boolean }) {
294 // Which app's buttons say they are working: production has no branch.
295 const app = branch ?? "production";
296 return (
297 <Form method="post" className="flex items-center gap-2">
298 {branch != null && <input type="hidden" name="branch" value={branch} />}
299 <input type="hidden" name="app" value={app} />
300 <SubmitButton
301 variant="quiet"
302 name="intent"
303 value="redeploy"
304 match={{ app }}
305 icon={compact}
306 pending="Redeploying…"
307 title="Build again from the current head"
308 >
309 <RotateCw size={13} />
310 {!compact && "Redeploy"}
311 </SubmitButton>
312 {up && (
313 <SubmitButton
314 variant="quiet"
315 name="intent"
316 value="take-down"
317 match={{ app }}
318 icon={compact}
319 pending="Taking down…"
320 title="Take it down now"
321 >
322 <Trash2 size={13} />
323 {!compact && "Take down"}
324 </SubmitButton>
325 )}
326 </Form>
327 );
328}
329
330function BuildRow({ group, base }: { group: BuildGroup<Deployment>; base: string }) {
331 const { build, count } = group;
332 const error = buildError(build);
333 return (
334 <li>
335 <Link to={`${base}/deployments/${build.id}`} className="flex items-center gap-4 px-4 py-3 text-sm hover:bg-surface">
336 <span className="w-20 shrink-0">
337 <StatusDot status={build.status} />
338 {/* A run of the same failure is one row: how many, and when the latest was. */}
339 {count > 1 && <span className="mt-0.5 block pl-3 text-xs text-muted">{count} times</span>}
340 </span>
341 <span className="min-w-0 grow">
342 <span className="block truncate font-medium">
343 {build.kind === "production" ? "Production" : `Preview of ${build.branch}`}
344 <span className="ml-2 font-mono text-xs font-normal text-faint">{build.commit.slice(0, 8)}</span>
345 </span>
346 {error && <span className="mt-0.5 line-clamp-2 text-xs text-muted sm:line-clamp-1">{error}</span>}
347 </span>
348 <span className="shrink-0 text-xs text-faint">
349 {count > 1 ? "last " : build.buildSeconds != null && `${build.buildSeconds} s · `}
350 <TimeAgo at={build.createdAt} />
351 </span>
352 </Link>
353 </li>
354 );
355}