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

sourceControlActions.ts

409 lines11.8 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 SourceControlProviderKind,
20 type SourceControlRepositoryVisibility,
21 type ThreadId,
22} from "@t3tools/contracts";
23import * as Cause from "effect/Cause";
24import * as Option from "effect/Option";
25import { AsyncResult } from "effect/reactivity";
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";
34import { suggestAppAccessForRemote } from "../components/sourceControlAppAccessToast";
35​
36export type SourceControlActionKind =
37 | "init"
38 | "pull"
39 | "publishRepository"
40 | "runStackedAction"
41 | "preparePullRequestThread";
42​
43export interface SourceControlActionScope {
44 readonly environmentId: EnvironmentId | null;
45 readonly cwd: string | null;
47​
48interface SourceControlActionState<
49 TArgs extends ReadonlyArray<unknown>,
50 R extends AtomCommandResult<unknown, unknown>,
51> {
52 readonly isPending: boolean;
53 readonly isAllowed: boolean;
54 readonly error: unknown;
55 readonly run: (
56 ...args: TArgs
57 ) => Promise<
58 AtomCommandResult<
59 AtomCommandSuccess<R>,
60 AtomCommandFailure<R> | VcsActionUnavailableError | EnvironmentAuthorizationError
61 >
62 >;
63 readonly resetError: () => void;
65​
66const ACTION_OPERATION = {
67 init: "init",
68 pull: "pull",
69 publishRepository: "publish_repository",
70 runStackedAction: "run_change_request",
71 preparePullRequestThread: "prepare_pull_request_thread",
72} as const satisfies Record<SourceControlActionKind, VcsActionOperation>;
73​
74function useAction<
75 TArgs extends ReadonlyArray<unknown>,
76 R extends AtomCommandResult<unknown, unknown>,
77>(input: {
78 readonly kind: SourceControlActionKind;
79 readonly label: string;
80 readonly scope: SourceControlActionScope;
81 readonly action: (...args: TArgs) => Promise<R>;
82 readonly onSuccess?: () => void;
83 readonly managedExternally?: boolean;
84}): SourceControlActionState<TArgs, R> {
85 const isAllowed = useEnvironmentScope(input.scope.environmentId, AuthSourceControlWriteScope);
86 const operation = ACTION_OPERATION[input.kind];
87 const state = useAtomValue(vcsActionManager.stateAtom(input.scope));
88 const ownsState = state.operation === operation;
89​
90 const resetError = () => {
91 vcsActionManager.resetError(appAtomRegistry, input.scope, operation);
92 };
93​
94 const run = 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​
130 return {
131 isAllowed,
132 error: ownsState ? state.error : null,
133 isPending: ownsState && state.isRunning,
134 resetError,
135 run,
136 };
138​
139function resolveScope(scope: SourceControlActionScope) {
140 if (scope.environmentId === null || scope.cwd === null) {
141 return null;
142 }
143 return {
144 environmentId: scope.environmentId,
145 cwd: scope.cwd,
146 };
148​
149export function useSourceControlActionRunning(
150 scope: SourceControlActionScope,
151 kinds: ReadonlyArray<SourceControlActionKind>,
152): boolean {
153 const state = useAtomValue(vcsActionManager.stateAtom(scope));
154 return (
155 state.isRunning &&
156 state.operation !== null &&
157 kinds.some((kind) => ACTION_OPERATION[kind] === state.operation)
158 );
160​
161export function useVcsInitAction(scope: SourceControlActionScope) {
162 const init = useAtomCommand(vcsEnvironment.init, { reportFailure: false });
163 const action = async () => {
164 const target = resolveScope(scope);
165 if (target === null) {
166 return AsyncResult.failure<never, VcsActionUnavailableError>(
167 Cause.fail(
168 new VcsActionUnavailableError({
169 operation: "init",
170 environmentId: scope.environmentId,
171 cwd: scope.cwd,
172 }),
173 ),
174 );
175 }
176 return init({
177 environmentId: target.environmentId,
178 input: { cwd: target.cwd },
179 });
180 };
181 return useAction({ kind: "init", label: "Initializing repository", scope, action });
183​
184export function useVcsPullAction(scope: SourceControlActionScope) {
185 const pull = useAtomCommand(vcsEnvironment.pull, { reportFailure: false });
186 const status = useEnvironmentQuery(
187 scope.environmentId !== null && scope.cwd !== null
188 ? vcsEnvironment.status({
189 environmentId: scope.environmentId,
190 input: { cwd: scope.cwd },
191 })
192 : null,
193 );
194 const action = async () => {
195 const target = resolveScope(scope);
196 if (target === null) {
197 return AsyncResult.failure<never, VcsActionUnavailableError>(
198 Cause.fail(
199 new VcsActionUnavailableError({
200 operation: "pull",
201 environmentId: scope.environmentId,
202 cwd: scope.cwd,
203 }),
204 ),
205 );
206 }
207 return pull({
208 environmentId: target.environmentId,
209 input: { cwd: target.cwd },
210 });
211 };
212 return useAction({
213 kind: "pull",
214 label: "Pulling latest changes...",
215 scope,
216 action,
217 onSuccess: status.refresh,
218 });
220​
221export function useGitStackedAction(scope: SourceControlActionScope) {
222 const runStackedAction = useAtomCommand(vcsActionManager.runStackedAction(scope), {
223 reportFailure: false,
224 });
225 const status = useEnvironmentQuery(
226 scope.environmentId !== null && scope.cwd !== null
227 ? vcsEnvironment.status({
228 environmentId: scope.environmentId,
229 input: { cwd: scope.cwd },
230 })
231 : null,
232 );
233​
234 const action = async (input: RunVcsStackedActionInput) => {
235 if (resolveScope(scope) === null) {
236 return AsyncResult.failure<never, VcsActionUnavailableError>(
237 Cause.fail(
238 new VcsActionUnavailableError({
239 operation: "run_change_request",
240 environmentId: scope.environmentId,
241 cwd: scope.cwd,
242 }),
243 ),
244 );
245 }
246 return runStackedAction(input);
247 };
248​
249 return useAction({
250 kind: "runStackedAction",
251 label: "Running source control action",
252 scope,
253 action,
254 onSuccess: status.refresh,
255 managedExternally: true,
256 });
258​
259export function useSourceControlPublishRepositoryAction(scope: SourceControlActionScope) {
260 const publishRepository = useAtomCommand(sourceControlEnvironment.publishRepository, {
261 reportFailure: false,
262 });
263 const status = useEnvironmentQuery(
264 scope.environmentId !== null && scope.cwd !== null
265 ? vcsEnvironment.status({
266 environmentId: scope.environmentId,
267 input: { cwd: scope.cwd },
268 })
269 : null,
270 );
271 const action = async (input: {
272 provider: SourceControlProviderKind;
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 const result = await publishRepository({
291 environmentId: target.environmentId,
292 input: {
293 cwd: target.cwd,
294 ...input,
295 },
296 });
297 if (result._tag === "Success") {
298 void suggestAppAccessForRemote(target.environmentId, result.value.remoteUrl);
299 }
300 return result;
301 };
302 return useAction({
303 kind: "publishRepository",
304 label: "Publishing repository",
305 scope,
306 action,
307 onSuccess: status.refresh,
308 });
310​
311export function usePreparePullRequestThreadAction(scope: SourceControlActionScope) {
312 const preparePullRequestThread = useAtomCommand(gitEnvironment.preparePullRequestThread, {
313 reportFailure: false,
314 });
315 const action = async (input: {
316 reference: string;
317 mode: "local" | "worktree";
318 threadId?: ThreadId;
319 }) => {
320 const target = resolveScope(scope);
321 if (target === null) {
322 return AsyncResult.failure<never, VcsActionUnavailableError>(
323 Cause.fail(
324 new VcsActionUnavailableError({
325 operation: "prepare_pull_request_thread",
326 environmentId: scope.environmentId,
327 cwd: scope.cwd,
328 }),
329 ),
330 );
331 }
332 if (
333 input.mode === "worktree" &&
334 input.threadId !== undefined &&
335 !readEnvironmentScope(target.environmentId, AuthOrchestrationOperateScope)
336 ) {
337 return AsyncResult.failure<never, EnvironmentAuthorizationError>(
338 Cause.fail(
339 new EnvironmentAuthorizationError({
340 requiredScope: AuthOrchestrationOperateScope,
341 message: "This connection cannot change threads.",
342 }),
343 ),
344 );
345 }
346 return preparePullRequestThread({
347 environmentId: target.environmentId,
348 input: {
349 cwd: target.cwd,
350 reference: input.reference,
351 mode: input.mode,
352 ...(input.threadId ? { threadId: input.threadId } : {}),
353 },
354 });
355 };
356 return useAction({
357 kind: "preparePullRequestThread",
358 label: "Preparing pull request thread",
359 scope,
360 action,
361 });
363​
364export interface PullRequestResolutionTarget {
365 readonly environmentId: EnvironmentId | null;
366 readonly cwd: string | null;
367 readonly reference: string | null;
369​
370export function readCachedPullRequestResolution(
371 target: PullRequestResolutionTarget,
372): GitResolvePullRequestResult | null {
373 if (target.environmentId === null || target.cwd === null || target.reference === null) {
374 return null;
375 }
376 return Option.getOrNull(
377 AsyncResult.value(
378 appAtomRegistry.get(
379 gitEnvironment.pullRequestResolution({
380 environmentId: target.environmentId,
381 input: { cwd: target.cwd, reference: target.reference },
382 }),
383 ),
384 ),
385 );
387​
388export function usePullRequestResolutionState(target: PullRequestResolutionTarget) {
389 const query = useEnvironmentQuery(
390 target.environmentId !== null && target.cwd !== null && target.reference !== null
391 ? gitEnvironment.pullRequestResolution({
392 environmentId: target.environmentId,
393 input: {
394 cwd: target.cwd,
395 reference: target.reference,
396 },
397 })
398 : null,
399 );
400 const cached = readCachedPullRequestResolution(target);
401​
402 return {
403 data: query.data ?? cached,
404 error: query.error,
405 isPending: query.isPending && cached === null,
406 isFetching: query.isPending,
407 refresh: query.refresh,
408 };