Open History to see the last commit
1import type {
2 GitRunStackedActionResult,
3 GitStackedAction,
4 PullRequestChangeBreakdown,
5 ReviewDiffPreviewSource,
6 VcsStatusResult,
7} from "@t3tools/contracts";
8import { summarizeChangedFiles } from "@t3tools/shared/changedFileKind";
9import { isTemporaryWorktreeBranch } from "@t3tools/shared/git";
10import { msg, select } from "gt-react";
11import { m, type MessageResolver } from "../i18n/messages";
12import { changeRequestTermKind } from "./pullRequest/changeRequestTerm";
13import type { ChangeRequestTerminology } from "@t3tools/client-runtime/source-control-clients";
14import {
15 changeRequestTerminologyFor,
16 type DefaultBranchActionDialogCopy,
17 type DefaultBranchConfirmableAction,
18 type GitActionIconName,
19 type GitDialogAction,
20 vcsActionLabelText,
21} from "@t3tools/client-runtime/state/vcs";
22
23export {
24 requiresDefaultBranchConfirmation,
25 type DefaultBranchConfirmableAction,
26 type GitActionIconName,
27} from "@t3tools/client-runtime/state/vcs";
28
29export interface GitActionMenuItem {
30 id: "commit" | "push" | "pr";
31 label: string;
32 disabled: boolean;
33 icon: GitActionIconName;
34 kind: "open_dialog";
35 dialogAction?: GitDialogAction;
36}
37
38export interface GitQuickAction {
39 label: string;
40 disabled: boolean;
41 kind: "run_action" | "run_pull" | "open_publish" | "show_hint";
42 action?: GitStackedAction;
43 hint?: string;
44}
45
46export interface GitActionProgressPresentation {
47 readonly status: string;
48 readonly output: string | null;
49 readonly startedAtMs: number | null;
50}
51
52export interface GitActionResultToastTiming {
53 readonly timeout: 0;
54 readonly dismissAfterVisibleMs: number | null;
55}
56
57export const GIT_ACTION_SUCCESS_VISIBLE_MS = 10_000;
58
59export function resolveGitActionResultToastTiming(
60 type: "error" | "success",
61): GitActionResultToastTiming {
62 return {
63 timeout: 0,
64 dismissAfterVisibleMs: type === "success" ? GIT_ACTION_SUCCESS_VISIBLE_MS : null,
65 };
66}
67
68export function resolveGitActionProgressPresentation(
69 input: {
70 readonly isRunning: boolean;
71 readonly operation: string | null;
72 readonly currentLabel: string | null;
73 readonly hookName?: string | null;
74 readonly lastOutputLine: string | null;
75 readonly phaseStartedAtMs: number | null;
76 readonly hookStartedAtMs: number | null;
77 },
78 resolve: MessageResolver = m,
79): GitActionProgressPresentation | null {
80 if (
81 !input.isRunning ||
82 (input.operation !== "run_change_request" && input.operation !== "pull")
83 ) {
84 return null;
85 }
86
87 const currentLabel = input.currentLabel?.trim();
88 const output = input.lastOutputLine?.trim();
89 const isPull = input.operation === "pull";
90 return {
91 status:
92 currentLabel && currentLabel !== "Running source control action"
93 ? (vcsActionLabelText({ currentLabel, hookName: input.hookName ?? null }, resolve) ??
94 currentLabel)
95 : isPull
96 ? resolve(msg("Pulling latest changes..."))
97 : resolve(msg("Starting source control action...")),
98 output: !isPull && output ? output : null,
99 startedAtMs: isPull
100 ? input.phaseStartedAtMs
101 : (input.hookStartedAtMs ?? input.phaseStartedAtMs),
102 };
103}
104
105export function formatGitActionElapsed(
106 startedAtMs: number | null,
107 nowMs: number,
108 resolve: MessageResolver = m,
109): string | null {
110 if (startedAtMs === null) {
111 return null;
112 }
113
114 const elapsedSeconds = Math.max(0, Math.floor((nowMs - startedAtMs) / 1_000));
115 if (elapsedSeconds < 60) {
116 return resolve(msg`${{ seconds: elapsedSeconds }}s`);
117 }
118
119 const minutes = Math.floor(elapsedSeconds / 60);
120 const seconds = elapsedSeconds % 60;
121 return resolve(msg`${{ minutes }}m ${{ seconds }}s`);
122}
123
124export function buildMenuItems(
125 gitStatus: VcsStatusResult | null,
126 isBusy: boolean,
127 hasPrimaryRemote = true,
128 resolve: MessageResolver = m,
129): GitActionMenuItem[] {
130 if (!gitStatus) return [];
131 const terminology = changeRequestTerminologyFor(gitStatus);
132
133 const hasBranch = gitStatus.refName !== null;
134 const hasChanges = gitStatus.hasWorkingTreeChanges;
135 const hasOpenPr = gitStatus.pr?.state === "open";
136 const isBehind = gitStatus.behindCount > 0;
137 const hasDefaultBranchDelta = (gitStatus.aheadOfDefaultCount ?? gitStatus.aheadCount) > 0;
138 const canPushWithoutUpstream = hasPrimaryRemote && !gitStatus.hasUpstream;
139 const canCommit = !isBusy && hasChanges;
140 const canPush =
141 !isBusy &&
142 hasBranch &&
143 !isBehind &&
144 gitStatus.aheadCount > 0 &&
145 (gitStatus.hasUpstream || canPushWithoutUpstream);
146 const canCreatePr =
147 !isBusy &&
148 hasBranch &&
149 !hasOpenPr &&
150 hasDefaultBranchDelta &&
151 !isBehind &&
152 (gitStatus.hasUpstream || canPushWithoutUpstream);
153
154 const commitItem: GitActionMenuItem = {
155 id: "commit",
156 label: resolve(msg({ context: "verb, git action" })`Commit`),
157 disabled: !canCommit,
158 icon: "commit",
159 kind: "open_dialog",
160 dialogAction: "commit",
161 };
162
163 if (!hasPrimaryRemote) {
164 return [commitItem];
165 }
166
167 const pushItem: GitActionMenuItem = {
168 id: "push",
169 label: resolve(msg({ context: "verb, git action" })`Push`),
170 disabled: !canPush,
171 icon: "push",
172 kind: "open_dialog",
173 dialogAction: "push",
174 };
175
176 if (hasOpenPr) {
177 return [commitItem, pushItem];
178 }
179
180 return [
181 commitItem,
182 pushItem,
183 {
184 id: "pr",
185 label: resolve(
186 msg`Create ${select(
187 { term: changeRequestTermKind(terminology) },
188 {
189 mr: "MR",
190 cr: "change request",
191 other: "PR",
192 },
193 )}`,
194 ),
195 disabled: !canCreatePr,
196 icon: "pr",
197 kind: "open_dialog",
198 dialogAction: "create_pr",
199 },
200 ];
201}
202
203export function getMenuActionDisabledReason(
204 {
205 item,
206 gitStatus,
207 isBusy,
208 hasPrimaryRemote,
209 }: {
210 item: GitActionMenuItem;
211 gitStatus: VcsStatusResult | null;
212 isBusy: boolean;
213 hasPrimaryRemote: boolean;
214 },
215 resolve: MessageResolver = m,
216): string | null {
217 if (!item.disabled) return null;
218 if (isBusy) return resolve(msg("Git action in progress."));
219 if (!gitStatus) return resolve(msg("Git status is unavailable."));
220
221 const hasBranch = gitStatus.refName !== null;
222 const hasChanges = gitStatus.hasWorkingTreeChanges;
223 const isAhead = gitStatus.aheadCount > 0;
224 const isBehind = gitStatus.behindCount > 0;
225 const terminology = changeRequestTerminologyFor(gitStatus);
226
227 if (item.id === "commit") {
228 if (!hasChanges) {
229 return resolve(msg("Worktree is clean. Make changes before committing."));
230 }
231 return resolve(msg("Commit is currently unavailable."));
232 }
233
234 if (item.id === "push") {
235 if (!hasBranch) {
236 return resolve(msg("Detached HEAD: check out a branch before pushing."));
237 }
238 if (isBehind) {
239 return resolve(msg("Branch is behind upstream. Pull/rebase before pushing."));
240 }
241 if (!gitStatus.hasUpstream && !hasPrimaryRemote) {
242 return resolve(msg('Add an "origin" remote before pushing.'));
243 }
244 if (!isAhead) {
245 return resolve(msg("No local commits to push."));
246 }
247 return resolve(msg("Push is currently unavailable."));
248 }
249
250 if (!hasBranch) {
251 return resolve(
252 msg`Detached HEAD: check out a branch before creating a ${select(
253 { term: changeRequestTermKind(terminology) },
254 {
255 mr: "merge request",
256 cr: "change request",
257 other: "pull request",
258 },
259 )}.`,
260 );
261 }
262 if (!gitStatus.hasUpstream && !hasPrimaryRemote) {
263 return resolve(
264 msg`Add an "origin" remote before creating a ${select(
265 { term: changeRequestTermKind(terminology) },
266 {
267 mr: "merge request",
268 cr: "change request",
269 other: "pull request",
270 },
271 )}.`,
272 );
273 }
274 if ((gitStatus.aheadOfDefaultCount ?? gitStatus.aheadCount) <= 0) {
275 return resolve(
276 msg`No local commits to include in a ${select(
277 { term: changeRequestTermKind(terminology) },
278 {
279 mr: "merge request",
280 cr: "change request",
281 other: "pull request",
282 },
283 )}.`,
284 );
285 }
286 if (isBehind) {
287 return resolve(
288 msg`Branch is behind upstream. Pull/rebase before creating a ${select(
289 { term: changeRequestTermKind(terminology) },
290 {
291 mr: "merge request",
292 cr: "change request",
293 other: "pull request",
294 },
295 )}.`,
296 );
297 }
298 return resolve(
299 msg`Create ${select(
300 { term: changeRequestTermKind(terminology) },
301 {
302 mr: "merge request",
303 cr: "change request",
304 other: "pull request",
305 },
306 )} is currently unavailable.`,
307 );
308}
309
310export function hasUsableGitMenuContent(input: {
311 readonly menuItems: readonly GitActionMenuItem[];
312 readonly canWriteSourceControl: boolean;
313 readonly canPublishRepository: boolean;
314 readonly hasNotice: boolean;
315}): boolean {
316 return (
317 input.canPublishRepository ||
318 input.hasNotice ||
319 (input.canWriteSourceControl && input.menuItems.some((item) => !item.disabled))
320 );
321}
322
323export function resolveQuickAction(
324 gitStatus: VcsStatusResult | null,
325 isBusy: boolean,
326 isDefaultRef = false,
327 hasPrimaryRemote = true,
328 resolve: MessageResolver = m,
329): GitQuickAction {
330 if (isBusy) {
331 return {
332 label: resolve(msg({ context: "verb, git action" })`Commit`),
333 disabled: true,
334 kind: "show_hint",
335 hint: resolve(msg("Git action in progress.")),
336 };
337 }
338
339 if (!gitStatus) {
340 return {
341 label: resolve(msg({ context: "verb, git action" })`Commit`),
342 disabled: true,
343 kind: "show_hint",
344 hint: resolve(msg("Git status is unavailable.")),
345 };
346 }
347
348 const hasBranch = gitStatus.refName !== null;
349 const hasChanges = gitStatus.hasWorkingTreeChanges;
350 const hasOpenPr = gitStatus.pr?.state === "open";
351 const isAhead = gitStatus.aheadCount > 0;
352 const hasDefaultBranchDelta = (gitStatus.aheadOfDefaultCount ?? gitStatus.aheadCount) > 0;
353 const isBehind = gitStatus.behindCount > 0;
354 const isDiverged = isAhead && isBehind;
355 const terminology = changeRequestTerminologyFor(gitStatus);
356
357 if (!hasBranch) {
358 return {
359 label: resolve(msg({ context: "verb, git action" })`Commit`),
360 disabled: true,
361 kind: "show_hint",
362 hint: resolve(
363 msg`Create and checkout a ref before pushing or opening a ${select(
364 { term: changeRequestTermKind(terminology) },
365 {
366 mr: "merge request",
367 cr: "change request",
368 other: "pull request",
369 },
370 )}.`,
371 ),
372 };
373 }
374
375 if (hasChanges) {
376 if (isBehind || (!gitStatus.hasUpstream && !hasPrimaryRemote)) {
377 return {
378 label: resolve(msg({ context: "verb, git action" })`Commit`),
379 disabled: false,
380 kind: "run_action",
381 action: "commit",
382 };
383 }
384 if (hasOpenPr || isDefaultRef) {
385 return {
386 label: resolve(msg("Commit & push")),
387 disabled: false,
388 kind: "run_action",
389 action: "commit_push",
390 };
391 }
392 return {
393 label: resolve(
394 msg`Commit, push & ${select(
395 { term: changeRequestTermKind(terminology) },
396 {
397 mr: "MR",
398 cr: "change request",
399 other: "PR",
400 },
401 )}`,
402 ),
403 disabled: false,
404 kind: "run_action",
405 action: "commit_push_pr",
406 };
407 }
408
409 if (!gitStatus.hasUpstream) {
410 if (!hasPrimaryRemote) {
411 return {
412 label: resolve(msg("Publish repository")),
413 disabled: false,
414 kind: "open_publish",
415 };
416 }
417 if (!isAhead) {
418 if (hasOpenPr) {
419 return {
420 label: resolve(msg({ context: "verb, git action" })`Commit`),
421 disabled: true,
422 kind: "show_hint",
423 hint: resolve(msg("Branch is up to date. No action needed.")),
424 };
425 }
426 return {
427 label: resolve(msg({ context: "verb, git action" })`Push`),
428 disabled: true,
429 kind: "show_hint",
430 hint: resolve(msg("No local commits to push.")),
431 };
432 }
433 if (hasOpenPr || isDefaultRef) {
434 return {
435 label: resolve(msg({ context: "verb, git action" })`Push`),
436 disabled: false,
437 kind: "run_action",
438 action: "push",
439 };
440 }
441 return {
442 label: resolve(
443 msg`Push & create ${select(
444 { term: changeRequestTermKind(terminology) },
445 {
446 mr: "MR",
447 cr: "change request",
448 other: "PR",
449 },
450 )}`,
451 ),
452 disabled: false,
453 kind: "run_action",
454 action: "create_pr",
455 };
456 }
457
458 if (isDiverged) {
459 return {
460 label: resolve(msg("Sync ref")),
461 disabled: true,
462 kind: "show_hint",
463 hint: resolve(msg("Branch has diverged from upstream. Rebase/merge first.")),
464 };
465 }
466
467 if (isBehind) {
468 return {
469 label: resolve(msg("Pull")),
470 disabled: false,
471 kind: "run_pull",
472 };
473 }
474
475 if (isAhead) {
476 if (hasOpenPr || isDefaultRef) {
477 return {
478 label: resolve(msg({ context: "verb, git action" })`Push`),
479 disabled: false,
480 kind: "run_action",
481 action: "push",
482 };
483 }
484 return {
485 label: resolve(
486 msg`Push & create ${select(
487 { term: changeRequestTermKind(terminology) },
488 {
489 mr: "MR",
490 cr: "change request",
491 other: "PR",
492 },
493 )}`,
494 ),
495 disabled: false,
496 kind: "run_action",
497 action: "create_pr",
498 };
499 }
500
501 if (hasOpenPr && gitStatus.hasUpstream) {
502 return {
503 label: resolve(msg({ context: "verb, git action" })`Commit`),
504 disabled: true,
505 kind: "show_hint",
506 hint: resolve(msg("Branch is up to date. No action needed.")),
507 };
508 }
509
510 if (hasDefaultBranchDelta && !isDefaultRef) {
511 return {
512 label: resolve(
513 msg`Create ${select(
514 { term: changeRequestTermKind(terminology) },
515 {
516 mr: "MR",
517 cr: "change request",
518 other: "PR",
519 },
520 )}`,
521 ),
522 disabled: false,
523 kind: "run_action",
524 action: "create_pr",
525 };
526 }
527
528 return {
529 label: resolve(msg({ context: "verb, git action" })`Commit`),
530 disabled: true,
531 kind: "show_hint",
532 hint: resolve(msg("Branch is up to date. No action needed.")),
533 };
534}
535
536export function resolveDefaultBranchActionDialogCopy(
537 input: {
538 action: DefaultBranchConfirmableAction;
539 branchName: string;
540 includesCommit: boolean;
541 terminology: ChangeRequestTerminology;
542 },
543 resolve: MessageResolver = m,
544): DefaultBranchActionDialogCopy {
545 const branch = input.branchName;
546 const term = changeRequestTermKind(input.terminology);
547
548 if (input.action === "push" || input.action === "commit_push") {
549 if (input.includesCommit) {
550 return {
551 title: resolve(msg("Commit & push to default ref?")),
552 description: resolve(
553 msg`This action will commit and push changes on "${{ branch }}". You can continue on this ref or create a feature ref and run the same action there.`,
554 ),
555 continueLabel: resolve(msg`Commit & push to ${{ branch }}`),
556 };
557 }
558 return {
559 title: resolve(msg("Push to default ref?")),
560 description: resolve(
561 msg`This action will push local commits on "${{ branch }}". You can continue on this ref or create a feature ref and run the same action there.`,
562 ),
563 continueLabel: resolve(msg`Push to ${{ branch }}`),
564 };
565 }
566
567 if (input.includesCommit) {
568 return {
569 title: resolve(
570 msg`Commit, push & create ${select({ term }, { mr: "MR", cr: "change request", other: "PR" })} from default ref?`,
571 ),
572 description: resolve(
573 msg`This action will commit, push, and create a ${select(
574 { term },
575 {
576 mr: "merge request",
577 cr: "change request",
578 other: "pull request",
579 },
580 )} on "${{ branch }}". You can continue on this ref or create a feature ref and run the same action there.`,
581 ),
582 continueLabel: resolve(
583 msg`Commit, push & create ${select({ term }, { mr: "MR", cr: "change request", other: "PR" })}`,
584 ),
585 };
586 }
587 return {
588 title: resolve(
589 msg`Push & create ${select({ term }, { mr: "MR", cr: "change request", other: "PR" })} from default ref?`,
590 ),
591 description: resolve(
592 msg`This action will push local commits and create a ${select(
593 { term },
594 {
595 mr: "merge request",
596 cr: "change request",
597 other: "pull request",
598 },
599 )} on "${{ branch }}". You can continue on this ref or create a feature ref and run the same action there.`,
600 ),
601 continueLabel: resolve(
602 msg`Push & create ${select({ term }, { mr: "MR", cr: "change request", other: "PR" })}`,
603 ),
604 };
605}
606
607/** The server names a feature branch from the commit it makes, so the action must commit changes. */
608export function resolveFeatureBranchUnavailableReason(
609 input: {
610 action: DefaultBranchConfirmableAction;
611 branchName: string;
612 hasWorkingTreeChanges: boolean;
613 },
614 resolve: MessageResolver = m,
615): string | null {
616 if (!input.hasWorkingTreeChanges) {
617 return resolve(
618 msg`There are no changes to commit, so a feature branch can't be named. Create a branch yourself or continue on ${{ branch: input.branchName }}.`,
619 );
620 }
621 if (input.action === "push" || input.action === "create_pr") {
622 return resolve(
623 msg`This action doesn't commit your changes, so a feature branch can't be named. Create a branch yourself or continue on ${{ branch: input.branchName }}.`,
624 );
625 }
626 return null;
627}
628
629export function resolveThreadBranchUpdate(
630 result: GitRunStackedActionResult,
631): { branch: string } | null {
632 if (result.branch.status !== "created" || !result.branch.name) {
633 return null;
634 }
635
636 return {
637 branch: result.branch.name,
638 };
639}
640
641export function resolveThreadBranchMetadataPatch(
642 branch: string | null,
643 expectedBranch: string | null,
644): {
645 branch: string | null;
646 expectedBranch: string | null;
647} {
648 return { branch, expectedBranch };
649}
650
651export function resolveLiveThreadBranchUpdate(input: {
652 threadBranch: string | null;
653 gitStatus: VcsStatusResult | null;
654}): { branch: string | null } | null {
655 if (!input.gitStatus) {
656 return null;
657 }
658
659 if (input.gitStatus.refName === null && input.threadBranch !== null) {
660 return null;
661 }
662
663 if (input.threadBranch === input.gitStatus.refName) {
664 return null;
665 }
666
667 if (
668 input.threadBranch !== null &&
669 input.gitStatus.refName !== null &&
670 !isTemporaryWorktreeBranch(input.threadBranch) &&
671 isTemporaryWorktreeBranch(input.gitStatus.refName)
672 ) {
673 return null;
674 }
675
676 return {
677 branch: input.gitStatus.refName,
678 };
679}
680
681export type ChangesLineTotals = {
682 readonly insertions: number;
683 readonly deletions: number;
684 /** Ref the counts compare against; `null` means they are uncommitted changes against HEAD. */
685 readonly baseRef: string | null;
686 /** `null` when the selected totals carry no per-file stats. */
687 readonly breakdown: PullRequestChangeBreakdown;
688};
689
690// `branchChanges ?? workingTree` treats `{0,0}` as present, so a zero branch total hid a dirty
691// working tree and the Changes row read +0 while Diff still showed the work.
692// The Diff panel's branch comparison wins when it has file stats, so a remembered base or
693// hidden whitespace reads the same in the row as in the panel.
694export function resolveChangesTotals(
695 status: VcsStatusResult | null | undefined,
696 branchPreview?: ReviewDiffPreviewSource | null,
697): ChangesLineTotals | null {
698 if (branchPreview?.files) {
699 let insertions = 0;
700 let deletions = 0;
701 for (const file of branchPreview.files) {
702 insertions += file.additions;
703 deletions += file.deletions;
704 }
705 return {
706 insertions,
707 deletions,
708 baseRef: branchPreview.baseRef,
709 breakdown: summarizeChangedFiles(branchPreview.files),
710 };
711 }
712 if (!status) return null;
713 const branch = status.branchChanges;
714 const tree = { ...status.workingTree, baseRef: null };
715 const selected =
716 branch && (branch.insertions > 0 || branch.deletions > 0)
717 ? branch
718 : tree.insertions > 0 || tree.deletions > 0
719 ? tree
720 : (branch ?? tree);
721 return {
722 insertions: selected.insertions,
723 deletions: selected.deletions,
724 baseRef: selected.baseRef,
725 breakdown:
726 selected === tree
727 ? summarizeChangedFiles(
728 tree.files.map((file) => ({
729 path: file.path,
730 additions: file.insertions,
731 deletions: file.deletions,
732 })),
733 )
734 : null,
735 };
736}