Open History to see the last commit
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;
30}
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;
38}
39
40export interface GitActionProgressPresentation {
41 readonly status: string;
42 readonly output: string | null;
43 readonly startedAtMs: number | null;
44}
45
46export interface GitActionResultToastTiming {
47 readonly timeout: 0;
48 readonly dismissAfterVisibleMs: number | null;
49}
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 };
60}
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 };
92}
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`;
107}
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 ];
176}
177
178export function hasUsableGitMenuContent(input: {
179 readonly menuItems: readonly GitActionMenuItem[];
180 readonly canWriteSourceControl: boolean;
181 readonly canPublishRepository: boolean;
182 readonly hasNotice: boolean;
183}): boolean {
184 return (
185 input.canPublishRepository ||
186 input.hasNotice ||
187 (input.canWriteSourceControl && input.menuItems.some((item) => !item.disabled))
188 );
189}
190
191export function resolveQuickAction(
192 gitStatus: VcsStatusResult | null,
193 isBusy: boolean,
194 isDefaultRef = false,
195 hasPrimaryRemote = true,
196): GitQuickAction {
197 if (isBusy) {
198 return { label: "Commit", disabled: true, kind: "show_hint", hint: "Git action in progress." };
199 }
200
201 if (!gitStatus) {
202 return {
203 label: "Commit",
204 disabled: true,
205 kind: "show_hint",
206 hint: "Git status is unavailable.",
207 };
208 }
209
210 const hasBranch = gitStatus.refName !== null;
211 const hasChanges = gitStatus.hasWorkingTreeChanges;
212 const hasOpenPr = gitStatus.pr?.state === "open";
213 const isAhead = gitStatus.aheadCount > 0;
214 const hasDefaultBranchDelta = (gitStatus.aheadOfDefaultCount ?? gitStatus.aheadCount) > 0;
215 const isBehind = gitStatus.behindCount > 0;
216 const isDiverged = isAhead && isBehind;
217 const terminology = changeRequestTerminologyFor(gitStatus);
218
219 if (!hasBranch) {
220 return {
221 label: "Commit",
222 disabled: true,
223 kind: "show_hint",
224 hint: `Create and checkout a ref before pushing or opening a ${terminology.singular}.`,
225 };
226 }
227
228 if (hasChanges) {
229 if (isBehind || (!gitStatus.hasUpstream && !hasPrimaryRemote)) {
230 return { label: "Commit", disabled: false, kind: "run_action", action: "commit" };
231 }
232 if (hasOpenPr || isDefaultRef) {
233 return { label: "Commit & push", disabled: false, kind: "run_action", action: "commit_push" };
234 }
235 return {
236 label: `Commit, push & ${terminology.shortLabel}`,
237 disabled: false,
238 kind: "run_action",
239 action: "commit_push_pr",
240 };
241 }
242
243 if (!gitStatus.hasUpstream) {
244 if (!hasPrimaryRemote) {
245 return {
246 label: "Publish repository",
247 disabled: false,
248 kind: "open_publish",
249 };
250 }
251 if (!isAhead) {
252 if (hasOpenPr) {
253 return {
254 label: "Commit",
255 disabled: true,
256 kind: "show_hint",
257 hint: "Branch is up to date. No action needed.",
258 };
259 }
260 return {
261 label: "Push",
262 disabled: true,
263 kind: "show_hint",
264 hint: "No local commits to push.",
265 };
266 }
267 if (hasOpenPr || isDefaultRef) {
268 return {
269 label: "Push",
270 disabled: false,
271 kind: "run_action",
272 action: isDefaultRef ? "commit_push" : "push",
273 };
274 }
275 return {
276 label: `Push & create ${terminology.shortLabel}`,
277 disabled: false,
278 kind: "run_action",
279 action: "create_pr",
280 };
281 }
282
283 if (isDiverged) {
284 return {
285 label: "Sync ref",
286 disabled: true,
287 kind: "show_hint",
288 hint: "Branch has diverged from upstream. Rebase/merge first.",
289 };
290 }
291
292 if (isBehind) {
293 return {
294 label: "Pull",
295 disabled: false,
296 kind: "run_pull",
297 };
298 }
299
300 if (isAhead) {
301 if (hasOpenPr || isDefaultRef) {
302 return {
303 label: "Push",
304 disabled: false,
305 kind: "run_action",
306 action: isDefaultRef ? "commit_push" : "push",
307 };
308 }
309 return {
310 label: `Push & create ${terminology.shortLabel}`,
311 disabled: false,
312 kind: "run_action",
313 action: "create_pr",
314 };
315 }
316
317 if (hasOpenPr && gitStatus.hasUpstream) {
318 return {
319 label: "Commit",
320 disabled: true,
321 kind: "show_hint",
322 hint: "Branch is up to date. No action needed.",
323 };
324 }
325
326 if (hasDefaultBranchDelta && !isDefaultRef) {
327 return {
328 label: `Create ${terminology.shortLabel}`,
329 disabled: false,
330 kind: "run_action",
331 action: "create_pr",
332 };
333 }
334
335 return {
336 label: "Commit",
337 disabled: true,
338 kind: "show_hint",
339 hint: "Branch is up to date. No action needed.",
340 };
341}
342
343export function resolveDefaultBranchActionDialogCopy(input: {
344 action: DefaultBranchConfirmableAction;
345 branchName: string;
346 includesCommit: boolean;
347 terminology: ChangeRequestTerminology;
348}): DefaultBranchActionDialogCopy {
349 const branchLabel = input.branchName;
350 const suffix = ` on "${branchLabel}". You can continue on this ref or create a feature ref and run the same action there.`;
351 const { terminology } = input;
352
353 if (input.action === "push" || input.action === "commit_push") {
354 if (input.includesCommit) {
355 return {
356 title: "Commit & push to default ref?",
357 description: `This action will commit and push changes${suffix}`,
358 continueLabel: `Commit & push to ${branchLabel}`,
359 };
360 }
361 return {
362 title: "Push to default ref?",
363 description: `This action will push local commits${suffix}`,
364 continueLabel: `Push to ${branchLabel}`,
365 };
366 }
367
368 if (input.includesCommit) {
369 return {
370 title: `Commit, push & create ${terminology.shortLabel} from default ref?`,
371 description: `This action will commit, push, and create a ${terminology.singular}${suffix}`,
372 continueLabel: `Commit, push & create ${terminology.shortLabel}`,
373 };
374 }
375 return {
376 title: `Push & create ${terminology.shortLabel} from default ref?`,
377 description: `This action will push local commits and create a ${terminology.singular}${suffix}`,
378 continueLabel: `Push & create ${terminology.shortLabel}`,
379 };
380}
381
382/** Clean trees cannot create feature branches because the server derives names from uncommitted changes. */
383export function resolveFeatureBranchUnavailableReason(input: {
384 branchName: string;
385 hasWorkingTreeChanges: boolean;
386}): string | null {
387 if (input.hasWorkingTreeChanges) return null;
388 return `There are no changes to commit, so a feature branch can't be named. Create a branch yourself or continue on ${input.branchName}.`;
389}
390
391export function resolveThreadBranchUpdate(
392 result: GitRunStackedActionResult,
393): { branch: string } | null {
394 if (result.branch.status !== "created" || !result.branch.name) {
395 return null;
396 }
397
398 return {
399 branch: result.branch.name,
400 };
401}
402
403export function resolveThreadBranchMetadataPatch(
404 branch: string | null,
405 expectedBranch: string | null,
406): {
407 branch: string | null;
408 expectedBranch: string | null;
409} {
410 return { branch, expectedBranch };
411}
412
413export function resolveLiveThreadBranchUpdate(input: {
414 threadBranch: string | null;
415 gitStatus: VcsStatusResult | null;
416}): { branch: string | null } | null {
417 if (!input.gitStatus) {
418 return null;
419 }
420
421 if (input.gitStatus.refName === null && input.threadBranch !== null) {
422 return null;
423 }
424
425 if (input.threadBranch === input.gitStatus.refName) {
426 return null;
427 }
428
429 if (
430 input.threadBranch !== null &&
431 input.gitStatus.refName !== null &&
432 !isTemporaryWorktreeBranch(input.threadBranch) &&
433 isTemporaryWorktreeBranch(input.gitStatus.refName)
434 ) {
435 return null;
436 }
437
438 return {
439 branch: input.gitStatus.refName,
440 };
441}
442
443export type ChangesLineTotals = {
444 readonly insertions: number;
445 readonly deletions: number;
446 /** Ref the counts compare against; `null` means they are uncommitted changes against HEAD. */
447 readonly baseRef: string | null;
448};
449
450// `branchChanges ?? workingTree` treats `{0,0}` as present, so a zero branch total hid a dirty
451// working tree and the Changes row read +0 while Diff still showed the work.
452// The Diff panel's branch comparison wins when it has file stats, so a remembered base or
453// hidden whitespace reads the same in the row as in the panel.
454export function resolveChangesTotals(
455 status: VcsStatusResult | null | undefined,
456 branchPreview?: ReviewDiffPreviewSource | null,
457): ChangesLineTotals | null {
458 if (branchPreview?.files) {
459 let insertions = 0;
460 let deletions = 0;
461 for (const file of branchPreview.files) {
462 insertions += file.additions;
463 deletions += file.deletions;
464 }
465 return { insertions, deletions, baseRef: branchPreview.baseRef };
466 }
467 if (!status) return null;
468 const branch = status.branchChanges;
469 const tree = { ...status.workingTree, baseRef: null };
470 const selected =
471 branch && (branch.insertions > 0 || branch.deletions > 0)
472 ? branch
473 : tree.insertions > 0 || tree.deletions > 0
474 ? tree
475 : (branch ?? tree);
476 return {
477 insertions: selected.insertions,
478 deletions: selected.deletions,
479 baseRef: selected.baseRef,
480 };
481}