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

use-selected-thread-git-actions.ts

384 lines13.3 KB

1import { useCallback, useEffect, useMemo } from "react";
2​
3import { EnvironmentProject, EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
4import type { AtomCommandResult } from "@t3tools/client-runtime/state/runtime";
5import {
6 type GitActionRequestInput,
7 type VcsActionOperation,
8 type VcsRef,
9} from "@t3tools/client-runtime/state/vcs";
10import type { GitRunStackedActionResult } from "@t3tools/contracts";
11import {
12 dedupeRemoteBranchesWithLocalMatches,
13 sanitizeFeatureBranchName,
14} from "@t3tools/shared/git";
15import * as Cause from "effect/Cause";
16import { AsyncResult } from "effect/unstable/reactivity";
17​
18import { useBranches } from "../state/queries";
19import { threadEnvironment } from "../state/threads";
20import { vcsActionManager, vcsEnvironment } from "../state/vcs";
21import { uuidv4 } from "../lib/uuid";
22import { appAtomRegistry } from "./atom-registry";
23import { setPendingConnectionError } from "./use-remote-environment-registry";
24import { useAtomCommand } from "./use-atom-command";
25import { showGitActionResult } from "./use-vcs-action-state";
26import { useThreadSelection } from "./use-thread-selection";
27import { useSelectedThreadWorktree } from "./use-selected-thread-worktree";
28​
29export function useSelectedThreadGitActions() {
30 const updateThreadMetadata = useAtomCommand(threadEnvironment.updateMetadata, {
31 reportFailure: false,
32 });
33 const refreshStatus = useAtomCommand(vcsEnvironment.refreshStatus, { reportFailure: false });
34 const switchRef = useAtomCommand(vcsEnvironment.switchRef, { reportFailure: false });
35 const createRef = useAtomCommand(vcsEnvironment.createRef, { reportFailure: false });
36 const createWorktree = useAtomCommand(vcsEnvironment.createWorktree, { reportFailure: false });
37 const pull = useAtomCommand(vcsEnvironment.pull, { reportFailure: false });
38 const { selectedThread, selectedThreadProject } = useThreadSelection();
39 const { selectedThreadCwd, selectedThreadWorktreePath } = useSelectedThreadWorktree();
40 const runStackedAction = useAtomCommand(
41 vcsActionManager.runStackedAction({
42 environmentId: selectedThread?.environmentId ?? null,
43 cwd: selectedThreadCwd,
44 }),
45 { reportFailure: false },
46 );
47​
48 const selectedThreadGitRootCwd = selectedThreadProject?.workspaceRoot ?? null;
49 const branchTarget = useMemo(
50 () => ({
51 environmentId: selectedThread?.environmentId ?? null,
52 cwd: selectedThreadGitRootCwd,
53 query: null,
54 }),
55 [selectedThread?.environmentId, selectedThreadGitRootCwd],
56 );
57 const branchState = useBranches(branchTarget);
58 const updateThreadGitContext = useCallback(
59 async (
60 thread: NonNullable<typeof selectedThread>,
61 nextState: {
62 readonly branch?: string | null;
63 readonly worktreePath?: string | null;
64 },
65 ) => {
66 return updateThreadMetadata({
67 environmentId: thread.environmentId,
68 input: {
69 threadId: thread.id,
70 ...(nextState.branch !== undefined ? { branch: nextState.branch } : {}),
71 ...(nextState.worktreePath !== undefined ? { worktreePath: nextState.worktreePath } : {}),
72 },
73 });
74 },
75 [updateThreadMetadata],
76 );
77​
78 const refreshSelectedThreadGitStatus = useCallback(
79 async (options?: { readonly quiet?: boolean; readonly cwd?: string | null }) => {
80 if (!selectedThread || !selectedThreadProject) {
81 return null;
82 }
83​
84 const cwd = options?.cwd ?? selectedThreadCwd;
85 if (!cwd) {
86 return null;
87 }
88​
89 const target = { environmentId: selectedThread.environmentId, cwd };
90 const execute = () =>
91 refreshStatus({
92 environmentId: selectedThread.environmentId,
93 input: { cwd },
94 });
95 const result = options?.quiet
96 ? await execute()
97 : await vcsActionManager.track(
98 appAtomRegistry,
99 target,
100 {
101 operation: "refresh_status",
102 label: "Refreshing source control status",
103 },
104 execute,
105 );
106 if (AsyncResult.isFailure(result)) {
107 const error = Cause.squash(result.cause);
108 const message = error instanceof Error ? error.message : "Failed to refresh git status.";
109 setPendingConnectionError(message);
110 return null;
111 }
112 setPendingConnectionError(null);
113 return result.value;
114 },
115 [refreshStatus, selectedThread, selectedThreadCwd, selectedThreadProject],
116 );
117​
118 useEffect(() => {
119 if (!selectedThread || !selectedThreadProject) {
120 return;
121 }
122 void refreshSelectedThreadGitStatus({ quiet: true });
123 }, [refreshSelectedThreadGitStatus, selectedThread, selectedThreadProject]);
124​
125 const runSelectedThreadGitMutation = useCallback(
126 async <T, E>(
127 operation: VcsActionOperation,
128 label: string,
129 execute: (input: {
130 readonly thread: EnvironmentThreadShell;
131 readonly project: EnvironmentProject;
132 readonly cwd: string;
133 }) => Promise<AtomCommandResult<T, E>>,
134 options?: { readonly managedExternally?: boolean },
135 ): Promise<T | null> => {
136 if (!selectedThread || !selectedThreadProject || !selectedThreadCwd) {
137 return null;
138 }
139​
140 const target = {
141 environmentId: selectedThread.environmentId,
142 cwd: selectedThreadCwd,
143 };
144 setPendingConnectionError(null);
145 const run = () =>
146 execute({
147 thread: selectedThread,
148 project: selectedThreadProject,
149 cwd: selectedThreadCwd,
150 });
151 const result =
152 options?.managedExternally === true
153 ? await run()
154 : await vcsActionManager.track(appAtomRegistry, target, { operation, label }, run);
155 if (AsyncResult.isFailure(result)) {
156 const error = Cause.squash(result.cause);
157 const message = error instanceof Error ? error.message : "Git action failed.";
158 setPendingConnectionError(message);
159 showGitActionResult({ type: "error", title: "Git action failed", description: message });
160 return null;
161 }
162 return result.value;
163 },
164 [selectedThread, selectedThreadCwd, selectedThreadProject],
165 );
166​
167 const refreshSelectedThreadBranches = useCallback(async (): Promise<ReadonlyArray<VcsRef>> => {
168 branchState.refresh();
169 return dedupeRemoteBranchesWithLocalMatches(branchState.data?.refs ?? []).filter(
170 (branch) => !branch.isRemote,
171 );
172 }, [branchState]);
173​
174 const syncSelectedThreadBranchState = useCallback(
175 async (input: {
176 readonly thread: EnvironmentThreadShell;
177 readonly cwd: string;
178 readonly nextThreadState?: {
179 readonly branch?: string | null;
180 readonly worktreePath?: string | null;
181 };
182 }): Promise<AtomCommandResult<void, unknown>> => {
183 if (input.nextThreadState) {
184 const updateResult = await updateThreadGitContext(input.thread, input.nextThreadState);
185 if (AsyncResult.isFailure(updateResult)) {
186 return AsyncResult.failure(updateResult.cause);
187 }
188 }
189 branchState.refresh();
190 await refreshSelectedThreadGitStatus({ quiet: true, cwd: input.cwd });
191 return AsyncResult.success(undefined);
192 },
193 [branchState, refreshSelectedThreadGitStatus, updateThreadGitContext],
194 );
195​
196 const onCheckoutSelectedThreadBranch = useCallback(
197 async (branch: string) => {
198 await runSelectedThreadGitMutation(
199 "switch_ref",
200 "Switching branch",
201 async ({ thread, cwd }) => {
202 const result = await switchRef({
203 environmentId: thread.environmentId,
204 input: { cwd, refName: branch },
205 });
206 if (AsyncResult.isFailure(result)) {
207 return result;
208 }
209 const syncResult = await syncSelectedThreadBranchState({
210 thread,
211 cwd,
212 nextThreadState: {
213 branch: result.value.refName ?? thread.branch,
214 worktreePath: selectedThreadWorktreePath,
215 },
216 });
217 return AsyncResult.isFailure(syncResult) ? AsyncResult.failure(syncResult.cause) : result;
218 },
219 );
220 },
221 [
222 runSelectedThreadGitMutation,
223 selectedThreadWorktreePath,
224 syncSelectedThreadBranchState,
225 switchRef,
226 ],
227 );
228​
229 const onCreateSelectedThreadBranch = useCallback(
230 async (branch: string) => {
231 await runSelectedThreadGitMutation(
232 "create_ref",
233 "Creating branch",
234 async ({ thread, cwd }) => {
235 const result = await createRef({
236 environmentId: thread.environmentId,
237 input: { cwd, refName: branch, switchRef: true },
238 });
239 if (AsyncResult.isFailure(result)) {
240 return result;
241 }
242 const syncResult = await syncSelectedThreadBranchState({
243 thread,
244 cwd,
245 nextThreadState: {
246 branch: result.value.refName ?? thread.branch,
247 worktreePath: selectedThreadWorktreePath,
248 },
249 });
250 return AsyncResult.isFailure(syncResult) ? AsyncResult.failure(syncResult.cause) : result;
251 },
252 );
253 },
254 [
255 runSelectedThreadGitMutation,
256 selectedThreadWorktreePath,
257 syncSelectedThreadBranchState,
258 createRef,
259 ],
260 );
261​
262 const onCreateSelectedThreadWorktree = useCallback(
263 async (nextWorktree: { readonly baseBranch: string; readonly newBranch: string }) => {
264 await runSelectedThreadGitMutation(
265 "create_worktree",
266 "Creating worktree",
267 async ({ thread, project }) => {
268 const result = await createWorktree({
269 environmentId: thread.environmentId,
270 input: {
271 cwd: project.workspaceRoot,
272 refName: nextWorktree.baseBranch,
273 newRefName: sanitizeFeatureBranchName(nextWorktree.newBranch),
274 path: null,
275 },
276 });
277 if (AsyncResult.isFailure(result)) {
278 return result;
279 }
280 const syncResult = await syncSelectedThreadBranchState({
281 thread,
282 cwd: result.value.worktree.path,
283 nextThreadState: {
284 branch: result.value.worktree.refName,
285 worktreePath: result.value.worktree.path,
286 },
287 });
288 return AsyncResult.isFailure(syncResult) ? AsyncResult.failure(syncResult.cause) : result;
289 },
290 );
291 },
292 [createWorktree, runSelectedThreadGitMutation, syncSelectedThreadBranchState],
293 );
294​
295 const onPullSelectedThreadBranch = useCallback(async () => {
296 await runSelectedThreadGitMutation(
297 "pull",
298 "Pulling latest changes",
299 async ({ thread, cwd }) => {
300 const result = await pull({
301 environmentId: thread.environmentId,
302 input: { cwd },
303 });
304 if (AsyncResult.isFailure(result)) {
305 return result;
306 }
307 await refreshSelectedThreadGitStatus({ quiet: true, cwd });
308 showGitActionResult({
309 type: "success",
310 title:
311 result.value.status === "skipped_up_to_date"
312 ? "Already up to date"
313 : `Pulled latest on ${result.value.refName}`,
314 });
315 return result;
316 },
317 );
318 }, [pull, refreshSelectedThreadGitStatus, runSelectedThreadGitMutation]);
319​
320 const onRunSelectedThreadGitAction = useCallback(
321 async (input: GitActionRequestInput): Promise<GitRunStackedActionResult | null> => {
322 const actionId = uuidv4();
323 return await runSelectedThreadGitMutation(
324 "run_change_request",
325 "Running source control action",
326 async ({ thread, cwd }) => {
327 const result = await runStackedAction({
328 actionId,
329 action: input.action,
330 ...(input.commitMessage ? { commitMessage: input.commitMessage } : {}),
331 ...(input.featureBranch ? { featureBranch: input.featureBranch } : {}),
332 ...(input.filePaths?.length ? { filePaths: [...input.filePaths] } : {}),
333 });
334 if (AsyncResult.isFailure(result)) {
335 return result;
336 }
337​
338 showGitActionResult({
339 type: "success",
340 title: result.value.toast.title,
341 description: result.value.toast.description,
342 prUrl:
343 result.value.toast.cta.kind === "open_pr" ? result.value.toast.cta.url : undefined,
344 });
345​
346 if (result.value.branch.status === "created" && result.value.branch.name) {
347 const syncResult = await syncSelectedThreadBranchState({
348 thread,
349 cwd,
350 nextThreadState: {
351 branch: result.value.branch.name,
352 worktreePath: selectedThreadWorktreePath,
353 },
354 });
355 if (AsyncResult.isFailure(syncResult)) {
356 return AsyncResult.failure(syncResult.cause);
357 }
358 } else {
359 await refreshSelectedThreadGitStatus({ quiet: true, cwd });
360 }
361 return result;
362 },
363 { managedExternally: true },
364 );
365 },
366 [
367 runStackedAction,
368 refreshSelectedThreadGitStatus,
369 runSelectedThreadGitMutation,
370 selectedThreadWorktreePath,
371 syncSelectedThreadBranchState,
372 ],
373 );
374​
375 return {
376 refreshSelectedThreadGitStatus,
377 refreshSelectedThreadBranches,
378 onCheckoutSelectedThreadBranch,
379 onCreateSelectedThreadBranch,
380 onCreateSelectedThreadWorktree,
381 onPullSelectedThreadBranch,
382 onRunSelectedThreadGitAction,
383 };