Open History to see the last commit
1import type {
2 EnvironmentId,
3 ScopedThreadRef,
4 ThreadLinkedPullRequest,
5 ThreadPullRequestLink,
6} from "@t3tools/contracts";
7import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell";
8import {
9 isAtomCommandInterrupted,
10 squashAtomCommandFailure,
11} from "@t3tools/client-runtime/state/runtime";
12import {
13 planThreadPullRequestMutation,
14 threadPullRequestLinkMode,
15} from "@t3tools/client-runtime/thread-pull-request-compatibility";
16import {
17 threadPullRequestKeysEqual,
18 visibleThreadPullRequests,
19} from "@t3tools/client-runtime/thread-pull-requests";
20import { findProjectForChangeRequest } from "@t3tools/client-runtime/change-request-links";
21import {
22 sourceControlClients,
23 type ChangeRequestLink,
24} from "@t3tools/client-runtime/source-control-clients";
25import { useAtomValue } from "@effect/atom-react";
26import { Atom } from "effect/reactivity";
27import { appAtomRegistry } from "~/rpc/atomRegistry";
28import { useProjects } from "~/state/entities";
29import { environmentServerConfigsAtom } from "~/state/server";
30import { threadEnvironment } from "~/state/threads";
31import { useAtomCommand } from "~/state/use-atom-command";
32
33export function canLinkChangeRequest(
34 mode: ReturnType<typeof threadPullRequestLinkMode>,
35 projects: ReadonlyArray<EnvironmentProject>,
36 parsed: ChangeRequestLink,
37): boolean {
38 if (mode === "unsupported") return false;
39 if (mode === "multiple") return true;
40 return findProjectForChangeRequest(projects, parsed) !== undefined;
41}
42
43// A primitive mode prevents unchanged status pushes from re-rendering every link.
44const linkModeAtom = Atom.family((environmentId: EnvironmentId | null) =>
45 Atom.make((get) =>
46 threadPullRequestLinkMode(
47 environmentId === null
48 ? undefined
49 : get(environmentServerConfigsAtom).get(environmentId)?.environment.capabilities,
50 ),
51 ).pipe(Atom.withLabel("pull-request-link-mode")),
52);
53
54export function usePullRequestLinking(environmentId: EnvironmentId | null | undefined) {
55 const projects = useProjects();
56 const mode = useAtomValue(linkModeAtom(environmentId ?? null));
57 const link = useAtomCommand(threadEnvironment.linkPullRequest, { reportFailure: false });
58 const unlink = useAtomCommand(threadEnvironment.unlinkPullRequest, { reportFailure: false });
59 const updateMetadata = useAtomCommand(threadEnvironment.updateMetadata, { reportFailure: false });
60 const environmentProjects = projects.filter((project) => project.environmentId === environmentId);
61 const canLink = (url: string) => {
62 const parsed = sourceControlClients.parseChangeRequestUrl(url)?.link;
63 return parsed !== undefined && canLinkChangeRequest(mode, environmentProjects, parsed);
64 };
65 const isLinked = (
66 thread: {
67 readonly pullRequests?: readonly ThreadPullRequestLink[];
68 readonly linkedPullRequest?: ThreadLinkedPullRequest | null | undefined;
69 } | null,
70 url: string,
71 ) => {
72 if (thread === null || mode === "unsupported") return false;
73 if (mode !== "multiple")
74 return (
75 thread.linkedPullRequest != null &&
76 sourceControlClients.isSameChangeRequest(thread.linkedPullRequest.url, url)
77 );
78 const parsed = sourceControlClients.parseChangeRequestUrl(url)?.link;
79 return (
80 parsed !== undefined &&
81 visibleThreadPullRequests(thread.pullRequests ?? []).some((entry) =>
82 threadPullRequestKeysEqual(entry, parsed),
83 )
84 );
85 };
86 const changeLink = async (threadRef: ScopedThreadRef, url: string, linked: boolean) => {
87 const parsed = sourceControlClients.parseChangeRequestUrl(url)?.link;
88 if (
89 parsed === undefined ||
90 threadRef.environmentId !== environmentId ||
91 (linked && !canLink(url))
92 )
93 throw new Error("The pull request is not available in this environment.");
94 const legacyProject = findProjectForChangeRequest(environmentProjects, parsed);
95 const mutation = planThreadPullRequestMutation({
96 capabilities: appAtomRegistry.get(environmentServerConfigsAtom).get(threadRef.environmentId)
97 ?.environment.capabilities,
98 threadId: threadRef.threadId,
99 reference: { ...parsed, url },
100 legacyProjectId: legacyProject?.id ?? null,
101 legacyRepository:
102 sourceControlClients.repositorySelector(legacyProject?.repositoryIdentity) ?? undefined,
103 linked,
104 });
105 if (mutation === null)
106 throw new Error("This environment does not support linking this pull request.");
107 const result = await (mutation.type === "thread.meta.update"
108 ? updateMetadata({ environmentId: threadRef.environmentId, input: mutation.input })
109 : mutation.type === "thread.pull-request.link"
110 ? link({ environmentId: threadRef.environmentId, input: mutation.input })
111 : unlink({ environmentId: threadRef.environmentId, input: mutation.input }));
112 if (result._tag === "Failure") {
113 if (isAtomCommandInterrupted(result)) throw new Error("Link update interrupted.");
114 throw squashAtomCommandFailure(result);
115 }
116 };
117 return { mode, canLink, isLinked, changeLink };
118}