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

sourceControlActions.ts

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