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

GitActionsControl.logic.ts

546 lines15.0 KB

1import type {
2 GitRunStackedActionResult,
3 GitStackedAction,
4 ReviewDiffPreviewSource,
5 VcsStatusResult,
6} from "@t3tools/contracts";
7import { isTemporaryWorktreeBranch } from "@t3tools/shared/git";
8import type { ChangeRequestTerminology } from "@t3tools/client-runtime/source-control-clients";
9import {
10 changeRequestTerminologyFor,
11 type DefaultBranchActionDialogCopy,
12 type DefaultBranchConfirmableAction,
13 type GitActionIconName,
14 type GitDialogAction,
15} from "@t3tools/client-runtime/state/vcs";
16​
17export {
18 requiresDefaultBranchConfirmation,
19 type DefaultBranchConfirmableAction,
20 type GitActionIconName,
21} from "@t3tools/client-runtime/state/vcs";
22​
23export interface GitActionMenuItem {
24 id: "commit" | "push" | "pr";
25 label: string;
26 disabled: boolean;
27 icon: GitActionIconName;
28 kind: "open_dialog";
29 dialogAction?: GitDialogAction;
31​
32export interface GitQuickAction {
33 label: string;
34 disabled: boolean;
35 kind: "run_action" | "run_pull" | "open_publish" | "show_hint";
36 action?: GitStackedAction;
37 hint?: string;
39​
40export interface GitActionProgressPresentation {
41 readonly status: string;
42 readonly output: string | null;
43 readonly startedAtMs: number | null;
45​
46export interface GitActionResultToastTiming {
47 readonly timeout: 0;
48 readonly dismissAfterVisibleMs: number | null;
50​
51export const GIT_ACTION_SUCCESS_VISIBLE_MS = 10_000;
52​
53export function resolveGitActionResultToastTiming(
54 type: "error" | "success",
55): GitActionResultToastTiming {
56 return {
57 timeout: 0,
58 dismissAfterVisibleMs: type === "success" ? GIT_ACTION_SUCCESS_VISIBLE_MS : null,
59 };
61​
62export function resolveGitActionProgressPresentation(input: {
63 readonly isRunning: boolean;
64 readonly operation: string | null;
65 readonly currentLabel: string | null;
66 readonly lastOutputLine: string | null;
67 readonly phaseStartedAtMs: number | null;
68 readonly hookStartedAtMs: number | null;
69}): GitActionProgressPresentation | null {
70 if (
71 !input.isRunning ||
72 (input.operation !== "run_change_request" && input.operation !== "pull")
73 ) {
74 return null;
75 }
76​
77 const currentLabel = input.currentLabel?.trim();
78 const output = input.lastOutputLine?.trim();
79 const isPull = input.operation === "pull";
80 return {
81 status:
82 currentLabel && currentLabel !== "Running source control action"
83 ? currentLabel
84 : isPull
85 ? "Pulling latest changes..."
86 : "Starting source control action...",
87 output: !isPull && output ? output : null,
88 startedAtMs: isPull
89 ? input.phaseStartedAtMs
90 : (input.hookStartedAtMs ?? input.phaseStartedAtMs),
91 };
93​
94export function formatGitActionElapsed(startedAtMs: number | null, nowMs: number): string | null {
95 if (startedAtMs === null) {
96 return null;
97 }
98​
99 const elapsedSeconds = Math.max(0, Math.floor((nowMs - startedAtMs) / 1_000));
100 if (elapsedSeconds < 60) {
101 return `${elapsedSeconds}s`;
102 }
103​
104 const minutes = Math.floor(elapsedSeconds / 60);
105 const seconds = elapsedSeconds % 60;
106 return `${minutes}m ${seconds}s`;
108​
109export function buildMenuItems(
110 gitStatus: VcsStatusResult | null,
111 isBusy: boolean,
112 hasPrimaryRemote = true,
113): GitActionMenuItem[] {
114 if (!gitStatus) return [];
115 const terminology = changeRequestTerminologyFor(gitStatus);
116​
117 const hasBranch = gitStatus.refName !== null;
118 const hasChanges = gitStatus.hasWorkingTreeChanges;
119 const hasOpenPr = gitStatus.pr?.state === "open";
120 const isBehind = gitStatus.behindCount > 0;
121 const hasDefaultBranchDelta = (gitStatus.aheadOfDefaultCount ?? gitStatus.aheadCount) > 0;
122 const canPushWithoutUpstream = hasPrimaryRemote && !gitStatus.hasUpstream;
123 const canCommit = !isBusy && hasChanges;
124 const canPush =
125 !isBusy &&
126 hasBranch &&
127 !isBehind &&
128 gitStatus.aheadCount > 0 &&
129 (gitStatus.hasUpstream || canPushWithoutUpstream);
130 const canCreatePr =
131 !isBusy &&
132 hasBranch &&
133 !hasOpenPr &&
134 hasDefaultBranchDelta &&
135 !isBehind &&
136 (gitStatus.hasUpstream || canPushWithoutUpstream);
137​
138 const commitItem: GitActionMenuItem = {
139 id: "commit",
140 label: "Commit",
141 disabled: !canCommit,
142 icon: "commit",
143 kind: "open_dialog",
144 dialogAction: "commit",
145 };
146​
147 if (!hasPrimaryRemote) {
148 return [commitItem];
149 }
150​
151 const pushItem: GitActionMenuItem = {
152 id: "push",
153 label: "Push",
154 disabled: !canPush,
155 icon: "push",
156 kind: "open_dialog",
157 dialogAction: "push",
158 };
159​
160 if (hasOpenPr) {
161 return [commitItem, pushItem];
162 }
163​
164 return [
165 commitItem,
166 pushItem,
167 {
168 id: "pr",
169 label: `Create ${terminology.shortLabel}`,
170 disabled: !canCreatePr,
171 icon: "pr",
172 kind: "open_dialog",
173 dialogAction: "create_pr",
174 },
175 ];
177​
178export function getMenuActionDisabledReason({
179 item,
180 gitStatus,
181 isBusy,
182 hasPrimaryRemote,
183}: {
184 item: GitActionMenuItem;
185 gitStatus: VcsStatusResult | null;
186 isBusy: boolean;
187 hasPrimaryRemote: boolean;
188}): string | null {
189 if (!item.disabled) return null;
190 if (isBusy) return "Git action in progress.";
191 if (!gitStatus) return "Git status is unavailable.";
192​
193 const hasBranch = gitStatus.refName !== null;
194 const hasChanges = gitStatus.hasWorkingTreeChanges;
195 const isAhead = gitStatus.aheadCount > 0;
196 const isBehind = gitStatus.behindCount > 0;
197 const terminology = changeRequestTerminologyFor(gitStatus);
198​
199 if (item.id === "commit") {
200 if (!hasChanges) {
201 return "Worktree is clean. Make changes before committing.";
202 }
203 return "Commit is currently unavailable.";
204 }
205​
206 if (item.id === "push") {
207 if (!hasBranch) {
208 return "Detached HEAD: check out a branch before pushing.";
209 }
210 if (isBehind) {
211 return "Branch is behind upstream. Pull/rebase before pushing.";
212 }
213 if (!gitStatus.hasUpstream && !hasPrimaryRemote) {
214 return 'Add an "origin" remote before pushing.';
215 }
216 if (!isAhead) {
217 return "No local commits to push.";
218 }
219 return "Push is currently unavailable.";
220 }
221​
222 if (!hasBranch) {
223 return `Detached HEAD: check out a branch before creating a ${terminology.singular}.`;
224 }
225 if (!gitStatus.hasUpstream && !hasPrimaryRemote) {
226 return `Add an "origin" remote before creating a ${terminology.singular}.`;
227 }
228 if ((gitStatus.aheadOfDefaultCount ?? gitStatus.aheadCount) <= 0) {
229 return `No local commits to include in a ${terminology.singular}.`;
230 }
231 if (isBehind) {
232 return `Branch is behind upstream. Pull/rebase before creating a ${terminology.singular}.`;
233 }
234 return `Create ${terminology.singular} is currently unavailable.`;
236​
237export function hasUsableGitMenuContent(input: {
238 readonly menuItems: readonly GitActionMenuItem[];
239 readonly canWriteSourceControl: boolean;
240 readonly canPublishRepository: boolean;
241 readonly hasNotice: boolean;
242}): boolean {
243 return (
244 input.canPublishRepository ||
245 input.hasNotice ||
246 (input.canWriteSourceControl && input.menuItems.some((item) => !item.disabled))
247 );
249​
250export function resolveQuickAction(
251 gitStatus: VcsStatusResult | null,
252 isBusy: boolean,
253 isDefaultRef = false,
254 hasPrimaryRemote = true,
255): GitQuickAction {
256 if (isBusy) {
257 return { label: "Commit", disabled: true, kind: "show_hint", hint: "Git action in progress." };
258 }
259​
260 if (!gitStatus) {
261 return {
262 label: "Commit",
263 disabled: true,
264 kind: "show_hint",
265 hint: "Git status is unavailable.",
266 };
267 }
268​
269 const hasBranch = gitStatus.refName !== null;
270 const hasChanges = gitStatus.hasWorkingTreeChanges;
271 const hasOpenPr = gitStatus.pr?.state === "open";
272 const isAhead = gitStatus.aheadCount > 0;
273 const hasDefaultBranchDelta = (gitStatus.aheadOfDefaultCount ?? gitStatus.aheadCount) > 0;
274 const isBehind = gitStatus.behindCount > 0;
275 const isDiverged = isAhead && isBehind;
276 const terminology = changeRequestTerminologyFor(gitStatus);
277​
278 if (!hasBranch) {
279 return {
280 label: "Commit",
281 disabled: true,
282 kind: "show_hint",
283 hint: `Create and checkout a ref before pushing or opening a ${terminology.singular}.`,
284 };
285 }
286​
287 if (hasChanges) {
288 if (isBehind || (!gitStatus.hasUpstream && !hasPrimaryRemote)) {
289 return { label: "Commit", disabled: false, kind: "run_action", action: "commit" };
290 }
291 if (hasOpenPr || isDefaultRef) {
292 return { label: "Commit & push", disabled: false, kind: "run_action", action: "commit_push" };
293 }
294 return {
295 label: `Commit, push & ${terminology.shortLabel}`,
296 disabled: false,
297 kind: "run_action",
298 action: "commit_push_pr",
299 };
300 }
301​
302 if (!gitStatus.hasUpstream) {
303 if (!hasPrimaryRemote) {
304 return {
305 label: "Publish repository",
306 disabled: false,
307 kind: "open_publish",
308 };
309 }
310 if (!isAhead) {
311 if (hasOpenPr) {
312 return {
313 label: "Commit",
314 disabled: true,
315 kind: "show_hint",
316 hint: "Branch is up to date. No action needed.",
317 };
318 }
319 return {
320 label: "Push",
321 disabled: true,
322 kind: "show_hint",
323 hint: "No local commits to push.",
324 };
325 }
326 if (hasOpenPr || isDefaultRef) {
327 return {
328 label: "Push",
329 disabled: false,
330 kind: "run_action",
331 action: isDefaultRef ? "commit_push" : "push",
332 };
333 }
334 return {
335 label: `Push & create ${terminology.shortLabel}`,
336 disabled: false,
337 kind: "run_action",
338 action: "create_pr",
339 };
340 }
341​
342 if (isDiverged) {
343 return {
344 label: "Sync ref",
345 disabled: true,
346 kind: "show_hint",
347 hint: "Branch has diverged from upstream. Rebase/merge first.",
348 };
349 }
350​
351 if (isBehind) {
352 return {
353 label: "Pull",
354 disabled: false,
355 kind: "run_pull",
356 };
357 }
358​
359 if (isAhead) {
360 if (hasOpenPr || isDefaultRef) {
361 return {
362 label: "Push",
363 disabled: false,
364 kind: "run_action",
365 action: isDefaultRef ? "commit_push" : "push",
366 };
367 }
368 return {
369 label: `Push & create ${terminology.shortLabel}`,
370 disabled: false,
371 kind: "run_action",
372 action: "create_pr",
373 };
374 }
375​
376 if (hasOpenPr && gitStatus.hasUpstream) {
377 return {
378 label: "Commit",
379 disabled: true,
380 kind: "show_hint",
381 hint: "Branch is up to date. No action needed.",
382 };
383 }
384​
385 if (hasDefaultBranchDelta && !isDefaultRef) {
386 return {
387 label: `Create ${terminology.shortLabel}`,
388 disabled: false,
389 kind: "run_action",
390 action: "create_pr",
391 };
392 }
393​
394 return {
395 label: "Commit",
396 disabled: true,
397 kind: "show_hint",
398 hint: "Branch is up to date. No action needed.",
399 };
401​
402export function resolveDefaultBranchActionDialogCopy(input: {
403 action: DefaultBranchConfirmableAction;
404 branchName: string;
405 includesCommit: boolean;
406 terminology: ChangeRequestTerminology;
407}): DefaultBranchActionDialogCopy {
408 const branchLabel = input.branchName;
409 const suffix = ` on "${branchLabel}". You can continue on this ref or create a feature ref and run the same action there.`;
410 const { terminology } = input;
411​
412 if (input.action === "push" || input.action === "commit_push") {
413 if (input.includesCommit) {
414 return {
415 title: "Commit & push to default ref?",
416 description: `This action will commit and push changes${suffix}`,
417 continueLabel: `Commit & push to ${branchLabel}`,
418 };
419 }
420 return {
421 title: "Push to default ref?",
422 description: `This action will push local commits${suffix}`,
423 continueLabel: `Push to ${branchLabel}`,
424 };
425 }
426​
427 if (input.includesCommit) {
428 return {
429 title: `Commit, push & create ${terminology.shortLabel} from default ref?`,
430 description: `This action will commit, push, and create a ${terminology.singular}${suffix}`,
431 continueLabel: `Commit, push & create ${terminology.shortLabel}`,
432 };
433 }
434 return {
435 title: `Push & create ${terminology.shortLabel} from default ref?`,
436 description: `This action will push local commits and create a ${terminology.singular}${suffix}`,
437 continueLabel: `Push & create ${terminology.shortLabel}`,
438 };
440​
441/** The server names a feature branch from the commit it makes, so the action must commit changes. */
442export function resolveFeatureBranchUnavailableReason(input: {
443 action: DefaultBranchConfirmableAction;
444 branchName: string;
445 hasWorkingTreeChanges: boolean;
446}): string | null {
447 if (!input.hasWorkingTreeChanges) {
448 return `There are no changes to commit, so a feature branch can't be named. Create a branch yourself or continue on ${input.branchName}.`;
449 }
450 if (input.action === "push" || input.action === "create_pr") {
451 return `This action doesn't commit your changes, so a feature branch can't be named. Create a branch yourself or continue on ${input.branchName}.`;
452 }
453 return null;
455​
456export function resolveThreadBranchUpdate(
457 result: GitRunStackedActionResult,
458): { branch: string } | null {
459 if (result.branch.status !== "created" || !result.branch.name) {
460 return null;
461 }
462​
463 return {
464 branch: result.branch.name,
465 };
467​
468export function resolveThreadBranchMetadataPatch(
469 branch: string | null,
470 expectedBranch: string | null,
471): {
472 branch: string | null;
473 expectedBranch: string | null;
474} {
475 return { branch, expectedBranch };
477​
478export function resolveLiveThreadBranchUpdate(input: {
479 threadBranch: string | null;
480 gitStatus: VcsStatusResult | null;
481}): { branch: string | null } | null {
482 if (!input.gitStatus) {
483 return null;
484 }
485​
486 if (input.gitStatus.refName === null && input.threadBranch !== null) {
487 return null;
488 }
489​
490 if (input.threadBranch === input.gitStatus.refName) {
491 return null;
492 }
493​
494 if (
495 input.threadBranch !== null &&
496 input.gitStatus.refName !== null &&
497 !isTemporaryWorktreeBranch(input.threadBranch) &&
498 isTemporaryWorktreeBranch(input.gitStatus.refName)
499 ) {
500 return null;
501 }
502​
503 return {
504 branch: input.gitStatus.refName,
505 };
507​
508export type ChangesLineTotals = {
509 readonly insertions: number;
510 readonly deletions: number;
511 /** Ref the counts compare against; `null` means they are uncommitted changes against HEAD. */
512 readonly baseRef: string | null;
513};
514​
515// `branchChanges ?? workingTree` treats `{0,0}` as present, so a zero branch total hid a dirty
516// working tree and the Changes row read +0 while Diff still showed the work.
517// The Diff panel's branch comparison wins when it has file stats, so a remembered base or
518// hidden whitespace reads the same in the row as in the panel.
519export function resolveChangesTotals(
520 status: VcsStatusResult | null | undefined,
521 branchPreview?: ReviewDiffPreviewSource | null,
522): ChangesLineTotals | null {
523 if (branchPreview?.files) {
524 let insertions = 0;
525 let deletions = 0;
526 for (const file of branchPreview.files) {
527 insertions += file.additions;
528 deletions += file.deletions;
529 }
530 return { insertions, deletions, baseRef: branchPreview.baseRef };
531 }
532 if (!status) return null;
533 const branch = status.branchChanges;
534 const tree = { ...status.workingTree, baseRef: null };
535 const selected =
536 branch && (branch.insertions > 0 || branch.deletions > 0)
537 ? branch
538 : tree.insertions > 0 || tree.deletions > 0
539 ? tree
540 : (branch ?? tree);
541 return {
542 insertions: selected.insertions,
543 deletions: selected.deletions,
544 baseRef: selected.baseRef,
545 };