Open History to see the last commit
1import { msg, useGT, useMessages, plural, part, select } from "gt-react-native";
2
3import * as Dialog from "../../components/ui/Dialog";
4import { useOpenPullRequest } from "../../native/useOpenPullRequest";
5import type { AppBarMenu } from "../../components/ui/AppBar.types";
6import {
7 AuthSourceControlWriteScope,
8 EnvironmentId,
9 type GitRunStackedActionResult,
10 type ProjectScript,
11 ThreadId,
12 type VcsStatusResult,
13} from "@t3tools/contracts";
14import {
15 type GitActionRequestInput,
16 requiresDefaultBranchConfirmation,
17 resolveQuickAction,
18} from "@t3tools/client-runtime/state/vcs";
19import { useNavigation } from "@react-navigation/native";
20import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients";
21import { changeRequestTermKind } from "../../lib/changeRequestTerm";
22
23import { m, type MessageResolver } from "../../i18n/messages";
24import { useEnvironmentScope } from "../../state/session";
25import { PullRequestGlyph } from "../pull-requests/pullRequestGlyphs";
26import {
27 basename,
28 getTerminalStatusLabel,
29 projectScriptMenuIcon,
30 type TerminalMenuSession,
31} from "../terminal/terminalMenu";
32import { projectScriptMenuLabel } from "@t3tools/shared/projectScriptsCopy";
33import { compactMenuBranchLabel } from "./ThreadGitControls.logic";
34
35function compactMenuStatus(gitStatus: VcsStatusResult | null, resolve: MessageResolver): string {
36 if (!gitStatus) {
37 return resolve(msg("Checking status"));
38 }
39 if (!gitStatus.isRepo) {
40 return resolve(msg("Not a repo"));
41 }
42
43 const parts: string[] = [];
44 if (gitStatus.hasWorkingTreeChanges) {
45 parts.push(
46 resolve(
47 msg`${plural(
48 { count: gitStatus.workingTree.files.length },
49 {
50 one: part`${{ count: gitStatus.workingTree.files.length }} changed`,
51 other: part`${{ count: gitStatus.workingTree.files.length }} changed`,
52 },
53 )}`,
54 ),
55 );
56 } else if (gitStatus.aheadCount === 0 && gitStatus.behindCount === 0) {
57 parts.push(resolve(msg({ context: "git working tree has no changes" })`Clean`));
58 }
59 if (gitStatus.aheadCount > 0) {
60 parts.push(
61 resolve(
62 msg`${plural(
63 { count: gitStatus.aheadCount },
64 {
65 one: part`${{ count: gitStatus.aheadCount }} ahead`,
66 other: part`${{ count: gitStatus.aheadCount }} ahead`,
67 },
68 )}`,
69 ),
70 );
71 }
72 if (gitStatus.behindCount > 0) {
73 parts.push(
74 resolve(
75 msg`${plural(
76 { count: gitStatus.behindCount },
77 {
78 one: part`${{ count: gitStatus.behindCount }} behind`,
79 other: part`${{ count: gitStatus.behindCount }} behind`,
80 },
81 )}`,
82 ),
83 );
84 }
85 if (gitStatus.pr?.state === "open") {
86 const { shortLabel } = sourceControlClients.get(
87 gitStatus.sourceControlProvider?.kind,
88 ).changeRequest;
89 parts.push(`${shortLabel} #${gitStatus.pr.number}`);
90 }
91
92 return parts.join(" · ");
93}
94
95type QuickActionIcon =
96 | "arrow.down.circle"
97 | "arrow.up.right.circle"
98 | "checkmark.circle"
99 | "arrow.up.circle";
100
101export type ThreadGitMenuProps = {
102 readonly environmentId: EnvironmentId | string;
103 readonly threadId: ThreadId | string;
104 readonly currentBranch: string | null;
105 readonly hasThread?: boolean;
106 /** The project tracks repositories besides its folder, which then need not be one itself. */
107 readonly tracksRepositories?: boolean;
108 readonly gitStatus: VcsStatusResult | null;
109 readonly gitOperationLabel: string | null;
110 readonly onOpenFilesInspector?: () => void;
111 readonly onOpenGitInspector?: () => void;
112 readonly onMergeBack?: () => void;
113 readonly onPull: () => Promise<void>;
114 readonly onRunAction: (input: GitActionRequestInput) => Promise<GitRunStackedActionResult | null>;
115};
116
117export type ThreadGitControlsProps = ThreadGitMenuProps & {
118 readonly canOpenTerminal: boolean;
119 readonly canOperateTerminal: boolean;
120 readonly canOpenFiles: boolean;
121 readonly projectScripts: ReadonlyArray<ProjectScript>;
122 readonly terminalSessions: ReadonlyArray<TerminalMenuSession>;
123 readonly onOpenTerminal: (terminalId?: string | null) => void;
124 readonly onOpenNewTerminal: () => void;
125 readonly onRunProjectScript: (script: ProjectScript) => Promise<void>;
126};
127
128function useThreadGitControlModel(props: ThreadGitMenuProps) {
129 const navigation = useNavigation();
130 const gt = useGT();
131 const messages = useMessages();
132 const openPullRequest = useOpenPullRequest();
133 const environmentId = props.environmentId;
134 const canWriteSourceControl = useEnvironmentScope(
135 environmentId ? EnvironmentId.make(String(environmentId)) : null,
136 AuthSourceControlWriteScope,
137 );
138 const threadId = props.threadId;
139 const { gitStatus, gitOperationLabel, onPull, onRunAction } = props;
140
141 const currentBranchLabel = gitStatus?.refName ?? props.currentBranch ?? gt`Detached HEAD`;
142 const busy = gitOperationLabel !== null;
143 const isRepo = gitStatus?.isRepo ?? true;
144 const hasPrimaryRemote = gitStatus?.hasPrimaryRemote ?? false;
145 const isDefaultRef = gitStatus?.isDefaultRef ?? false;
146
147 const quickAction = (() => {
148 if (!isRepo) {
149 return {
150 label: gt`Git unavailable`,
151 disabled: true,
152 kind: "show_hint" as const,
153 hint: gt`This workspace is not a git repository.`,
154 };
155 }
156 const action = resolveQuickAction(gitStatus, busy, isDefaultRef, hasPrimaryRemote, messages);
157 return !canWriteSourceControl && (action.kind === "run_pull" || action.kind === "run_action")
158 ? {
159 ...action,
160 disabled: true,
161 hint: gt`This connection cannot change source control.`,
162 }
163 : action;
164 })();
165
166 const quickActionHint = quickAction.disabled
167 ? (quickAction.hint ?? gt`This action is unavailable.`)
168 : null;
169
170 const quickActionIcon: QuickActionIcon = (() => {
171 if (quickAction.kind === "run_pull") return "arrow.down.circle";
172 if (quickAction.kind === "open_pr") return "arrow.up.right.circle";
173 if (quickAction.kind === "run_action") {
174 if (quickAction.action === "commit") return "checkmark.circle";
175 if (quickAction.action === "push" || quickAction.action === "commit_push")
176 return "arrow.up.circle";
177 }
178 return "arrow.up.right.circle";
179 })();
180
181 const openExistingPr = async () => {
182 const term = changeRequestTermKind(
183 sourceControlClients.get(gitStatus?.sourceControlProvider?.kind).changeRequest,
184 );
185 const prUrl = gitStatus?.pr?.state === "open" ? gitStatus.pr.url : null;
186 if (!prUrl) {
187 Dialog.alert(
188 gt`${select(
189 { term },
190 {
191 mr: "No open MR",
192 cr: "No open change request",
193 other: "No open PR",
194 },
195 )}`,
196 gt`${select(
197 { term },
198 {
199 mr: "This branch does not have an open merge request.",
200 cr: "This branch does not have an open change request.",
201 other: "This branch does not have an open pull request.",
202 },
203 )}`,
204 );
205 return;
206 }
207 if (!(await openPullRequest(prUrl))) {
208 Dialog.alert(
209 gt`${select(
210 { term },
211 {
212 mr: "Unable to open MR",
213 cr: "Unable to open change request",
214 other: "Unable to open PR",
215 },
216 )}`,
217 gt`${select(
218 { term },
219 {
220 mr: "The merge request could not be opened.",
221 cr: "The change request could not be opened.",
222 other: "The pull request could not be opened.",
223 },
224 )}`,
225 );
226 }
227 };
228
229 const runActionWithPrompt = async (input: GitActionRequestInput) => {
230 if (!canWriteSourceControl) return;
231 const confirmableAction =
232 input.action === "push" ||
233 input.action === "create_pr" ||
234 input.action === "commit_push" ||
235 input.action === "commit_push_pr"
236 ? input.action
237 : null;
238 const branchName = gitStatus?.refName;
239 if (
240 branchName &&
241 confirmableAction &&
242 !input.featureBranch &&
243 requiresDefaultBranchConfirmation(input.action, isDefaultRef)
244 ) {
245 if (props.hasThread === false) {
246 Dialog.alert(
247 gt`Choose a feature branch`,
248 gt`Switch branches before publishing changes from this draft.`,
249 );
250 return;
251 }
252 navigation.navigate("GitConfirm", {
253 environmentId: String(environmentId),
254 threadId: String(threadId),
255 confirmAction: confirmableAction,
256 });
257 return;
258 }
259
260 await onRunAction(input);
261 };
262
263 const runQuickAction = async () => {
264 if (quickAction.disabled) return;
265 if (quickAction.kind === "open_pr") {
266 await openExistingPr();
267 return;
268 }
269 if (quickAction.kind === "run_pull") {
270 await onPull();
271 return;
272 }
273 if (quickAction.kind === "run_action" && quickAction.action) {
274 await runActionWithPrompt({ action: quickAction.action });
275 }
276 };
277
278 const openReview = () => {
279 navigation.navigate("ThreadReview", {
280 environmentId: EnvironmentId.make(String(environmentId)),
281 threadId: ThreadId.make(String(threadId)),
282 });
283 };
284
285 const openGitInspector = () => {
286 if (props.onOpenGitInspector) {
287 props.onOpenGitInspector();
288 return;
289 }
290 navigation.navigate("GitOverview", {
291 environmentId: String(environmentId),
292 threadId: String(threadId),
293 });
294 };
295
296 return {
297 currentBranchLabel,
298 isRepo,
299 openGitInspector,
300 openReview,
301 quickAction,
302 quickActionHint,
303 quickActionIcon,
304 runQuickAction,
305 };
306}
307
308export function threadTerminalMenu(
309 props: ThreadGitControlsProps,
310 resolve: MessageResolver = m,
311): AppBarMenu | null {
312 if (!props.canOpenTerminal) return null;
313 return {
314 title: resolve(msg("Terminal")),
315 icon: "terminal",
316 separateBackground: false,
317 items: [
318 ...(props.projectScripts.length > 0
319 ? props.projectScripts.map((script) => ({
320 id: `script-${script.id}`,
321 title: projectScriptMenuLabel(script, resolve),
322 icon: projectScriptMenuIcon(script.icon),
323 subtitle: script.command,
324 disabled: !props.canOperateTerminal,
325 onPress: () => void props.onRunProjectScript(script),
326 }))
327 : [
328 {
329 id: "script-none",
330 title: resolve(msg("No project scripts")),
331 icon: "play",
332 subtitle: resolve(msg("This project has no saved scripts yet")),
333 disabled: true,
334 onPress: () => {},
335 },
336 ]),
337 ...props.terminalSessions.map((session) => ({
338 id: `terminal-${session.terminalId}`,
339 title: session.displayLabel,
340 icon: "terminal",
341 subtitle: [
342 getTerminalStatusLabel(
343 {
344 status: session.status,
345 hasRunningSubprocess: session.hasRunningSubprocess,
346 },
347 resolve,
348 ),
349 basename(session.cwd),
350 ]
351 .filter(Boolean)
352 .join(" · "),
353 onPress: () => props.onOpenTerminal(session.terminalId),
354 })),
355 {
356 id: "terminal-new",
357 title: resolve(msg("Open new terminal")),
358 icon: "plus",
359 subtitle: resolve(msg("Start another shell for this thread")),
360 disabled: !props.canOperateTerminal,
361 onPress: props.onOpenNewTerminal,
362 },
363 ],
364 };
365}
366
367/** The thread's git menu, shared by the thread bar and Review. */
368export function useThreadGitMenuDefinition(props: ThreadGitMenuProps): AppBarMenu | null {
369 const model = useThreadGitControlModel(props);
370 const gt = useGT();
371 const messages = useMessages();
372 // A plain folder that tracks repositories has no branch of its own; its turns still have diffs.
373 const repositoriesOnly = !model.isRepo && props.tracksRepositories === true;
374 return {
375 title: gt`Git controls`,
376 icon: "point.topleft.down.curvedto.point.bottomright.up",
377 separateBackground: false,
378 items: [
379 ...(repositoriesOnly
380 ? // A worktree thread of such a folder still has a branch: its repositories are on it.
381 props.currentBranch === null
382 ? []
383 : [
384 {
385 id: "git-status",
386 title: compactMenuBranchLabel(props.currentBranch),
387 icon: "point.topleft.down.curvedto.point.bottomright.up",
388 disabled: true,
389 subtitle: gt`Repository worktrees`,
390 onPress: () => {},
391 },
392 ]
393 : [
394 {
395 id: "git-status",
396 title: compactMenuBranchLabel(model.currentBranchLabel),
397 icon: "point.topleft.down.curvedto.point.bottomright.up",
398 disabled: true,
399 subtitle: compactMenuStatus(props.gitStatus, messages),
400 onPress: () => {},
401 },
402 {
403 id: "git-quick-action",
404 title: model.quickAction.label,
405 icon: model.quickActionIcon,
406 disabled: model.quickAction.disabled,
407 subtitle: model.quickActionHint ?? undefined,
408 onPress: () => {
409 void model.runQuickAction();
410 },
411 },
412 ]),
413 {
414 id: "git-review",
415 title: gt`Review changes`,
416 icon: "text.bubble",
417 disabled: !(model.isRepo || repositoriesOnly) || props.hasThread === false,
418 subtitle:
419 props.hasThread === false
420 ? gt`Available after the first message`
421 : repositoriesOnly
422 ? gt`Turn diffs`
423 : gt`Turn diffs and worktree changes`,
424 onPress: model.openReview,
425 },
426 ...(props.onMergeBack
427 ? [
428 {
429 id: "git-merge-back",
430 title: gt`Merge back to source`,
431 icon: PullRequestGlyph.merged,
432 subtitle: gt`Bring this thread's latest turn into its source`,
433 onPress: props.onMergeBack,
434 },
435 ]
436 : []),
437 {
438 id: "git-more",
439 title: gt({ context: "menu item that opens more git actions" })`More`,
440 icon: "ellipsis",
441 disabled: props.hasThread === false,
442 subtitle:
443 props.hasThread === false
444 ? gt`Available after the first message`
445 : repositoriesOnly
446 ? gt`Repositories`
447 : props.tracksRepositories === true
448 ? gt`Commit, branches, repositories`
449 : gt`Commit, files, branches`,
450 onPress: model.openGitInspector,
451 },
452 ],
453 };
454}