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