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

sourceControlActions.ts

392 lines11.5 KB

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;
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;
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 };
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 };
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 );
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 });
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 });
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 threadId?: ThreadId;
222 onProgress?: (event: GitActionProgressEvent) => void;
223 }) => {
224 if (resolveScope(scope) === null) {
225 return AsyncResult.failure<never, VcsActionUnavailableError>(
226 Cause.fail(
227 new VcsActionUnavailableError({
228 operation: "run_change_request",
229 environmentId: scope.environmentId,
230 cwd: scope.cwd,
231 }),
232 ),
233 );
234 }
235 return runStackedAction({
236 actionId: input.actionId,
237 action: input.action,
238 ...(input.commitMessage ? { commitMessage: input.commitMessage } : {}),
239 ...(input.featureBranch ? { featureBranch: true } : {}),
240 ...(input.filePaths?.length ? { filePaths: input.filePaths } : {}),
241 ...(input.threadId !== undefined ? { threadId: input.threadId } : {}),
242 ...(input.onProgress ? { onProgress: input.onProgress } : {}),
243 });
244 },
245 [runStackedAction, scope],
246 );
247​
248 return useAction({
249 kind: "runStackedAction",
250 label: "Running source control action",
251 scope,
252 action,
253 onSuccess: status.refresh,
254 managedExternally: true,
255 });
257​
258export function useSourceControlPublishRepositoryAction(scope: SourceControlActionScope) {
259 const publishRepository = useAtomCommand(sourceControlEnvironment.publishRepository, {
260 reportFailure: false,
261 });
262 const status = useEnvironmentQuery(
263 scope.environmentId !== null && scope.cwd !== null
264 ? vcsEnvironment.status({
265 environmentId: scope.environmentId,
266 input: { cwd: scope.cwd },
267 })
268 : null,
269 );
270 const action = useCallback(
271 async (input: {
272 provider: "github" | "gitlab" | "bitbucket" | "azure-devops";
273 repository: string;
274 visibility: SourceControlRepositoryVisibility;
275 remoteName: string;
276 protocol: SourceControlCloneProtocol;
277 }) => {
278 const target = resolveScope(scope);
279 if (target === null) {
280 return AsyncResult.failure<never, VcsActionUnavailableError>(
281 Cause.fail(
282 new VcsActionUnavailableError({
283 operation: "publish_repository",
284 environmentId: scope.environmentId,
285 cwd: scope.cwd,
286 }),
287 ),
288 );
289 }
290 return publishRepository({
291 environmentId: target.environmentId,
292 input: {
293 cwd: target.cwd,
294 ...input,
295 },
296 });
297 },
298 [publishRepository, scope],
299 );
300 return useAction({
301 kind: "publishRepository",
302 label: "Publishing repository",
303 scope,
304 action,
305 onSuccess: status.refresh,
306 });
308​
309export function usePreparePullRequestThreadAction(scope: SourceControlActionScope) {
310 const preparePullRequestThread = useAtomCommand(gitEnvironment.preparePullRequestThread, {
311 reportFailure: false,
312 });
313 const action = useCallback(
314 async (input: { reference: string; mode: "local" | "worktree"; threadId?: ThreadId }) => {
315 const target = resolveScope(scope);
316 if (target === null) {
317 return AsyncResult.failure<never, VcsActionUnavailableError>(
318 Cause.fail(
319 new VcsActionUnavailableError({
320 operation: "prepare_pull_request_thread",
321 environmentId: scope.environmentId,
322 cwd: scope.cwd,
323 }),
324 ),
325 );
326 }
327 return preparePullRequestThread({
328 environmentId: target.environmentId,
329 input: {
330 cwd: target.cwd,
331 reference: input.reference,
332 mode: input.mode,
333 ...(input.threadId ? { threadId: input.threadId } : {}),
334 },
335 });
336 },
337 [preparePullRequestThread, scope],
338 );
339 return useAction({
340 kind: "preparePullRequestThread",
341 label: "Preparing pull request thread",
342 scope,
343 action,
344 });
346​
347export interface PullRequestResolutionTarget {
348 readonly environmentId: EnvironmentId | null;
349 readonly cwd: string | null;
350 readonly reference: string | null;
352​
353export function readCachedPullRequestResolution(
354 target: PullRequestResolutionTarget,
355): GitResolvePullRequestResult | null {
356 if (target.environmentId === null || target.cwd === null || target.reference === null) {
357 return null;
358 }
359 return Option.getOrNull(
360 AsyncResult.value(
361 appAtomRegistry.get(
362 gitEnvironment.pullRequestResolution({
363 environmentId: target.environmentId,
364 input: { cwd: target.cwd, reference: target.reference },
365 }),
366 ),
367 ),
368 );
370​
371export function usePullRequestResolutionState(target: PullRequestResolutionTarget) {
372 const query = useEnvironmentQuery(
373 target.environmentId !== null && target.cwd !== null && target.reference !== null
374 ? gitEnvironment.pullRequestResolution({
375 environmentId: target.environmentId,
376 input: {
377 cwd: target.cwd,
378 reference: target.reference,
379 },
380 })
381 : null,
382 );
383 const cached = readCachedPullRequestResolution(target);
384​
385 return {
386 data: query.data ?? cached,
387 error: query.error,
388 isPending: query.isPending && cached === null,
389 isFetching: query.isPending,
390 refresh: query.refresh,
391 };