Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

TanStackSourceSourceControlProvider.ts

610 lines24.2 KB

1import {
2 requireSettingsSecretLiteral,
3 SourceControlProviderError,
4 type ChangeRequest,
5 type SourceControlProviderAuth,
6 type SourceControlProviderDiscoveryItem,
7} from "@t3tools/contracts";
8import * as HostProcess from "@t3tools/shared/HostProcess";
9import {
10 isMissingExecutable,
11 providerAuth,
12 type SourceControlManagedCliDiscoverySpec,
13} from "@t3tools/source-control-core/server/discovery";
14import * as SourceControlHost from "@t3tools/source-control-core/server/SourceControlHost";
15import * as SourceControlProvider from "@t3tools/source-control-core/server/SourceControlProvider";
16import { readSourceControlHostSettings } from "@t3tools/source-control-core/shared/definition";
17import * as DateTime from "effect/DateTime";
18import * as Effect from "effect/Effect";
19import * as FileSystem from "effect/FileSystem";
20import * as Option from "effect/Option";
21import * as Result from "effect/Result";
22import * as Schema from "effect/Schema";
23​
24import * as TanStackSource from "../shared/definition.ts";
25import * as TanStackSourceApi from "./TanStackSourceApi.ts";
26import { parseTanStackSourceAuthStatus } from "./tanStackSourceAuthStatus.ts";
27import * as TanStackSourceCredentials from "./TanStackSourceCredentials.ts";
28import * as Hosts from "./tanStackSourceHosts.ts";
29import * as Json from "./tanStackSourceJson.ts";
30​
31const HOST = TanStackSource.TANSTACK_SOURCE_HOST;
32/** Pull requests from one branch name, across forks, read in full when looking one up. */
33const MAX_BRANCH_MATCHES = 20;
34const LABEL = "TanStack Source";
35const LOGIN = `src auth login --web --hostname ${HOST}`;
36​
37const INSTALL_HINT = `Install the TanStack Source CLI with \`curl -fsSL https://${HOST}/install | sh\`, then run \`${LOGIN}\`, save a token in Settings, or set SRC_TOKEN on the server.`;
38​
39/** The account a request would use: SRC_TOKEN, else the one picked in Settings, else the active one. */
40export function effectiveAccount(
41 accounts: ReturnType<typeof parseTanStackSourceAuthStatus>,
42 choice: string | undefined,
43) {
44 const usable = accounts.filter((entry) => entry.host === HOST && entry.authenticated);
45 return (
46 usable.find((entry) => entry.environmentVariable !== null) ??
47 (choice === undefined ? undefined : usable.find((entry) => entry.account === choice)) ??
48 usable.find((entry) => entry.active) ??
49 usable[0]
50 );
52​
53const decodeUser = Schema.decodeEffect(Schema.fromJsonString(Json.SourceUser));
54​
55const authAccounts = (accounts: ReturnType<typeof parseTanStackSourceAuthStatus>) =>
56 accounts
57 .filter((entry) => entry.account !== "")
58 .map((entry) => ({
59 host: entry.host,
60 account: entry.account,
61 active: entry.active,
62 authenticated: entry.authenticated,
63 ...(entry.error === null ? {} : { error: entry.error }),
64 ...(entry.environmentVariable === null
65 ? {}
66 : { environmentVariable: entry.environmentVariable }),
67 }));
68​
69/**
70 * `src` has no version flag, so its sign-in status is the only probe. A saved token or SRC_TOKEN
71 * is checked against the API, since the CLI knows nothing of the first.
72 */
73export const makeDiscovery = Effect.gen(function* () {
74 const sourceControlHost = yield* SourceControlHost.SourceControlHost;
75 const api = yield* TanStackSourceApi.TanStackSourceApi;
76 const environment = yield* HostProcess.Environment;
77​
78 const viewer = api.request({ host: HOST, operation: "discovery", path: "/user" }).pipe(
79 Effect.flatMap((raw) =>
80 decodeUser(raw).pipe(
81 Effect.mapError(
82 (cause) =>
83 new TanStackSourceApi.TanStackSourceApiError({
84 host: HOST,
85 operation: "discovery",
86 status: null,
87 reason: "failed",
88 detail: "TanStack Source returned an unreadable account.",
89 cause,
90 }),
91 ),
92 ),
93 ),
94 Effect.result,
95 );
96​
97 const probe = Effect.fn("TanStackSourceSourceControlProvider.discovery")(function* (cwd: string) {
98 const current = yield* sourceControlHost.settings
99 .getWithSecrets(TanStackSource.definition.kind)
100 .pipe(Effect.orElseSucceed(() => undefined));
101 const settings = readSourceControlHostSettings(
102 TanStackSource.settings,
103 current?.sourceControlHosts[TanStackSource.definition.kind],
104 );
105 const status = yield* sourceControlHost.process
106 .run({
107 operation: "source-control.discovery.auth",
108 command: "src",
109 args: ["auth", "status"],
110 cwd,
111 env: { SRC_NO_TELEMETRY: "1" },
112 allowNonZeroExit: true,
113 timeoutMs: 5_000,
114 maxOutputBytes: 8_000,
115 appendTruncationMarker: true,
116 })
117 .pipe(Effect.result);
118 const installed = Result.isSuccess(status) || !isMissingExecutable(status.failure);
119 const accounts = Result.isSuccess(status)
120 ? parseTanStackSourceAuthStatus(`${status.success.stdout}\n${status.success.stderr}`)
121 : [];
122 const item = (fields: {
123 readonly auth: SourceControlProviderAuth;
124 readonly available: boolean;
125 }): SourceControlProviderDiscoveryItem => ({
126 kind: TanStackSource.definition.kind,
127 label: LABEL,
128 executable: "src",
129 status: fields.available ? "available" : "missing",
130 version: Option.none(),
131 installHint: INSTALL_HINT,
132 detail: Option.none(),
133 auth:
134 accounts.length === 0 ? fields.auth : { ...fields.auth, accounts: authAccounts(accounts) },
135 });
136​
137 if (settings.hosts[HOST]?.enabled === false)
138 return item({
139 available: installed,
140 auth: providerAuth({
141 status: "unauthenticated",
142 host: HOST,
143 detail: `${HOST} is turned off in Settings → Source control & issues.`,
144 }),
145 });
146​
147 const saved = yield* Effect.result(
148 requireSettingsSecretLiteral(settings.tokens[HOST], current?.secretProviders ?? {}),
149 );
150 if (Result.isFailure(saved))
151 return item({
152 available: true,
153 auth: providerAuth({
154 status: "unauthenticated",
155 host: HOST,
156 detail: saved.failure.message,
157 }),
158 });
159 const savedToken = saved.success.trim() !== "";
160 const envToken = TanStackSourceCredentials.environmentToken(HOST, environment) !== null;
161 if (savedToken || envToken) {
162 const tokenSource = savedToken ? "the token saved in Settings" : "SRC_TOKEN";
163 const answer = yield* viewer;
164 return item({
165 available: true,
166 auth: Result.isSuccess(answer)
167 ? providerAuth({
168 status: "authenticated",
169 host: HOST,
170 account: answer.success.username,
171 detail: savedToken
172 ? "Using the token saved in Settings; it overrides SRC_TOKEN and the src login."
173 : "Using SRC_TOKEN from the server environment; it overrides the account chosen in Settings.",
174 })
175 : answer.failure.reason === "unauthenticated"
176 ? providerAuth({
177 status: "unauthenticated",
178 host: HOST,
179 detail: savedToken
180 ? "TanStack Source refused the token saved in Settings. Replace or remove it in Settings → Source control & issues."
181 : "TanStack Source refused the token in SRC_TOKEN. Replace it, or unset it to use `src auth login`.",
182 })
183 : providerAuth({
184 status: "unknown",
185 host: HOST,
186 detail: `Could not check ${tokenSource}: ${answer.failure.detail}`,
187 }),
188 });
189 }
190​
191 if (!installed)
192 return item({
193 available: false,
194 auth: providerAuth({ status: "unknown", detail: INSTALL_HINT }),
195 });
196 const chosen = effectiveAccount(accounts, settings.hosts[HOST]?.account);
197 if (chosen !== undefined)
198 return item({
199 available: true,
200 auth: providerAuth({ status: "authenticated", host: HOST, account: chosen.account }),
201 });
202 const failed = accounts.find((entry) => entry.host === HOST);
203 return item({
204 available: true,
205 auth: providerAuth({
206 status: Result.isSuccess(status) ? "unauthenticated" : "unknown",
207 host: HOST,
208 detail: failed?.error ?? `Run \`${LOGIN}\` to sign the src CLI in.`,
209 }),
210 });
211 });
212​
213 return {
214 type: "managed-cli",
215 kind: TanStackSource.definition.kind,
216 label: LABEL,
217 installHint: INSTALL_HINT,
218 probe,
219 // Source's remotes are recognized by host alone, so an unknown remote is never one.
220 refineUnknownRemote: () => Effect.succeed(null),
221 } satisfies SourceControlManagedCliDiscoverySpec;
222});
223​
224const Repository = Schema.Struct({
225 owner: Schema.String,
226 name: Schema.String,
227 defaultBranch: Schema.NullOr(Schema.String),
228 cloneUrl: Schema.String,
229});
230​
231interface Target {
232 readonly host: Hosts.TanStackSourceHost;
233 readonly repository: string;
235​
236const cloneUrls = (target: Target, cloneUrl?: string) => {
237 const url = cloneUrl ?? `${Hosts.webRepositoryUrl(target.host, target.repository)}.git`;
238 // Source serves git over HTTPS only.
239 return { nameWithOwner: target.repository, url, sshUrl: url };
240};
241​
242export const make = Effect.gen(function* () {
243 const api = yield* TanStackSourceApi.TanStackSourceApi;
244 const host = yield* SourceControlHost.SourceControlHost;
245 const fileSystem = yield* FileSystem.FileSystem;
246​
247 const error = (operation: string, cwd: string, detail: string, cause?: unknown) =>
248 new SourceControlProviderError({
249 provider: TanStackSource.definition.kind,
250 operation,
251 cwd,
252 detail,
253 ...(cause === undefined ? {} : { cause }),
254 });
255 const read = <S extends Schema.Codec<unknown, unknown, never, never>>(
256 operation: string,
257 cwd: string,
258 request: Omit<TanStackSourceApi.TanStackSourceApiRequest, "operation">,
259 schema: S,
260 ) =>
261 api.request({ ...request, operation }).pipe(
262 Effect.mapError((cause) => error(operation, cwd, cause.detail, cause)),
263 Effect.flatMap((raw) =>
264 Schema.decodeEffect(Schema.fromJsonString(schema))(raw).pipe(
265 Effect.mapError((cause) =>
266 error(operation, cwd, "TanStack Source returned an unreadable response.", cause),
267 ),
268 ),
269 ),
270 );
271​
272 const resolveTarget = Effect.fn("TanStackSourceSourceControlProvider.resolveTarget")(function* (
273 operation: string,
274 input: {
275 readonly cwd: string;
276 readonly context?: SourceControlProvider.SourceControlProviderContext;
277 readonly repository?: string;
278 },
279 ) {
280 const named =
281 input.repository === undefined ? null : Hosts.parseTanStackSourceRemote(input.repository);
282 if (named) return named;
283 if (input.repository !== undefined) {
284 const repository = Hosts.tanStackSourceRepositoryPath(input.repository);
285 if (repository !== null) return { host: HOST, repository } satisfies Target;
286 return yield* error(
287 operation,
288 input.cwd,
289 "A TanStack Source repository is named owner/name or by its source.tanstack.com URL.",
290 );
291 }
292 const remoteUrl =
293 input.context?.remoteUrl ??
294 (yield* host.git.resolvePrimaryRemoteName(input.cwd).pipe(
295 Effect.flatMap((remote) => host.git.readConfigValue(input.cwd, `remote.${remote}.url`)),
296 Effect.mapError((cause) =>
297 error(operation, input.cwd, "Could not read the TanStack Source remote.", cause),
298 ),
299 ));
300 const remote = remoteUrl ? Hosts.parseTanStackSourceRemote(remoteUrl) : null;
301 if (remote) return remote;
302 return yield* error(operation, input.cwd, "No TanStack Source repository remote was found.");
303 });
304​
305 const toChangeRequest = (target: Target, pull: Json.SourcePullDetail): ChangeRequest => {
306 const headRepository = pull.headRepo ?? target.repository;
307 const headBranch = Json.headBranchName(pull.head);
308 // A pull request synced from a GitHub fork names its head only by its pull ref.
309 const crossRepository =
310 headRepository.toLowerCase() !== target.repository.toLowerCase() ||
311 headBranch.startsWith("refs/");
312 const updatedAt = pull.mergedAt ?? pull.createdAt;
313 return {
314 provider: TanStackSource.definition.kind,
315 number: pull.number,
316 title: pull.title,
317 url: Json.pullUrl(target.host, target.repository, pull.number),
318 baseRefName: pull.base,
319 headRefName: headBranch,
320 ...(pull.headSha ? { headSha: pull.headSha } : {}),
321 state: pull.state,
322 ...(pull.draft ? { isDraft: true } : {}),
323 mergedAt: pull.mergedAt === null ? null : Json.iso(pull.mergedAt),
324 updatedAt: Option.some(DateTime.makeUnsafe(updatedAt)),
325 isCrossRepository: crossRepository,
326 headRepositoryNameWithOwner: headRepository,
327 headRepositoryOwnerLogin: headRepository.split("/")[0] ?? null,
328 };
329 };
330​
331 const readPull = (operation: string, cwd: string, target: Target, number: number) =>
332 read(
333 operation,
334 cwd,
335 { host: target.host, path: `/repos/${target.repository}/pulls/${number}` },
336 Json.SourcePullDetail,
337 ).pipe(Effect.map((pull) => toChangeRequest(target, pull)));
338​
339 const getPull = Effect.fn("TanStackSourceSourceControlProvider.getPull")(function* (input: {
340 readonly cwd: string;
341 readonly context?: SourceControlProvider.SourceControlProviderContext;
342 readonly reference: string;
343 }) {
344 const link = TanStackSource.parsePullRequestUrl(input.reference.trim());
345 const target: Target = link
346 ? { host: HOST, repository: link.repository }
347 : yield* resolveTarget("getChangeRequest", input);
348 const number = link ? link.number : Number(/^#?([1-9]\d*)$/u.exec(input.reference.trim())?.[1]);
349 if (!Number.isSafeInteger(number) || number < 1)
350 return yield* error(
351 "getChangeRequest",
352 input.cwd,
353 "A TanStack Source pull request is a number or a source.tanstack.com pull request URL.",
354 );
355 return yield* readPull("getChangeRequest", input.cwd, target, number);
356 });
357​
358 return SourceControlProvider.SourceControlProvider.of({
359 kind: TanStackSource.definition.kind,
360 repositoryNameFromRemoteUrl: (url) => Hosts.parseTanStackSourceRemote(url)?.repository ?? null,
361 getChangeRequest: getPull,
362 listChangeRequests: Effect.fn("TanStackSourceSourceControlProvider.listChangeRequests")(
363 function* (input) {
364 const target = yield* resolveTarget("listChangeRequests", input);
365 const source = SourceControlProvider.sourceControlRefFromInput(input);
366 const branch = SourceControlProvider.sourceBranch(input);
367 const limit = input.limit ?? 20;
368 const query = new URLSearchParams({ head: branch });
369 if (input.state !== "all") query.set("state", input.state);
370 const page = yield* read(
371 "listChangeRequests",
372 input.cwd,
373 { host: target.host, path: `/repos/${target.repository}/pulls?${query}` },
374 Json.SourcePulls,
375 );
376 // List rows name neither the base nor the head's repository, so matches are read in full
377 // and the limit counts only those whose head is the one asked for.
378 const matches = page.items
379 .filter((pull) => Json.headBranchName(pull.head) === branch)
380 .slice(0, MAX_BRANCH_MATCHES);
381 const details = yield* Effect.forEach(
382 matches,
383 (pull) => readPull("listChangeRequests", input.cwd, target, pull.number),
384 { concurrency: 4 },
385 );
386 const owned = details.filter(
387 (detail) =>
388 (!source?.repository ||
389 detail.headRepositoryNameWithOwner?.toLowerCase() ===
390 source.repository.toLowerCase()) &&
391 (!source?.owner ||
392 detail.headRepositoryOwnerLogin?.toLowerCase() === source.owner.toLowerCase()),
393 );
394 return owned.slice(0, limit);
395 },
396 ),
397 createsDraftChangeRequests: true,
398 createChangeRequest: Effect.fn("TanStackSourceSourceControlProvider.createChangeRequest")(
399 function* (input) {
400 const target = yield* resolveTarget("createChangeRequest", {
401 ...input,
402 ...(input.target?.repository ? { repository: input.target.repository } : {}),
403 });
404 const source = SourceControlProvider.sourceControlRefFromInput(input);
405 if (
406 (source?.repository &&
407 source.repository.toLowerCase() !== target.repository.toLowerCase()) ||
408 (source?.owner &&
409 source.owner.toLowerCase() !== target.repository.split("/")[0]?.toLowerCase())
410 )
411 return yield* error(
412 "createChangeRequest",
413 input.cwd,
414 "TanStack Source opens pull requests from a branch of the same repository. Push the branch there first.",
415 );
416 const body = yield* fileSystem
417 .readFileString(input.bodyFile)
418 .pipe(
419 Effect.mapError((cause) =>
420 error(
421 "createChangeRequest",
422 input.cwd,
423 "Could not read the pull request description.",
424 cause,
425 ),
426 ),
427 );
428 yield* api
429 .request({
430 host: target.host,
431 operation: "createChangeRequest",
432 method: "POST",
433 path: `/repos/${target.repository}/pulls`,
434 body: {
435 title: input.title,
436 head: SourceControlProvider.sourceBranch(input),
437 base: input.target?.refName ?? input.baseRefName,
438 ...(body.trim().length === 0 ? {} : { body }),
439 ...(input.draft === true ? { draft: true } : {}),
440 },
441 })
442 .pipe(
443 Effect.mapError((cause) =>
444 error("createChangeRequest", input.cwd, cause.detail, cause),
445 ),
446 );
447 },
448 ),
449 getRepositoryCloneUrls: Effect.fn("TanStackSourceSourceControlProvider.getRepositoryCloneUrls")(
450 function* (input) {
451 const target = yield* resolveTarget("getRepositoryCloneUrls", input);
452 const repository = yield* read(
453 "getRepositoryCloneUrls",
454 input.cwd,
455 { host: target.host, path: `/repos/${target.repository}` },
456 Repository,
457 );
458 return cloneUrls(
459 { host: target.host, repository: `${repository.owner}/${repository.name}` },
460 repository.cloneUrl,
461 );
462 },
463 ),
464 createRepository: Effect.fn("TanStackSourceSourceControlProvider.createRepository")(
465 function* (input) {
466 const target = yield* resolveTarget("createRepository", input);
467 const [owner, name] = target.repository.split("/");
468 const created = yield* read(
469 "createRepository",
470 input.cwd,
471 {
472 host: target.host,
473 method: "POST",
474 path: "/repos",
475 body: { name, owner, visibility: input.visibility },
476 },
477 Repository,
478 );
479 return cloneUrls(
480 { host: target.host, repository: `${created.owner}/${created.name}` },
481 created.cloneUrl,
482 );
483 },
484 ),
485 getDefaultBranch: Effect.fn("TanStackSourceSourceControlProvider.getDefaultBranch")(
486 function* (input) {
487 const target = yield* resolveTarget("getDefaultBranch", input);
488 const repository = yield* read(
489 "getDefaultBranch",
490 input.cwd,
491 { host: target.host, path: `/repos/${target.repository}` },
492 Repository,
493 );
494 return repository.defaultBranch;
495 },
496 ),
497 // Every pull request's head is published as `refs/pull/<n>/head`, forks and GitHub sync too.
498 checkoutChangeRequest: Effect.fn("TanStackSourceSourceControlProvider.checkoutChangeRequest")(
499 function* (input) {
500 const pull = yield* getPull(input);
501 const target = yield* resolveTarget("checkoutChangeRequest", input).pipe(
502 Effect.orElseSucceed(() => null),
503 );
504 const pullRepository = Hosts.tanStackSourceRepositoryPath(
505 new URL(pull.url).pathname.split("/pull/")[0] ?? "",
506 );
507 const git = host.git;
508 yield* Effect.gen(function* () {
509 const remoteName =
510 input.context &&
511 target !== null &&
512 pullRepository !== null &&
513 target.repository.toLowerCase() === pullRepository.toLowerCase()
514 ? input.context.remoteName
515 : yield* git.ensureRemote({
516 cwd: input.cwd,
517 preferredName: "source",
518 url: `${Hosts.webRepositoryUrl(HOST, pullRepository ?? "")}.git`,
519 });
520 const operation = "TanStackSourceSourceControlProvider.checkoutChangeRequest";
521 const branches = yield* git.listLocalBranchNames(input.cwd);
522 if (!pull.isCrossRepository) {
523 const localBranch = pull.headRefName;
524 const remoteBranch = { cwd: input.cwd, remoteName, remoteBranch: localBranch };
525 if (input.force !== true && !branches.includes(localBranch))
526 yield* git.fetchRemoteBranch({ ...remoteBranch, localBranch });
527 else yield* git.fetchRemoteTrackingBranch(remoteBranch);
528 if (input.force === true)
529 yield* git.execute({
530 operation,
531 cwd: input.cwd,
532 // The upstream is recorded next, through the host's serialized config write.
533 args: [
534 "checkout",
535 "--no-track",
536 "-B",
537 localBranch,
538 `refs/remotes/${remoteName}/${localBranch}`,
539 "--",
540 ],
541 });
542 yield* git.setBranchUpstream({ ...remoteBranch, branch: localBranch });
543 yield* Effect.scoped(git.switchRef({ cwd: input.cwd, refName: localBranch }));
544 return;
545 }
546 // A fork's head, or one synced from GitHub, is only reachable through its pull ref.
547 const localBranch = `pr-${pull.number}`;
548 const tracking = `refs/remotes/${remoteName}/pull/${pull.number}`;
549 yield* git.execute({
550 operation,
551 cwd: input.cwd,
552 args: ["fetch", "--no-tags", remoteName, `+refs/pull/${pull.number}/head:${tracking}`],
553 });
554 const exists = branches.includes(localBranch);
555 // T3 records which pull request it made `pr-<n>` for, and reuses only that branch, and
556 // only while it holds nothing the pull request lacks: an unrelated branch of the name,
557 // or local commits, are never switched to, moved or lost.
558 const ownerKey = `branch.${localBranch}.t3TanstackSourcePull`;
559 const owner = `${pullRepository ?? ""}#${pull.number}`;
560 if (exists && input.force !== true) {
561 const recorded = yield* git
562 .readConfigValue(input.cwd, ownerKey)
563 .pipe(Effect.orElseSucceed(() => null));
564 const behind =
565 recorded === owner &&
566 (yield* git
567 .execute({
568 operation,
569 cwd: input.cwd,
570 args: ["merge-base", "--is-ancestor", `refs/heads/${localBranch}`, tracking],
571 })
572 .pipe(
573 Effect.as(true),
574 Effect.orElseSucceed(() => false),
575 ));
576 if (!behind)
577 return yield* error(
578 "checkoutChangeRequest",
579 input.cwd,
580 recorded === owner
581 ? `Local branch ${localBranch} has commits pull request #${pull.number} does not. Rename it, or check out with force to replace it.`
582 : `Local branch ${localBranch} was not made for pull request #${pull.number}. Rename it, or check out with force to replace it.`,
583 );
584 }
585 if (exists)
586 yield* git.execute({
587 operation,
588 cwd: input.cwd,
589 args: ["checkout", "--no-track", "-B", localBranch, tracking, "--"],
590 });
591 else
592 yield* git.createBranch({ cwd: input.cwd, branch: localBranch, startPoint: tracking });
593 yield* git.writeConfigValue({ cwd: input.cwd, key: ownerKey, value: owner });
594 yield* Effect.scoped(git.switchRef({ cwd: input.cwd, refName: localBranch }));
595 }).pipe(
596 Effect.mapError((cause) =>
597 cause._tag === "SourceControlProviderError"
598 ? cause
599 : error(
600 "checkoutChangeRequest",
601 input.cwd,
602 "Could not check out the TanStack Source pull request.",
603 cause,
604 ),
605 ),
606 );
607 },
608 ),
609 });
610});