Open History to see the last commit
1import {
2 type EnvironmentId,
3 type GitActionProgressEvent,
4 type GitStackedAction,
5 type ThreadId,
6} from "@t3tools/contracts";
7import {
8 infiniteQueryOptions,
9 mutationOptions,
10 queryOptions,
11 type QueryClient,
12} from "@tanstack/react-query";
13import { ensureEnvironmentApi } from "../environmentApi";
14import { requireEnvironmentConnection } from "../environments/runtime";
15
16const GIT_BRANCHES_STALE_TIME_MS = 15_000;
17const GIT_BRANCHES_REFETCH_INTERVAL_MS = 60_000;
18const GIT_BRANCHES_PAGE_SIZE = 100;
19
20export const gitQueryKeys = {
21 all: ["git"] as const,
22 branches: (environmentId: EnvironmentId | null, cwd: string | null) =>
23 ["git", "branches", environmentId ?? null, cwd] as const,
24 branchSearch: (environmentId: EnvironmentId | null, cwd: string | null, query: string) =>
25 ["git", "branches", environmentId ?? null, cwd, "search", query] as const,
26};
27
28export const gitMutationKeys = {
29 init: (environmentId: EnvironmentId | null, cwd: string | null) =>
30 ["git", "mutation", "init", environmentId ?? null, cwd] as const,
31 checkout: (environmentId: EnvironmentId | null, cwd: string | null) =>
32 ["git", "mutation", "checkout", environmentId ?? null, cwd] as const,
33 runStackedAction: (environmentId: EnvironmentId | null, cwd: string | null) =>
34 ["git", "mutation", "run-stacked-action", environmentId ?? null, cwd] as const,
35 pull: (environmentId: EnvironmentId | null, cwd: string | null) =>
36 ["git", "mutation", "pull", environmentId ?? null, cwd] as const,
37 preparePullRequestThread: (environmentId: EnvironmentId | null, cwd: string | null) =>
38 ["git", "mutation", "prepare-pull-request-thread", environmentId ?? null, cwd] as const,
39};
40
41export function invalidateGitQueries(
42 queryClient: QueryClient,
43 input?: { environmentId?: EnvironmentId | null; cwd?: string | null },
44) {
45 const environmentId = input?.environmentId ?? null;
46 const cwd = input?.cwd ?? null;
47 if (cwd !== null) {
48 return queryClient.invalidateQueries({ queryKey: gitQueryKeys.branches(environmentId, cwd) });
49 }
50
51 return queryClient.invalidateQueries({ queryKey: gitQueryKeys.all });
52}
53
54function invalidateGitBranchQueries(
55 queryClient: QueryClient,
56 environmentId: EnvironmentId | null,
57 cwd: string | null,
58) {
59 if (cwd === null) {
60 return Promise.resolve();
61 }
62
63 return queryClient.invalidateQueries({ queryKey: gitQueryKeys.branches(environmentId, cwd) });
64}
65
66export function gitBranchSearchInfiniteQueryOptions(input: {
67 environmentId: EnvironmentId | null;
68 cwd: string | null;
69 query: string;
70 enabled?: boolean;
71}) {
72 const normalizedQuery = input.query.trim();
73
74 return infiniteQueryOptions({
75 queryKey: gitQueryKeys.branchSearch(input.environmentId, input.cwd, normalizedQuery),
76 initialPageParam: 0,
77 queryFn: async ({ pageParam }) => {
78 if (!input.cwd) throw new Error("Git branches are unavailable.");
79 if (!input.environmentId) throw new Error("Git branches are unavailable.");
80 const api = ensureEnvironmentApi(input.environmentId);
81 return api.git.listBranches({
82 cwd: input.cwd,
83 ...(normalizedQuery.length > 0 ? { query: normalizedQuery } : {}),
84 cursor: pageParam,
85 limit: GIT_BRANCHES_PAGE_SIZE,
86 });
87 },
88 getNextPageParam: (lastPage) => lastPage.nextCursor ?? undefined,
89 enabled: input.cwd !== null && (input.enabled ?? true),
90 staleTime: GIT_BRANCHES_STALE_TIME_MS,
91 refetchOnWindowFocus: true,
92 refetchOnReconnect: true,
93 refetchInterval: GIT_BRANCHES_REFETCH_INTERVAL_MS,
94 });
95}
96
97export function gitResolvePullRequestQueryOptions(input: {
98 environmentId: EnvironmentId | null;
99 cwd: string | null;
100 reference: string | null;
101}) {
102 return queryOptions({
103 queryKey: [
104 "git",
105 "pull-request",
106 input.environmentId ?? null,
107 input.cwd,
108 input.reference,
109 ] as const,
110 queryFn: async () => {
111 if (!input.cwd || !input.reference || !input.environmentId) {
112 throw new Error("Pull request lookup is unavailable.");
113 }
114 const api = ensureEnvironmentApi(input.environmentId);
115 return api.git.resolvePullRequest({ cwd: input.cwd, reference: input.reference });
116 },
117 enabled: input.environmentId !== null && input.cwd !== null && input.reference !== null,
118 staleTime: 30_000,
119 refetchOnWindowFocus: false,
120 refetchOnReconnect: false,
121 });
122}
123
124export function gitInitMutationOptions(input: {
125 environmentId: EnvironmentId | null;
126 cwd: string | null;
127 queryClient: QueryClient;
128}) {
129 return mutationOptions({
130 mutationKey: gitMutationKeys.init(input.environmentId, input.cwd),
131 mutationFn: async () => {
132 if (!input.cwd || !input.environmentId) throw new Error("Git init is unavailable.");
133 const api = ensureEnvironmentApi(input.environmentId);
134 return api.git.init({ cwd: input.cwd });
135 },
136 onSettled: async () => {
137 await invalidateGitBranchQueries(input.queryClient, input.environmentId, input.cwd);
138 },
139 });
140}
141
142export function gitCheckoutMutationOptions(input: {
143 environmentId: EnvironmentId | null;
144 cwd: string | null;
145 queryClient: QueryClient;
146}) {
147 return mutationOptions({
148 mutationKey: gitMutationKeys.checkout(input.environmentId, input.cwd),
149 mutationFn: async (branch: string) => {
150 if (!input.cwd || !input.environmentId) throw new Error("Git checkout is unavailable.");
151 const api = ensureEnvironmentApi(input.environmentId);
152 return api.git.checkout({ cwd: input.cwd, branch });
153 },
154 onSettled: async () => {
155 await invalidateGitBranchQueries(input.queryClient, input.environmentId, input.cwd);
156 },
157 });
158}
159
160export function gitRunStackedActionMutationOptions(input: {
161 environmentId: EnvironmentId | null;
162 cwd: string | null;
163 queryClient: QueryClient;
164}) {
165 return mutationOptions({
166 mutationKey: gitMutationKeys.runStackedAction(input.environmentId, input.cwd),
167 mutationFn: async ({
168 actionId,
169 action,
170 commitMessage,
171 featureBranch,
172 filePaths,
173 onProgress,
174 }: {
175 actionId: string;
176 action: GitStackedAction;
177 commitMessage?: string;
178 featureBranch?: boolean;
179 filePaths?: string[];
180 onProgress?: (event: GitActionProgressEvent) => void;
181 }) => {
182 if (!input.cwd || !input.environmentId) throw new Error("Git action is unavailable.");
183 return requireEnvironmentConnection(input.environmentId).client.git.runStackedAction(
184 {
185 action,
186 actionId,
187 cwd: input.cwd,
188 ...(commitMessage ? { commitMessage } : {}),
189 ...(featureBranch ? { featureBranch: true } : {}),
190 ...(filePaths && filePaths.length > 0 ? { filePaths } : {}),
191 },
192 ...(onProgress ? [{ onProgress }] : []),
193 );
194 },
195 onSuccess: async () => {
196 await invalidateGitBranchQueries(input.queryClient, input.environmentId, input.cwd);
197 },
198 });
199}
200
201export function gitPullMutationOptions(input: {
202 environmentId: EnvironmentId | null;
203 cwd: string | null;
204 queryClient: QueryClient;
205}) {
206 return mutationOptions({
207 mutationKey: gitMutationKeys.pull(input.environmentId, input.cwd),
208 mutationFn: async () => {
209 if (!input.cwd || !input.environmentId) throw new Error("Git pull is unavailable.");
210 const api = ensureEnvironmentApi(input.environmentId);
211 return api.git.pull({ cwd: input.cwd });
212 },
213 onSuccess: async () => {
214 await invalidateGitBranchQueries(input.queryClient, input.environmentId, input.cwd);
215 },
216 });
217}
218
219export function gitCreateWorktreeMutationOptions(input: {
220 environmentId: EnvironmentId | null;
221 queryClient: QueryClient;
222}) {
223 return mutationOptions({
224 mutationKey: ["git", "mutation", "create-worktree", input.environmentId ?? null] as const,
225 mutationFn: (
226 args: Parameters<ReturnType<typeof ensureEnvironmentApi>["git"]["createWorktree"]>[0],
227 ) => {
228 if (!input.environmentId) {
229 throw new Error("Worktree creation is unavailable.");
230 }
231 return ensureEnvironmentApi(input.environmentId).git.createWorktree(args);
232 },
233 onSuccess: async () => {
234 await invalidateGitQueries(input.queryClient, { environmentId: input.environmentId });
235 },
236 });
237}
238
239export function gitRemoveWorktreeMutationOptions(input: {
240 environmentId: EnvironmentId | null;
241 queryClient: QueryClient;
242}) {
243 return mutationOptions({
244 mutationKey: ["git", "mutation", "remove-worktree", input.environmentId ?? null] as const,
245 mutationFn: (
246 args: Parameters<ReturnType<typeof ensureEnvironmentApi>["git"]["removeWorktree"]>[0],
247 ) => {
248 if (!input.environmentId) {
249 throw new Error("Worktree removal is unavailable.");
250 }
251 return ensureEnvironmentApi(input.environmentId).git.removeWorktree(args);
252 },
253 onSuccess: async () => {
254 await invalidateGitQueries(input.queryClient, { environmentId: input.environmentId });
255 },
256 });
257}
258
259export function gitPreparePullRequestThreadMutationOptions(input: {
260 environmentId: EnvironmentId | null;
261 cwd: string | null;
262 queryClient: QueryClient;
263}) {
264 return mutationOptions({
265 mutationKey: gitMutationKeys.preparePullRequestThread(input.environmentId, input.cwd),
266 mutationFn: async (args: {
267 reference: string;
268 mode: "local" | "worktree";
269 threadId?: ThreadId;
270 }) => {
271 if (!input.cwd || !input.environmentId) {
272 throw new Error("Pull request thread preparation is unavailable.");
273 }
274 const api = ensureEnvironmentApi(input.environmentId);
275 return api.git.preparePullRequestThread({
276 cwd: input.cwd,
277 reference: args.reference,
278 mode: args.mode,
279 ...(args.threadId ? { threadId: args.threadId } : {}),
280 });
281 },
282 onSuccess: async () => {
283 await invalidateGitBranchQueries(input.queryClient, input.environmentId, input.cwd);
284 },
285 });
286}