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