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

sourceControlActions.ts

477 lines13.9 KB

1import { useAtomValue } from "@effect/atom-react";
2import {
3 type VcsActionOperation,
4 type VcsActionState,
5 EMPTY_VCS_ACTION_ATOM,
6 EMPTY_VCS_ACTION_STATE,
7 createVcsActionManager,
8 getVcsActionTargetKey,
9 vcsActionStateAtom,
10} from "@t3tools/client-runtime";
11import {
12 type EnvironmentId,
13 type GitActionProgressEvent,
14 type GitRunStackedActionResult,
15 type GitStackedAction,
16 type GitResolvePullRequestResult,
17 type SourceControlCloneProtocol,
18 type SourceControlPublishRepositoryResult,
19 type SourceControlRepositoryVisibility,
20 type ThreadId,
21 type VcsPullResult,
22} from "@t3tools/contracts";
23import {
24 useCallback,
25 useEffect,
26 useMemo,
27 useState,
28 useSyncExternalStore,
29 useTransition,
30} from "react";
31​
32import { ensureEnvironmentApi } from "../environmentApi";
33import { readEnvironmentConnection } from "../environments/runtime";
34import { appAtomRegistry } from "../rpc/atomRegistry";
35import { getVcsStatusSnapshot, refreshVcsStatus } from "./vcsStatusState";
36import { vcsRefManager } from "./vcsRefState";
37​
38type SourceControlActionKind =
39 | "init"
40 | "pull"
41 | "publishRepository"
42 | "runStackedAction"
43 | "preparePullRequestThread";
44​
45interface SourceControlActionScope {
46 readonly environmentId: EnvironmentId | null;
47 readonly cwd: string | null;
49​
50interface SourceControlActionState<TArgs extends ReadonlyArray<unknown>, TResult> {
51 readonly isPending: boolean;
52 readonly error: unknown;
53 readonly run: (...args: TArgs) => Promise<TResult>;
54 readonly resetError: () => void;
56​
57export const vcsActionManager = createVcsActionManager({
58 getRegistry: () => appAtomRegistry,
59 getClient: (environmentId) => {
60 const client = readEnvironmentConnection(environmentId)?.client;
61 return client ? { ...client.vcs, runChangeRequest: client.git.runStackedAction } : null;
62 },
63 onInvalidate: (target) => invalidateSourceControlState(target),
64});
65​
66const actionListeners = new Set<() => void>();
67const activeActionCounts = new Map<string, number>();
68​
69function notifyActionListeners(): void {
70 for (const listener of actionListeners) {
71 listener();
72 }
74​
75function subscribeActionState(listener: () => void): () => void {
76 actionListeners.add(listener);
77 return () => {
78 actionListeners.delete(listener);
79 };
81​
82function actionKey(kind: SourceControlActionKind, scope: SourceControlActionScope): string {
83 return `${kind}:${scope.environmentId ?? ""}:${scope.cwd ?? ""}`;
85​
86function beginAction(key: string): () => void {
87 activeActionCounts.set(key, (activeActionCounts.get(key) ?? 0) + 1);
88 notifyActionListeners();
89 let ended = false;
90 return () => {
91 if (ended) {
92 return;
93 }
94 ended = true;
95 const next = (activeActionCounts.get(key) ?? 1) - 1;
96 if (next <= 0) {
97 activeActionCounts.delete(key);
98 } else {
99 activeActionCounts.set(key, next);
100 }
101 notifyActionListeners();
102 };
104​
105function isAnyActionRunning(
106 kinds: ReadonlyArray<SourceControlActionKind>,
107 scope: SourceControlActionScope,
108): boolean {
109 return kinds.some((kind) => (activeActionCounts.get(actionKey(kind, scope)) ?? 0) > 0);
111​
112function getVcsActionOperationForKind(kind: SourceControlActionKind): VcsActionOperation | null {
113 switch (kind) {
114 case "init":
115 return "init";
116 case "pull":
117 return "pull";
118 case "runStackedAction":
119 return "run_change_request";
120 case "publishRepository":
121 case "preparePullRequestThread":
122 return null;
123 }
125​
126function useVcsActionStateForScope(scope: SourceControlActionScope): VcsActionState {
127 const targetKey = getVcsActionTargetKey(scope);
128 const state = useAtomValue(
129 targetKey !== null ? vcsActionStateAtom(targetKey) : EMPTY_VCS_ACTION_ATOM,
130 );
131 return targetKey === null ? EMPTY_VCS_ACTION_STATE : state;
133​
134export function invalidateSourceControlState(scope?: {
135 readonly environmentId?: EnvironmentId | null;
136 readonly cwd?: string | null;
137}): Promise<void> {
138 const environmentId = scope?.environmentId ?? null;
139 const cwd = scope?.cwd ?? null;
140 if (cwd !== null) {
141 vcsRefManager.invalidateScope({ environmentId, cwd });
142 if (environmentId !== null) {
143 return refreshVcsStatus({ environmentId, cwd }).then(
144 () => undefined,
145 () => undefined,
146 );
147 }
148 return Promise.resolve();
149 }
150​
151 vcsRefManager.invalidate();
152 return Promise.resolve();
154​
155function useSourceControlAction<TArgs extends ReadonlyArray<unknown>, TResult>(input: {
156 readonly kind: SourceControlActionKind;
157 readonly scope: SourceControlActionScope;
158 readonly action: (...args: TArgs) => Promise<TResult>;
159 readonly invalidateOnSuccess?: boolean;
160}): SourceControlActionState<TArgs, TResult> {
161 const { action, invalidateOnSuccess = true, kind, scope } = input;
162 const [error, setError] = useState<unknown>(null);
163 const [activeCount, setActiveCount] = useState(0);
164 const [isTransitionPending, startTransition] = useTransition();
165 const key = actionKey(kind, scope);
166​
167 const resetError = useCallback(() => {
168 startTransition(() => setError(null));
169 }, [startTransition]);
170​
171 const run = useCallback(
172 async (...args: TArgs): Promise<TResult> => {
173 const endAction = beginAction(key);
174 startTransition(() => {
175 setError(null);
176 setActiveCount((count) => count + 1);
177 });
178 try {
179 const result = await action(...args);
180 if (invalidateOnSuccess) {
181 await invalidateSourceControlState(scope);
182 }
183 return result;
184 } catch (nextError) {
185 startTransition(() => setError(nextError));
186 throw nextError;
187 } finally {
188 endAction();
189 startTransition(() => setActiveCount((count) => Math.max(0, count - 1)));
190 }
191 },
192 [action, invalidateOnSuccess, key, scope, startTransition],
193 );
194​
195 return {
196 error,
197 isPending: activeCount > 0 || isTransitionPending,
198 resetError,
199 run,
200 };
202​
203export function useSourceControlActionRunning(
204 scope: SourceControlActionScope,
205 kinds: ReadonlyArray<SourceControlActionKind>,
206): boolean {
207 const stableKinds = useMemo(() => kinds.toSorted(), [kinds]);
208 const appActionRunning = useSyncExternalStore(
209 subscribeActionState,
210 () => isAnyActionRunning(stableKinds, scope),
211 () => false,
212 );
213 const vcsActionState = useVcsActionStateForScope(scope);
214 const vcsActionRunning =
215 vcsActionState.isRunning &&
216 stableKinds.some((kind) => getVcsActionOperationForKind(kind) === vcsActionState.operation);
217​
218 return appActionRunning || vcsActionRunning;
220​
221function useVcsManagerAction<TArgs extends ReadonlyArray<unknown>, TResult>(input: {
222 readonly operation: VcsActionOperation;
223 readonly scope: SourceControlActionScope;
224 readonly unavailableMessage: string;
225 readonly action: (...args: TArgs) => Promise<TResult | null>;
226}): SourceControlActionState<TArgs, TResult> {
227 const { action, operation, scope, unavailableMessage } = input;
228 const vcsActionState = useVcsActionStateForScope(scope);
229 const [error, setError] = useState<unknown>(null);
230 const [isTransitionPending, startTransition] = useTransition();
231​
232 const resetError = useCallback(() => {
233 vcsActionManager.reset(scope);
234 startTransition(() => setError(null));
235 }, [scope, startTransition]);
236​
237 const run = useCallback(
238 async (...args: TArgs): Promise<TResult> => {
239 startTransition(() => setError(null));
240 try {
241 const result = await action(...args);
242 if (result === null) {
243 throw new Error(unavailableMessage);
244 }
245 return result;
246 } catch (nextError) {
247 startTransition(() => setError(nextError));
248 throw nextError;
249 }
250 },
251 [action, startTransition, unavailableMessage],
252 );
253​
254 return {
255 error: error ?? vcsActionState.error,
256 isPending:
257 isTransitionPending || (vcsActionState.isRunning && vcsActionState.operation === operation),
258 resetError,
259 run,
260 };
262​
263export function useVcsInitAction(scope: SourceControlActionScope) {
264 const action = useCallback(async () => {
265 if (!scope.cwd || !scope.environmentId) throw new Error("Git init is unavailable.");
266 return vcsActionManager.init(scope);
267 }, [scope]);
268​
269 return useVcsManagerAction({
270 operation: "init",
271 scope,
272 unavailableMessage: "Git init is unavailable.",
273 action,
274 });
276​
277export function useGitStackedAction(scope: SourceControlActionScope) {
278 const action = useCallback(
279 async ({
280 actionId,
281 action,
282 commitMessage,
283 featureBranch,
284 filePaths,
285 onProgress,
286 }: {
287 actionId: string;
288 action: GitStackedAction;
289 commitMessage?: string;
290 featureBranch?: boolean;
291 filePaths?: string[];
292 onProgress?: (event: GitActionProgressEvent) => void;
293 }): Promise<GitRunStackedActionResult | null> => {
294 if (!scope.cwd || !scope.environmentId) throw new Error("Git action is unavailable.");
295 return vcsActionManager.runChangeRequest(
296 scope,
297 {
298 actionId,
299 action,
300 ...(commitMessage ? { commitMessage } : {}),
301 ...(featureBranch ? { featureBranch: true } : {}),
302 ...(filePaths && filePaths.length > 0 ? { filePaths } : {}),
303 },
304 {
305 gitStatus: getVcsStatusSnapshot(scope).data,
306 ...(onProgress ? { onProgress } : {}),
307 },
308 );
309 },
310 [scope],
311 );
312​
313 return useVcsManagerAction({
314 operation: "run_change_request",
315 scope,
316 unavailableMessage: "Git action is unavailable.",
317 action,
318 });
320​
321export function useVcsPullAction(scope: SourceControlActionScope) {
322 const action = useCallback(async (): Promise<VcsPullResult | null> => {
323 if (!scope.cwd || !scope.environmentId) throw new Error("Git pull is unavailable.");
324 return vcsActionManager.pull(scope);
325 }, [scope]);
326​
327 return useVcsManagerAction({
328 operation: "pull",
329 scope,
330 unavailableMessage: "Git pull is unavailable.",
331 action,
332 });
334​
335export function useSourceControlPublishRepositoryAction(scope: SourceControlActionScope) {
336 const action = useCallback(
337 async (args: {
338 provider: "github" | "gitlab" | "bitbucket" | "azure-devops";
339 repository: string;
340 visibility: SourceControlRepositoryVisibility;
341 remoteName: string;
342 protocol: SourceControlCloneProtocol;
343 }): Promise<SourceControlPublishRepositoryResult> => {
344 if (!scope.cwd || !scope.environmentId) {
345 throw new Error("Repository publishing is unavailable.");
346 }
347 return ensureEnvironmentApi(scope.environmentId).sourceControl.publishRepository({
348 cwd: scope.cwd,
349 ...args,
350 });
351 },
352 [scope],
353 );
354​
355 return useSourceControlAction({
356 kind: "publishRepository",
357 scope,
358 action,
359 });
361​
362export function usePreparePullRequestThreadAction(scope: SourceControlActionScope) {
363 const action = useCallback(
364 async (args: { reference: string; mode: "local" | "worktree"; threadId?: ThreadId }) => {
365 if (!scope.cwd || !scope.environmentId) {
366 throw new Error("Pull request thread preparation is unavailable.");
367 }
368 return ensureEnvironmentApi(scope.environmentId).git.preparePullRequestThread({
369 cwd: scope.cwd,
370 reference: args.reference,
371 mode: args.mode,
372 ...(args.threadId ? { threadId: args.threadId } : {}),
373 });
374 },
375 [scope],
376 );
377​
378 return useSourceControlAction({
379 kind: "preparePullRequestThread",
380 scope,
381 action,
382 });
384​
385interface PullRequestResolutionTarget {
386 readonly environmentId: EnvironmentId | null;
387 readonly cwd: string | null;
388 readonly reference: string | null;
390​
391interface PullRequestResolutionState {
392 readonly data: GitResolvePullRequestResult | null;
393 readonly error: unknown;
394 readonly isPending: boolean;
395 readonly isFetching: boolean;
397​
398const EMPTY_PULL_REQUEST_RESOLUTION: PullRequestResolutionState = {
399 data: null,
400 error: null,
401 isPending: false,
402 isFetching: false,
403};
404​
405const pullRequestResolutionCache = new Map<string, GitResolvePullRequestResult>();
406​
407function pullRequestResolutionKey(target: PullRequestResolutionTarget): string | null {
408 if (!target.environmentId || !target.cwd || !target.reference) {
409 return null;
410 }
411 return `${target.environmentId}:${target.cwd}:${target.reference}`;
413​
414export function readCachedPullRequestResolution(
415 target: PullRequestResolutionTarget,
416): GitResolvePullRequestResult | null {
417 const key = pullRequestResolutionKey(target);
418 return key ? (pullRequestResolutionCache.get(key) ?? null) : null;
420​
421export function usePullRequestResolution(
422 target: PullRequestResolutionTarget,
423): PullRequestResolutionState {
424 const stableTarget = useMemo(
425 () => ({
426 environmentId: target.environmentId,
427 cwd: target.cwd,
428 reference: target.reference,
429 }),
430 [target.cwd, target.environmentId, target.reference],
431 );
432 const key = pullRequestResolutionKey(stableTarget);
433 const [state, setState] = useState<PullRequestResolutionState>(() => {
434 const cached = readCachedPullRequestResolution(stableTarget);
435 return cached
436 ? { data: cached, error: null, isPending: false, isFetching: false }
437 : EMPTY_PULL_REQUEST_RESOLUTION;
438 });
439​
440 useEffect(() => {
441 if (!key || !stableTarget.environmentId || !stableTarget.cwd || !stableTarget.reference) {
442 setState(EMPTY_PULL_REQUEST_RESOLUTION);
443 return;
444 }
445​
446 const cached = pullRequestResolutionCache.get(key) ?? null;
447 setState({
448 data: cached,
449 error: null,
450 isPending: cached === null,
451 isFetching: true,
452 });
453​
454 let cancelled = false;
455 ensureEnvironmentApi(stableTarget.environmentId)
456 .git.resolvePullRequest({ cwd: stableTarget.cwd, reference: stableTarget.reference })
457 .then((result) => {
458 if (cancelled) {
459 return;
460 }
461 pullRequestResolutionCache.set(key, result);
462 setState({ data: result, error: null, isPending: false, isFetching: false });
463 })
464 .catch((error: unknown) => {
465 if (cancelled) {
466 return;
467 }
468 setState({ data: cached, error, isPending: false, isFetching: false });
469 });
470​
471 return () => {
472 cancelled = true;
473 };
474 }, [key, stableTarget]);
475​
476 return state;