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