Open History to see the last commit
1import { useAtomValue } from "@effect/atom-react";
2import type {
3 AtomCommandFailure,
4 AtomCommandResult,
5 AtomCommandSuccess,
6} from "@t3tools/client-runtime/state/runtime";
7import {
8 VcsActionUnavailableError,
9 type VcsActionOperation,
10 type RunVcsStackedActionInput,
11} from "@t3tools/client-runtime/state/vcs";
12import type {
13 EnvironmentId,
14 GitResolvePullRequestResult,
15 SourceControlCloneProtocol,
16 SourceControlRepositoryVisibility,
17 ThreadId,
18} from "@t3tools/contracts";
19import * as Cause from "effect/Cause";
20import * as Option from "effect/Option";
21import { AsyncResult } from "effect/unstable/reactivity";
22import { useCallback } from "react";
23
24import { appAtomRegistry } from "../rpc/atomRegistry";
25import { gitEnvironment } from "./git";
26import { useEnvironmentQuery } from "./query";
27import { sourceControlEnvironment } from "./sourceControl";
28import { useAtomCommand } from "./use-atom-command";
29import { vcsActionManager, vcsEnvironment } from "./vcs";
30
31export type SourceControlActionKind =
32 | "init"
33 | "pull"
34 | "publishRepository"
35 | "runStackedAction"
36 | "preparePullRequestThread";
37
38export interface SourceControlActionScope {
39 readonly environmentId: EnvironmentId | null;
40 readonly cwd: string | null;
41}
42
43interface SourceControlActionState<
44 TArgs extends ReadonlyArray<unknown>,
45 R extends AtomCommandResult<unknown, unknown>,
46> {
47 readonly isPending: boolean;
48 readonly error: unknown;
49 readonly run: (
50 ...args: TArgs
51 ) => Promise<
52 AtomCommandResult<AtomCommandSuccess<R>, AtomCommandFailure<R> | VcsActionUnavailableError>
53 >;
54 readonly resetError: () => void;
55}
56
57const ACTION_OPERATION = {
58 init: "init",
59 pull: "pull",
60 publishRepository: "publish_repository",
61 runStackedAction: "run_change_request",
62 preparePullRequestThread: "prepare_pull_request_thread",
63} as const satisfies Record<SourceControlActionKind, VcsActionOperation>;
64
65function useAction<
66 TArgs extends ReadonlyArray<unknown>,
67 R extends AtomCommandResult<unknown, unknown>,
68>(input: {
69 readonly kind: SourceControlActionKind;
70 readonly label: string;
71 readonly scope: SourceControlActionScope;
72 readonly action: (...args: TArgs) => Promise<R>;
73 readonly onSuccess?: () => void;
74 readonly managedExternally?: boolean;
75}): SourceControlActionState<TArgs, R> {
76 const operation = ACTION_OPERATION[input.kind];
77 const state = useAtomValue(vcsActionManager.stateAtom(input.scope));
78 const ownsState = state.operation === operation;
79
80 const resetError = useCallback(() => {
81 vcsActionManager.resetError(appAtomRegistry, input.scope, operation);
82 }, [input.scope, operation]);
83
84 const run = useCallback(
85 async (...args: TArgs) => {
86 const execute = async (): Promise<
87 AtomCommandResult<AtomCommandSuccess<R>, AtomCommandFailure<R>>
88 > => {
89 const result = await input.action(...args);
90 if (AsyncResult.isSuccess(result)) {
91 input.onSuccess?.();
92 }
93 return result as AtomCommandResult<AtomCommandSuccess<R>, AtomCommandFailure<R>>;
94 };
95 return input.managedExternally === true
96 ? execute()
97 : vcsActionManager.track(
98 appAtomRegistry,
99 input.scope,
100 {
101 operation,
102 label: input.label,
103 },
104 execute,
105 );
106 },
107 [input.action, input.label, input.managedExternally, input.onSuccess, input.scope, operation],
108 );
109
110 return {
111 error: ownsState ? state.error : null,
112 isPending: ownsState && state.isRunning,
113 resetError,
114 run,
115 };
116}
117
118function resolveScope(scope: SourceControlActionScope) {
119 if (scope.environmentId === null || scope.cwd === null) {
120 return null;
121 }
122 return {
123 environmentId: scope.environmentId,
124 cwd: scope.cwd,
125 };
126}
127
128export function useSourceControlActionRunning(
129 scope: SourceControlActionScope,
130 kinds: ReadonlyArray<SourceControlActionKind>,
131): boolean {
132 const state = useAtomValue(vcsActionManager.stateAtom(scope));
133 return (
134 state.isRunning &&
135 state.operation !== null &&
136 kinds.some((kind) => ACTION_OPERATION[kind] === state.operation)
137 );
138}
139
140export function useVcsInitAction(scope: SourceControlActionScope) {
141 const init = useAtomCommand(vcsEnvironment.init, { reportFailure: false });
142 const action = useCallback(async () => {
143 const target = resolveScope(scope);
144 if (target === null) {
145 return AsyncResult.failure<never, VcsActionUnavailableError>(
146 Cause.fail(
147 new VcsActionUnavailableError({
148 operation: "init",
149 environmentId: scope.environmentId,
150 cwd: scope.cwd,
151 }),
152 ),
153 );
154 }
155 return init({
156 environmentId: target.environmentId,
157 input: { cwd: target.cwd },
158 });
159 }, [init, scope]);
160 return useAction({ kind: "init", label: "Initializing repository", scope, action });
161}
162
163export function useVcsPullAction(scope: SourceControlActionScope) {
164 const pull = useAtomCommand(vcsEnvironment.pull, { reportFailure: false });
165 const status = useEnvironmentQuery(
166 scope.environmentId !== null && scope.cwd !== null
167 ? vcsEnvironment.status({
168 environmentId: scope.environmentId,
169 input: { cwd: scope.cwd },
170 })
171 : null,
172 );
173 const action = useCallback(async () => {
174 const target = resolveScope(scope);
175 if (target === null) {
176 return AsyncResult.failure<never, VcsActionUnavailableError>(
177 Cause.fail(
178 new VcsActionUnavailableError({
179 operation: "pull",
180 environmentId: scope.environmentId,
181 cwd: scope.cwd,
182 }),
183 ),
184 );
185 }
186 return pull({
187 environmentId: target.environmentId,
188 input: { cwd: target.cwd },
189 });
190 }, [pull, scope]);
191 return useAction({
192 kind: "pull",
193 label: "Pulling latest changes...",
194 scope,
195 action,
196 onSuccess: status.refresh,
197 });
198}
199
200export function useGitStackedAction(scope: SourceControlActionScope) {
201 const runStackedAction = useAtomCommand(vcsActionManager.runStackedAction(scope), {
202 reportFailure: false,
203 });
204 const status = useEnvironmentQuery(
205 scope.environmentId !== null && scope.cwd !== null
206 ? vcsEnvironment.status({
207 environmentId: scope.environmentId,
208 input: { cwd: scope.cwd },
209 })
210 : null,
211 );
212
213 const action = useCallback(
214 async (input: RunVcsStackedActionInput) => {
215 if (resolveScope(scope) === null) {
216 return AsyncResult.failure<never, VcsActionUnavailableError>(
217 Cause.fail(
218 new VcsActionUnavailableError({
219 operation: "run_change_request",
220 environmentId: scope.environmentId,
221 cwd: scope.cwd,
222 }),
223 ),
224 );
225 }
226 return runStackedAction(input);
227 },
228 [runStackedAction, scope],
229 );
230
231 return useAction({
232 kind: "runStackedAction",
233 label: "Running source control action",
234 scope,
235 action,
236 onSuccess: status.refresh,
237 managedExternally: true,
238 });
239}
240
241export function useSourceControlPublishRepositoryAction(scope: SourceControlActionScope) {
242 const publishRepository = useAtomCommand(sourceControlEnvironment.publishRepository, {
243 reportFailure: false,
244 });
245 const status = useEnvironmentQuery(
246 scope.environmentId !== null && scope.cwd !== null
247 ? vcsEnvironment.status({
248 environmentId: scope.environmentId,
249 input: { cwd: scope.cwd },
250 })
251 : null,
252 );
253 const action = useCallback(
254 async (input: {
255 provider: "github" | "gitlab" | "forgejo" | "bitbucket" | "azure-devops";
256 repository: string;
257 visibility: SourceControlRepositoryVisibility;
258 remoteName: string;
259 protocol: SourceControlCloneProtocol;
260 }) => {
261 const target = resolveScope(scope);
262 if (target === null) {
263 return AsyncResult.failure<never, VcsActionUnavailableError>(
264 Cause.fail(
265 new VcsActionUnavailableError({
266 operation: "publish_repository",
267 environmentId: scope.environmentId,
268 cwd: scope.cwd,
269 }),
270 ),
271 );
272 }
273 return publishRepository({
274 environmentId: target.environmentId,
275 input: {
276 cwd: target.cwd,
277 ...input,
278 },
279 });
280 },
281 [publishRepository, scope],
282 );
283 return useAction({
284 kind: "publishRepository",
285 label: "Publishing repository",
286 scope,
287 action,
288 onSuccess: status.refresh,
289 });
290}
291
292export function usePreparePullRequestThreadAction(scope: SourceControlActionScope) {
293 const preparePullRequestThread = useAtomCommand(gitEnvironment.preparePullRequestThread, {
294 reportFailure: false,
295 });
296 const action = useCallback(
297 async (input: { reference: string; mode: "local" | "worktree"; threadId?: ThreadId }) => {
298 const target = resolveScope(scope);
299 if (target === null) {
300 return AsyncResult.failure<never, VcsActionUnavailableError>(
301 Cause.fail(
302 new VcsActionUnavailableError({
303 operation: "prepare_pull_request_thread",
304 environmentId: scope.environmentId,
305 cwd: scope.cwd,
306 }),
307 ),
308 );
309 }
310 return preparePullRequestThread({
311 environmentId: target.environmentId,
312 input: {
313 cwd: target.cwd,
314 reference: input.reference,
315 mode: input.mode,
316 ...(input.threadId ? { threadId: input.threadId } : {}),
317 },
318 });
319 },
320 [preparePullRequestThread, scope],
321 );
322 return useAction({
323 kind: "preparePullRequestThread",
324 label: "Preparing pull request thread",
325 scope,
326 action,
327 });
328}
329
330export interface PullRequestResolutionTarget {
331 readonly environmentId: EnvironmentId | null;
332 readonly cwd: string | null;
333 readonly reference: string | null;
334}
335
336export function readCachedPullRequestResolution(
337 target: PullRequestResolutionTarget,
338): GitResolvePullRequestResult | null {
339 if (target.environmentId === null || target.cwd === null || target.reference === null) {
340 return null;
341 }
342 return Option.getOrNull(
343 AsyncResult.value(
344 appAtomRegistry.get(
345 gitEnvironment.pullRequestResolution({
346 environmentId: target.environmentId,
347 input: { cwd: target.cwd, reference: target.reference },
348 }),
349 ),
350 ),
351 );
352}
353
354export function usePullRequestResolutionState(target: PullRequestResolutionTarget) {
355 const query = useEnvironmentQuery(
356 target.environmentId !== null && target.cwd !== null && target.reference !== null
357 ? gitEnvironment.pullRequestResolution({
358 environmentId: target.environmentId,
359 input: {
360 cwd: target.cwd,
361 reference: target.reference,
362 },
363 })
364 : null,
365 );
366 const cached = readCachedPullRequestResolution(target);
367
368 return {
369 data: query.data ?? cached,
370 error: query.error,
371 isPending: query.isPending && cached === null,
372 isFetching: query.isPending,
373 refresh: query.refresh,
374 };
375}