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

threadRepositories.ts

739 lines27.9 KB

1import { mFallback, msg } from "gt-i18n";
2import type { MFunctionType } from "gt-i18n/types";
3import {
4 repositoryRewindCheckpoint,
5 TASK_FOLDER_DEFAULT_REPOSITORIES_MAX,
6 type TaskFolder,
7} from "@t3tools/contracts";
8import type {
9 CheckpointScopeId,
10 OrchestrationV2Checkpoint,
11 OrchestrationV2CheckpointFileTotals,
12 OrchestrationV2CheckpointScope,
13 OrchestrationV2ThreadProjection,
14 RunId,
15 ThreadTurnRepositoryDiff,
16 VcsStatusResult,
17 WorkspaceFolder,
18} from "@t3tools/contracts";
19import { isAbsolutePath } from "@t3tools/shared/path";
20​
21type ChangedFiles = OrchestrationV2Checkpoint["files"];
22​
23/** One tracked Git repository a thread reaches. */
24export interface ThreadRepositoryScope {
25 readonly scopeId: CheckpointScopeId;
26 /** Display name. */
27 readonly name: string;
28 /** Stable identity; matches `ThreadTurnDiff.repositories[].repositoryPath`. */
29 readonly repositoryPath: string;
30 /** The repository folder on the environment's disk; file paths resolve against it. */
31 readonly cwd: string;
32 /**
33 * The repository folder from the thread's folder, `/`-separated; starts with `../` outside it.
34 * Absent when the two folders share no root.
35 */
36 readonly relativePath?: string;
38​
39/** What one turn changed in one repository. `files` paths are relative to the repository. */
40export interface TurnRepositoryChanges extends ThreadRepositoryScope {
41 /** May be a prefix of the changed files when `filesTotal` is set. */
42 readonly files: ChangedFiles;
43 readonly filesTotal?: OrchestrationV2CheckpointFileTotals;
44 /** The turn changed this repository, but nothing was recorded before it to compare with. */
45 readonly baselineMissing: boolean;
47​
48interface ChangedFileList {
49 readonly files: ChangedFiles;
50 readonly filesTotal?: OrchestrationV2CheckpointFileTotals | undefined;
52​
53/** A turn's own files plus its repositories; `ThreadCheckpointSummary` has this shape. */
54export interface TurnChangesSource extends ChangedFileList {
55 readonly repositories?: ReadonlyArray<TurnRepositoryChanges> | undefined;
57​
58export interface TurnChanges {
59 /** Files changed in the thread's own folder, relative to it. */
60 readonly rootFiles: ChangedFiles;
61 readonly repositories: ReadonlyArray<TurnRepositoryChanges>;
62 /** Across the thread's folder and every repository. */
63 readonly totals: OrchestrationV2CheckpointFileTotals;
65​
66/** One patch of a turn diff. Its file paths are relative to `relativePath`. */
67export interface TurnDiffSection {
68 readonly key: string;
69 readonly name: string;
70 /** Null for the thread's own folder. */
71 readonly repositoryPath: string | null;
72 /** Empty for the thread's own folder. */
73 readonly relativePath: string;
74 readonly diff: string;
76​
77const ROOT_SECTION_KEY = ".";
78const NO_REPOSITORY_CHANGES: ReadonlyArray<TurnRepositoryChanges> = Object.freeze([]);
79const NO_TURN_REPOSITORY_CHANGES: ReadonlyMap<
80 RunId,
81 ReadonlyArray<TurnRepositoryChanges>
82> = new Map();
83​
84export function isRepositoryCheckpointScope(
85 scope: Pick<OrchestrationV2CheckpointScope, "repositoryPath">,
86): boolean {
87 return typeof scope.repositoryPath === "string";
89​
90/** Scopes whose checkpoints belong to a repository, never to the thread's own timeline. */
91export function repositoryCheckpointScopeIds(
92 scopes: ReadonlyArray<Pick<OrchestrationV2CheckpointScope, "id" | "repositoryPath">>,
93): ReadonlySet<CheckpointScopeId> {
94 return new Set(scopes.flatMap((scope) => (isRepositoryCheckpointScope(scope) ? [scope.id] : [])));
96​
97/**
98 * What a rewind to `checkpoint`, the thread's own rewind target, can restore on disk: every file,
99 * only the repositories of a task folder whose project folder has no snapshot, or nothing.
100 * The server refuses a file rewind this does not offer.
101 */
102export function rewindFileRestore(input: {
103 readonly projection: Pick<OrchestrationV2ThreadProjection, "checkpoints" | "checkpointScopes">;
104 readonly checkpoint: Pick<OrchestrationV2Checkpoint, "status" | "appRunOrdinal"> | undefined;
105 readonly taskFolder: Pick<TaskFolder, "projectIsWorktree"> | null | undefined;
106}): "files" | "repositories" | null {
107 const { checkpoint, projection } = input;
108 if (checkpoint === undefined) return null;
109 if (checkpoint.status === "ready") return "files";
110 if (checkpoint.status !== "missing" || input.taskFolder?.projectIsWorktree !== false) return null;
111 const targetOrdinal = checkpoint.appRunOrdinal ?? 0;
112 return projection.checkpointScopes.some(
113 (scope) =>
114 isRepositoryCheckpointScope(scope) &&
115 repositoryRewindCheckpoint(
116 projection.checkpoints.filter((candidate) => candidate.scopeId === scope.id),
117 targetOrdinal,
118 ) !== null,
119 )
120 ? "repositories"
121 : null;
123​
124function pathSegments(path: string): { root: string; segments: string[] } | undefined {
125 const normalized = path.replaceAll("\\", "/");
126 const segments = normalized.split("/").filter((segment) => segment.length > 0);
127 if (normalized.startsWith("/")) return { root: "/", segments };
128 const drive = segments[0];
129 if (drive === undefined || !/^[a-zA-Z]:$/.test(drive)) return undefined;
130 return { root: drive.toLowerCase(), segments: segments.slice(1) };
132​
133function relativeFolderPath(from: string, to: string): string | undefined {
134 const source = pathSegments(from);
135 const target = pathSegments(to);
136 if (source === undefined || target === undefined || source.root !== target.root) {
137 return undefined;
138 }
139 const same = (left: string, right: string) =>
140 source.root === "/" ? left === right : left.toLowerCase() === right.toLowerCase();
141 let shared = 0;
142 while (
143 shared < source.segments.length &&
144 shared < target.segments.length &&
145 same(source.segments[shared]!, target.segments[shared]!)
146 ) {
147 shared += 1;
148 }
149 return [...source.segments.slice(shared).map(() => ".."), ...target.segments.slice(shared)].join(
150 "/",
151 );
153​
154/** Whether a `/`-separated path from a folder stays inside that folder. */
155export function isRelativePathInsideFolder(relativePath: string): boolean {
156 return relativePath !== ".." && !relativePath.startsWith("../") && !isAbsolutePath(relativePath);
158​
159function repositoryScope(
160 scope: OrchestrationV2CheckpointScope,
161 repositoryPath: string,
162 threadCwd: string | undefined,
163): ThreadRepositoryScope {
164 const relativePath =
165 threadCwd === undefined ? undefined : relativeFolderPath(threadCwd, scope.cwd);
166 return {
167 scopeId: scope.id,
168 name: scope.label ?? scope.cwd.replaceAll("\\", "/").split("/").findLast(Boolean) ?? scope.cwd,
169 repositoryPath,
170 cwd: scope.cwd,
171 ...(relativePath === undefined ? {} : { relativePath }),
172 };
174​
175function byNameThenPath(left: ThreadRepositoryScope, right: ThreadRepositoryScope): number {
176 return (
177 left.name.localeCompare(right.name) || left.repositoryPath.localeCompare(right.repositoryPath)
178 );
180​
181/** The repositories a thread reaches, by name and then path. */
182export function threadRepositoryScopes(
183 projection: Pick<OrchestrationV2ThreadProjection, "checkpointScopes">,
184): ReadonlyArray<ThreadRepositoryScope> {
185 const scopes = projection.checkpointScopes;
186 return scopes
187 .flatMap((scope) =>
188 scope.repositoryPath === undefined
189 ? []
190 : [
191 repositoryScope(
192 scope,
193 scope.repositoryPath,
194 scopes.find((candidate) => candidate.id === scope.parentScopeId)?.cwd,
195 ),
196 ],
197 )
198 .sort(byNameThenPath);
200​
201// Rows compare a turn's repositories by identity, so an unchanged turn keeps the same objects
202// while later turns append checkpoints.
203const changesByCheckpoint = new WeakMap<
204 OrchestrationV2Checkpoint,
205 {
206 readonly scope: OrchestrationV2CheckpointScope;
207 readonly threadCwd: string | undefined;
208 readonly changes: TurnRepositoryChanges;
209 }
210>();
211const turnChangesByFirst = new WeakMap<
212 TurnRepositoryChanges,
213 ReadonlyArray<TurnRepositoryChanges>
214>();
215​
216/**
217 * Per run, the repositories it changed, by name and then path. A run that changed none has no
218 * entry. Unchanged runs keep their array across calls.
219 */
220export function deriveTurnRepositoryChanges(
221 projection: Pick<OrchestrationV2ThreadProjection, "checkpoints" | "checkpointScopes">,
222): ReadonlyMap<RunId, ReadonlyArray<TurnRepositoryChanges>> {
223 const scopes = projection.checkpointScopes;
224 if (!scopes.some(isRepositoryCheckpointScope)) return NO_TURN_REPOSITORY_CHANGES;
225 const scopeById = new Map(scopes.map((scope) => [scope.id, scope]));
226 const withoutBaseline = new Set<string>();
227 for (const checkpoint of projection.checkpoints) {
228 if (checkpoint.status === "missing") {
229 withoutBaseline.add(`${checkpoint.scopeId}\u0000${checkpoint.ordinalWithinScope + 1}`);
230 }
231 }
232 const byRun = new Map<RunId, TurnRepositoryChanges[]>();
233 for (const checkpoint of projection.checkpoints) {
234 if (checkpoint.runId === null || checkpoint.status !== "ready") continue;
235 const scope = scopeById.get(checkpoint.scopeId);
236 if (scope?.repositoryPath === undefined) continue;
237 const baselineMissing =
238 checkpoint.files.length === 0 &&
239 withoutBaseline.has(`${checkpoint.scopeId}\u0000${checkpoint.ordinalWithinScope}`);
240 if (checkpoint.files.length === 0 && !baselineMissing) continue;
241 const threadCwd =
242 scope.parentScopeId === null ? undefined : scopeById.get(scope.parentScopeId)?.cwd;
243 const cached = changesByCheckpoint.get(checkpoint);
244 let changes = cached?.changes;
245 if (
246 cached === undefined ||
247 changes === undefined ||
248 cached.scope !== scope ||
249 cached.threadCwd !== threadCwd ||
250 changes.baselineMissing !== baselineMissing
251 ) {
252 changes = {
253 ...repositoryScope(scope, scope.repositoryPath, threadCwd),
254 files: checkpoint.files,
255 ...(checkpoint.filesTotal === undefined ? {} : { filesTotal: checkpoint.filesTotal }),
256 baselineMissing,
257 };
258 changesByCheckpoint.set(checkpoint, { scope, threadCwd, changes });
259 }
260 const forRun = byRun.get(checkpoint.runId);
261 if (forRun === undefined) byRun.set(checkpoint.runId, [changes]);
262 else forRun.push(changes);
263 }
264 const stable = new Map<RunId, ReadonlyArray<TurnRepositoryChanges>>();
265 for (const [runId, repositories] of byRun) {
266 repositories.sort(byNameThenPath);
267 const first = repositories[0]!;
268 const previous = turnChangesByFirst.get(first);
269 if (
270 previous !== undefined &&
271 previous.length === repositories.length &&
272 previous.every((entry, index) => entry === repositories[index])
273 ) {
274 stable.set(runId, previous);
275 } else {
276 turnChangesByFirst.set(first, repositories);
277 stable.set(runId, repositories);
278 }
279 }
280 return stable;
282​
283/** Totals for a file list that may be a prefix of what changed. */
284function changedFileTotals(list: ChangedFileList): OrchestrationV2CheckpointFileTotals {
285 if (list.filesTotal !== undefined) return list.filesTotal;
286 let additions = 0;
287 let deletions = 0;
288 for (const file of list.files) {
289 additions += file.additions;
290 deletions += file.deletions;
291 }
292 return { count: list.files.length, additions, deletions };
294​
295/** A turn's changed files: the thread folder's own, then each repository's, with totals. */
296export function turnChanges(turn: TurnChangesSource): TurnChanges {
297 const repositories = turn.repositories ?? NO_REPOSITORY_CHANGES;
298 const totals = { ...changedFileTotals(turn) };
299 for (const repository of repositories) {
300 const repositoryTotals = changedFileTotals(repository);
301 totals.count += repositoryTotals.count;
302 totals.additions += repositoryTotals.additions;
303 totals.deletions += repositoryTotals.deletions;
304 }
305 return { rootFiles: turn.files, repositories, totals };
307​
308/**
309 * Whether a turn has changes to show. The thread folder's own checkpoint need not be ready: a
310 * plain folder holding repositories never has one, and its turns still change those repositories.
311 */
312export function turnHasChanges(turn: TurnChangesSource): boolean {
313 return turn.files.length > 0 || (turn.repositories?.length ?? 0) > 0;
315​
316/** A repository file's path from the thread's folder, as the turn diff sections name it. */
317export function repositoryFilePath(relativePath: string, filePath: string): string {
318 return relativePath === "" || relativePath === "." ? filePath : `${relativePath}/${filePath}`;
320​
321/**
322 * The patches of a turn diff, the thread folder's own first. Empty patches are left out, so a
323 * diff without repositories gives its one patch or nothing.
324 */
325export function turnDiffSections(
326 diff: {
327 readonly diff: string;
328 readonly repositories?: ReadonlyArray<ThreadTurnRepositoryDiff> | undefined;
329 },
330 rootName: string,
331): ReadonlyArray<TurnDiffSection> {
332 const root: ReadonlyArray<TurnDiffSection> =
333 diff.diff.trim() === ""
334 ? []
335 : [
336 {
337 key: ROOT_SECTION_KEY,
338 name: rootName,
339 repositoryPath: null,
340 relativePath: "",
341 diff: diff.diff,
342 },
343 ];
344 return [
345 ...root,
346 ...(diff.repositories ?? []).flatMap((repository) =>
347 repository.diff.trim() === ""
348 ? []
349 : [
350 {
351 key: repository.repositoryPath,
352 name: repository.name,
353 repositoryPath: repository.repositoryPath,
354 relativePath: repository.relativePath,
355 diff: repository.diff,
356 },
357 ],
358 ),
359 ];
361​
362/**
363 * The repository section a thread-relative path belongs to, and the path inside that repository.
364 * Null for a file of the thread's own folder.
365 */
366export function repositorySectionForPath(
367 sections: ReadonlyArray<TurnDiffSection>,
368 filePath: string,
369): { readonly section: TurnDiffSection; readonly path: string } | null {
370 let match: { readonly section: TurnDiffSection; readonly path: string } | null = null;
371 for (const section of sections) {
372 if (section.repositoryPath === null || section.relativePath === "") continue;
373 const prefix = `${section.relativePath}/`;
374 if (!filePath.startsWith(prefix)) continue;
375 if (match === null || section.relativePath.length > match.section.relativePath.length) {
376 match = { section, path: filePath.slice(prefix.length) };
377 }
378 }
379 return match;
381​
382/** How many repository sections a thread shows before the rest fold behind "Show N more". */
383export const THREAD_REPOSITORY_SECTIONS_VISIBLE = 4;
384​
385/** A tracked repository the user asked to see in a thread, besides those the thread changed. */
386export interface PinnedThreadRepository {
387 /** The tracked folder's path; matches `ThreadRepositoryScope.repositoryPath`. */
388 readonly repositoryPath: string;
389 readonly name: string;
391​
392/** One repository a thread shows Git state and actions for. */
393export interface ThreadRepositorySection {
394 /** Stable across renders and reorders; the repository's path. */
395 readonly key: string;
396 readonly name: string;
397 /** The folder Git commands run in. */
398 readonly cwd: string;
399 /**
400 * Pinned sections can be removed; changed ones stay for as long as the thread has them. A
401 * `worktree` section is the thread's own worktree of that repository.
402 */
403 readonly origin: "pinned" | "changed" | "worktree";
405​
406export interface ThreadRepositorySections {
407 readonly visible: ReadonlyArray<ThreadRepositorySection>;
408 /** Folded away until the user asks for them. Clients render and subscribe for none of these. */
409 readonly hidden: ReadonlyArray<ThreadRepositorySection>;
411​
412const NO_SECTIONS: ThreadRepositorySections = Object.freeze({
413 visible: Object.freeze([]),
414 hidden: Object.freeze([]),
415});
416​
417/**
418 * The repositories a thread changed, most recently changed first. A repository no turn has a
419 * checkpoint for yet sorts last, by name.
420 */
421export function threadChangedRepositories(
422 projection: Pick<OrchestrationV2ThreadProjection, "checkpoints" | "checkpointScopes">,
423): ReadonlyArray<ThreadRepositoryScope> {
424 const scopes = threadRepositoryScopes(projection);
425 if (scopes.length < 2) return scopes;
426 const lastChange = new Map<CheckpointScopeId, number>();
427 // A repository scope's ordinal is the run's; a loaded snapshot is not in capture order.
428 for (const checkpoint of projection.checkpoints) {
429 if (checkpoint.runId === null) continue;
430 const latest = lastChange.get(checkpoint.scopeId) ?? -1;
431 if (checkpoint.ordinalWithinScope > latest) {
432 lastChange.set(checkpoint.scopeId, checkpoint.ordinalWithinScope);
433 }
434 }
435 // `scopes` is by name already, and the sort is stable.
436 return [...scopes].sort(
437 (left, right) => (lastChange.get(right.scopeId) ?? -1) - (lastChange.get(left.scopeId) ?? -1),
438 );
440​
441/** A repository whose uncommitted and branch changes a thread can show. */
442export type ThreadGitRepository = Pick<ThreadRepositoryScope, "repositoryPath" | "name" | "cwd">;
443​
444/**
445 * Every repository a thread can read Git changes of: the ones it changed first, then the rest of
446 * its task folder's worktrees, or of the project's tracked repositories when it runs in place.
447 */
448export function threadGitRepositories(input: {
449 readonly changed: ReadonlyArray<ThreadGitRepository>;
450 readonly taskFolder: Pick<TaskFolder, "repositories"> | null;
451 /** The project's folders, for a thread in the project folder itself; null otherwise. */
452 readonly folders: ReadonlyArray<Pick<WorkspaceFolder, "path" | "name" | "state">> | null;
453 readonly threadCwd: string | null;
454}): ReadonlyArray<ThreadGitRepository> {
455 const reached: ReadonlyArray<ThreadGitRepository> =
456 input.taskFolder !== null
457 ? input.taskFolder.repositories.map((repository) => ({
458 repositoryPath: repository.repositoryPath,
459 name: repository.name,
460 cwd: repository.worktreePath,
461 }))
462 : (input.folders ?? []).flatMap((folder) =>
463 folder.state === "git" && folder.path !== input.threadCwd
464 ? [{ repositoryPath: folder.path, name: folder.name, cwd: folder.path }]
465 : [],
466 );
467 if (reached.length === 0) return input.changed;
468 // A checkpoint scope keeps the folder it was captured in, which a moved thread has left.
469 const reachedByPath = new Map(
470 reached.map((repository) => [repository.repositoryPath, repository]),
471 );
472 const listed = new Set(input.changed.map((repository) => repository.repositoryPath));
473 return [
474 ...input.changed.map(
475 (repository) => reachedByPath.get(repository.repositoryPath) ?? repository,
476 ),
477 ...reached.filter((repository) => !listed.has(repository.repositoryPath)),
478 ];
480​
481/**
482 * A task folder's repositories, each bound to its worktree: changed ones first, then the rest.
483 * A changed repository inside one of those worktrees, such as a submodule, follows them.
484 */
485function taskFolderSections(
486 taskFolder: Pick<TaskFolder, "repositories" | "root">,
487 changed: ReadonlyArray<ThreadRepositoryScope>,
488): ThreadRepositorySection[] {
489 const byPath = new Map(
490 taskFolder.repositories.map((repository) => [repository.repositoryPath, repository]),
491 );
492 const ordered = new Set<string>();
493 for (const scope of changed) {
494 if (byPath.has(scope.repositoryPath)) ordered.add(scope.repositoryPath);
495 }
496 for (const repository of taskFolder.repositories) ordered.add(repository.repositoryPath);
497 const worktrees = [...ordered].map((repositoryPath) => {
498 const repository = byPath.get(repositoryPath)!;
499 return {
500 key: repositoryPath,
501 name: repository.name,
502 cwd: repository.worktreePath,
503 origin: "worktree" as const,
504 };
505 });
506 const inside = changed.flatMap((scope) => {
507 const relative = relativeFolderPath(taskFolder.root, scope.cwd);
508 return byPath.has(scope.repositoryPath) ||
509 relative === undefined ||
510 !isRelativePathInsideFolder(relative)
511 ? []
512 : [
513 {
514 key: scope.repositoryPath,
515 name: scope.name,
516 cwd: scope.cwd,
517 origin: "changed" as const,
518 },
519 ];
520 });
521 return [...worktrees, ...inside];
523​
524/**
525 * The repository sections of a thread: pinned ones in the order they were pinned, then the ones
526 * the thread changed. `threadCwd` is the thread's own folder, which has its own Git controls.
527 *
528 * A thread with a `taskFolder` lists that folder's repositories instead, changed or not, and
529 * never a pin or a changed repository outside it: those would be someone else's checkout.
530 */
531export function threadRepositorySections(input: {
532 readonly changed: ReadonlyArray<ThreadRepositoryScope>;
533 readonly pinned: ReadonlyArray<PinnedThreadRepository>;
534 readonly threadCwd: string | null;
535 readonly showAll: boolean;
536 readonly taskFolder?: Pick<TaskFolder, "repositories" | "root"> | null | undefined;
537 /**
538 * False for a thread that reaches no tracked repository: a project that tracks none, or a
539 * single worktree. It lists what it changed, such as a submodule, and no pin.
540 */
541 readonly reachesTracked?: boolean | undefined;
542}): ThreadRepositorySections {
543 const sections: ThreadRepositorySection[] = [];
544 if (input.taskFolder != null) {
545 sections.push(...taskFolderSections(input.taskFolder, input.changed));
546 } else {
547 const seen = new Set<string>(input.threadCwd === null ? [] : [input.threadCwd]);
548 const add = (section: ThreadRepositorySection) => {
549 if (seen.has(section.key)) return;
550 seen.add(section.key);
551 sections.push(section);
552 };
553 for (const pin of input.reachesTracked === false ? [] : input.pinned) {
554 add({ key: pin.repositoryPath, name: pin.name, cwd: pin.repositoryPath, origin: "pinned" });
555 }
556 for (const scope of input.changed) {
557 add({ key: scope.repositoryPath, name: scope.name, cwd: scope.cwd, origin: "changed" });
558 }
559 }
560 if (sections.length === 0) return NO_SECTIONS;
561 if (input.showAll || sections.length <= THREAD_REPOSITORY_SECTIONS_VISIBLE) {
562 return { visible: sections, hidden: NO_SECTIONS.hidden };
563 }
564 return {
565 visible: sections.slice(0, THREAD_REPOSITORY_SECTIONS_VISIBLE),
566 hidden: sections.slice(THREAD_REPOSITORY_SECTIONS_VISIBLE),
567 };
569​
570/** Adds a pin at the end; pinning a repository twice keeps its place. */
571export function pinThreadRepository(
572 pinned: ReadonlyArray<PinnedThreadRepository>,
573 repository: PinnedThreadRepository,
574): ReadonlyArray<PinnedThreadRepository> {
575 return pinned.some((entry) => entry.repositoryPath === repository.repositoryPath)
576 ? pinned
577 : [...pinned, repository];
579​
580export function unpinThreadRepository(
581 pinned: ReadonlyArray<PinnedThreadRepository>,
582 repositoryPath: string,
583): ReadonlyArray<PinnedThreadRepository> {
584 const next = pinned.filter((entry) => entry.repositoryPath !== repositoryPath);
585 return next.length === pinned.length ? pinned : next;
587​
588/** The tracked Git repositories a thread can still add: not its own folder, not shown yet. */
589export function pinnableThreadRepositories(input: {
590 readonly folders: ReadonlyArray<Pick<WorkspaceFolder, "path" | "name" | "state">>;
591 readonly sections: ThreadRepositorySections;
592 readonly threadCwd: string | null;
593}): ReadonlyArray<PinnedThreadRepository> {
594 const shown = new Set(
595 [...input.sections.visible, ...input.sections.hidden].map((section) => section.key),
596 );
597 return input.folders.flatMap((folder) =>
598 folder.state !== "git" || folder.path === input.threadCwd || shown.has(folder.path)
599 ? []
600 : [{ repositoryPath: folder.path, name: folder.name }],
601 );
603​
604/** The tracked Git repositories a task folder has no worktree for yet. */
605export function addableTaskFolderRepositories(input: {
606 readonly folders: ReadonlyArray<Pick<WorkspaceFolder, "path" | "name" | "state">>;
607 readonly taskFolder: Pick<TaskFolder, "projectRoot" | "repositories">;
608}): ReadonlyArray<PinnedThreadRepository> {
609 const present = new Set(
610 input.taskFolder.repositories.map((repository) => repository.repositoryPath),
611 );
612 return input.folders.flatMap((folder) =>
613 folder.state !== "git" ||
614 folder.path === input.taskFolder.projectRoot ||
615 present.has(folder.path)
616 ? []
617 : [{ repositoryPath: folder.path, name: folder.name }],
618 );
620​
621/** A tracked Git repository a new worktree thread can get a worktree of. */
622export interface WorktreeRepositoryChoice {
623 /** The tracked folder's path; what `workspaceStrategy.repositories[].path` takes. */
624 readonly repositoryPath: string;
625 readonly name: string;
626 /** The folder from the project folder, `/`-separated, when it sits inside it. */
627 readonly relativePath?: string;
629​
630/** A project's tracked Git folders, in the project's order. */
631export function worktreeRepositoryChoices(input: {
632 readonly folders: ReadonlyArray<Pick<WorkspaceFolder, "path" | "name" | "state">>;
633 readonly projectRoot: string;
634}): ReadonlyArray<WorktreeRepositoryChoice> {
635 return input.folders.flatMap((folder) => {
636 if (folder.state !== "git") return [];
637 const relativePath = relativeFolderPath(input.projectRoot, folder.path);
638 return [
639 {
640 repositoryPath: folder.path,
641 name: folder.name,
642 ...(relativePath === undefined ||
643 relativePath === "" ||
644 !isRelativePathInsideFolder(relativePath)
645 ? {}
646 : { relativePath }),
647 },
648 ];
649 });
651​
652export interface WorktreeRepositorySelection {
653 /** Chosen tracked paths, in the choices' order. */
654 readonly selected: ReadonlyArray<string>;
655 /** Short text for the control that opens the checklist. */
656 readonly label: string;
657 /** Nothing is selected only because the project tracks too many to take them all by default. */
658 readonly needsChoice: boolean;
659 /**
660 * What the launch sends as `workspaceStrategy.repositories`. Undefined until the user chooses,
661 * so the server applies its own default.
662 */
663 readonly strategyRepositories: ReadonlyArray<{ readonly path: string }> | undefined;
665​
666/**
667 * Which repositories a new worktree thread takes. Without a choice it mirrors the server: all of
668 * them up to `TASK_FOLDER_DEFAULT_REPOSITORIES_MAX`, none above. Chosen paths the project no
669 * longer tracks are dropped once its folders are known.
670 */
671export function resolveWorktreeRepositorySelection(
672 input: {
673 /** Null while the project's tracked folders are still loading. */
674 readonly choices: ReadonlyArray<WorktreeRepositoryChoice> | null;
675 readonly chosen: ReadonlyArray<string> | undefined;
676 },
677 resolve: MFunctionType = mFallback,
678): WorktreeRepositorySelection {
679 const { choices, chosen } = input;
680 if (choices === null) {
681 const selected = chosen ?? [];
682 return {
683 selected,
684 label: resolve(msg("Repositories")),
685 needsChoice: false,
686 strategyRepositories: chosen?.map((path) => ({ path })),
687 };
688 }
689 const takesAllByDefault = choices.length <= TASK_FOLDER_DEFAULT_REPOSITORIES_MAX;
690 const wanted = chosen === undefined ? null : new Set(chosen);
691 const selected = choices.flatMap((choice) =>
692 (wanted === null ? takesAllByDefault : wanted.has(choice.repositoryPath))
693 ? [choice.repositoryPath]
694 : [],
695 );
696 const needsChoice = chosen === undefined && !takesAllByDefault;
697 return {
698 selected,
699 label: needsChoice
700 ? resolve(msg("Choose repositories"))
701 : selected.length === 0
702 ? resolve(msg("No repositories"))
703 : selected.length !== 1 && selected.length === choices.length
704 ? resolve(msg("All repositories"))
705 : resolve(
706 msg("{count, plural, one {{count} repository} other {{count} repositories}}", {
707 count: selected.length,
708 }),
709 ),
710 needsChoice,
711 strategyRepositories: chosen === undefined ? undefined : selected.map((path) => ({ path })),
712 };
714​
715/** What a collapsed repository section shows; null until the first status arrives. */
716export interface RepositorySectionSummary {
717 /** Null on a detached HEAD. */
718 readonly branch: string | null;
719 readonly isRepository: boolean;
720 readonly changedFiles: number;
721 readonly insertions: number;
722 readonly deletions: number;
723 /** The branch's pull request, from the last remote read anyone made of this folder. */
724 readonly pullRequest: NonNullable<VcsStatusResult["pr"]> | null;
726​
727export function repositorySectionSummary(
728 status: VcsStatusResult | null | undefined,
729): RepositorySectionSummary | null {
730 if (status == null) return null;
731 return {
732 branch: status.refName,
733 isRepository: status.isRepo,
734 changedFiles: status.workingTree.files.length,
735 insertions: status.workingTree.insertions,
736 deletions: status.workingTree.deletions,
737 pullRequest: status.pr,
738 };