From cf1abeee436bf6db811455198b54c16f645a7412 Mon Sep 17 00:00:00 2001 From: Michael Yong Date: Tue, 3 Nov 2026 12:40:29 -0800 Subject: [PATCH 1/2] Delete dead code left by the composer and git plugin moves - Remove useUpdateEnvironment, which was built but never mutated, and its always-false isPending read in ThreadDetailView. - Remove isGitDiffFixedPanelTab, EMPTY_ORDERED_MENTION_SUGGESTIONS, the echoed useCommandSuggestions().triggers field, and ComposerBox's never-passed maxHeight prop. - Use apps/app's cached composerDraftFromPromptDraft in ComposerBox and drop the uncached client-core copy. - Drop nine unused @tiptap/* dependencies from @bb/app; @tiptap/core and @tiptap/pm stay as devDependencies for PromptBoxInternal.test.tsx. - Replace host-workspace's porcelain v1 quoted-path parser with a check of the two status letters, which is all the conflict check reads. - Reuse locks.ts's checkout admission lock and transcript.ts's throwIfProvisionAborted instead of host-workspace copies; drop a dead withGitRefMutationLock re-export and file-internal exports. - Correct stale docs and comments (protocol 255, ComposerBox owns submit, host ultracode decoration, bundle-budget note). Co-Authored-By: Claude Opus 5.5 --- apps/app/bundle-budget.json | 2 +- apps/app/package.json | 13 +- apps/app/src/app.css | 4 +- .../src/components/promptbox/ComposerBox.tsx | 6 +- .../hooks/mutations/environment-mutations.ts | 63 -------- apps/app/src/hooks/useCommandSuggestions.ts | 2 - apps/app/src/lib/fixed-panel-tabs-state.ts | 1 - apps/app/src/test/fixtures/composer-search.ts | 1 - .../views/thread-detail/ThreadDetailView.tsx | 5 +- docs/api_to_audit.md | 7 +- docs/vcs-process-admission.md | 2 +- .../src/panel/fixed-panel-tabs-state.ts | 10 -- .../src/prompt/mentions/composer-mention.ts | 10 -- .../src/prompt/mentions/mention-candidates.ts | 5 - .../client-core/test/composer-mention.test.ts | 7 +- packages/environment-provider-host/src/git.ts | 2 +- .../environment-provider-host/src/locks.ts | 2 +- .../src/workspace-git.ts | 6 +- .../src/checkout-mutation-lock.ts | 44 +---- packages/host-workspace/src/git.ts | 153 +----------------- packages/host-workspace/src/index.ts | 1 - packages/host-workspace/src/provision.ts | 15 +- packages/host-workspace/test/git.test.ts | 65 -------- pnpm-lock.yaml | 39 +---- 24 files changed, 42 insertions(+), 423 deletions(-) delete mode 100644 apps/app/src/hooks/mutations/environment-mutations.ts diff --git a/apps/app/bundle-budget.json b/apps/app/bundle-budget.json index 1eeb66f1498..4dd135c4acb 100644 --- a/apps/app/bundle-budget.json +++ b/apps/app/bundle-budget.json @@ -75,7 +75,7 @@ "NewThreadPage decide how slow bb feels on a phone after boot. Their", "forbiddenPackages are the diff engine, math, file tree and terminal code", "that only a user action needs.", - "The composer (tiptap/prosemirror) is visible on both pages and is allowed.", + "The composer is the bundled Composer plugin, so core ships no tiptap.", "Run `node scripts/why-eager.mjs --from=views/SplitWorkspaceRoute.tsx `", "to print the static chain that pulled a package into the route.", "", diff --git a/apps/app/package.json b/apps/app/package.json index d9eaf15e1c3..c51b97026f7 100644 --- a/apps/app/package.json +++ b/apps/app/package.json @@ -54,17 +54,6 @@ "@radix-ui/react-tooltip": "^1.2.12", "@tanstack/react-query": "^5.62.0", "@tanstack/react-virtual": "3.14.20", - "@tiptap/core": "^3.26.0", - "@tiptap/extension-blockquote": "^3.26.0", - "@tiptap/extension-document": "^3.26.0", - "@tiptap/extension-hard-break": "^3.26.0", - "@tiptap/extension-mention": "^3.26.0", - "@tiptap/extension-paragraph": "^3.26.0", - "@tiptap/extension-text": "^3.26.0", - "@tiptap/extensions": "^3.26.0", - "@tiptap/pm": "^3.26.0", - "@tiptap/react": "^3.26.0", - "@tiptap/suggestion": "^3.26.0", "@xterm/addon-fit": "0.12.0-beta.292", "@xterm/addon-search": "0.17.0-beta.292", "@xterm/addon-unicode11": "^0.9.0", @@ -115,6 +104,8 @@ "@rolldown/plugin-babel": "^0.2.3", "@tailwindcss/vite": "^4.3.0", "@testing-library/react": "^16.3.2", + "@tiptap/core": "^3.26.0", + "@tiptap/pm": "^3.26.0", "@types/cacache": "^20.0.1", "@types/mdast": "^4.0.4", "@types/node": "^22.0.0", diff --git a/apps/app/src/app.css b/apps/app/src/app.css index 38ea2da94b9..bbaa98a58d3 100644 --- a/apps/app/src/app.css +++ b/apps/app/src/app.css @@ -193,8 +193,8 @@ /* * Light up the `ultracode` keyword in the prompt editor with animated purple - * sparkles (mirrors Claude Code). The wrapping span is added as a ProseMirror - * inline decoration (see prompt-ultracode-highlight-extension.ts); it stays + * sparkles (mirrors Claude Code). The wrapping span is added by the host's + * composer decoration source (see composer-decorations.ts); it stays * editable text, so this is paint-only. `background-clip: text` shimmers a * purple gradient through the glyphs, and two pseudo-element glints twinkle at * opposite corners. `prefers-reduced-motion` keeps the purple, drops motion. diff --git a/apps/app/src/components/promptbox/ComposerBox.tsx b/apps/app/src/components/promptbox/ComposerBox.tsx index 251573c2758..a4e3591d4fb 100644 --- a/apps/app/src/components/promptbox/ComposerBox.tsx +++ b/apps/app/src/components/promptbox/ComposerBox.tsx @@ -31,7 +31,6 @@ import type { } from "@get-bb/plugin-sdk"; import type { ThreadResponse } from "@bb/server-contract"; import { - composerDraftFromPromptDraft, DEFAULT_PLUGIN_MENTION_TRIGGER, promptDraftFromComposerDraft, type PromptDraftAttachment, @@ -94,6 +93,7 @@ import { usePluginFrontendLoadFailed, usePluginFrontendsSettled, } from "@/lib/plugin-frontend-boot-state"; +import { composerDraftFromPromptDraft } from "@/lib/plugin-composer-handle"; import { schedulePluginFrontendReconcile } from "@/lib/plugin-frontend-lazy"; import { useComposerInputLock } from "@/lib/plugin-sdk-hooks"; import { sdk } from "@/lib/sdk"; @@ -196,6 +196,7 @@ export type ComposerBoxProps = Omit< | "resolveMentionLink" | "attachments" | "history" + | "maxHeight" > & { typeahead: TypeaheadConfig; attachments?: AttachmentsConfig; @@ -497,8 +498,7 @@ function useComposerRendererHostApi({ const queryClient = useContext(QueryClientContext); const reportTypeaheadLayout = useContext(QueuedEditorTypeaheadLayoutContext); const isFocusedPane = useOptionalPaneContext()?.isFocused ?? true; - const availableMaxHeight = useContext(ComposerMaxHeightContext); - const maxHeight = input.maxHeight ?? availableMaxHeight; + const maxHeight = useContext(ComposerMaxHeightContext); const decorationSources = composerDecorationSources( resolvedEditor.effects, diff --git a/apps/app/src/hooks/mutations/environment-mutations.ts b/apps/app/src/hooks/mutations/environment-mutations.ts deleted file mode 100644 index 08621563529..00000000000 --- a/apps/app/src/hooks/mutations/environment-mutations.ts +++ /dev/null @@ -1,63 +0,0 @@ -import { useMutation, useQueryClient } from "@tanstack/react-query"; -import type { Environment } from "@bb/domain"; -import type { UpdateEnvironmentRequest } from "@bb/server-contract"; -import { sdk } from "@/lib/sdk"; -import { - beginEnvironmentNameUpdateTransaction, - completeEnvironmentNameUpdateTransaction, - rollbackEnvironmentNameUpdateTransaction, - type EnvironmentNameUpdateTransaction, -} from "../cache-owners/environment-workspace-cache-owner"; -type UpdateEnvironmentMutationRequest = { - id: string; -} & UpdateEnvironmentRequest; - -export function useUpdateEnvironment() { - const queryClient = useQueryClient(); - - return useMutation({ - meta: { - errorMessage: "Failed to update environment.", - showErrorToast: false, - }, - mutationFn: ({ id, ...request }: UpdateEnvironmentMutationRequest) => { - if (request.name !== undefined) { - return sdk.environments.update({ - environmentId: id, - name: request.name, - ...(request.mergeBaseBranch !== undefined - ? { mergeBaseBranch: request.mergeBaseBranch } - : {}), - }); - } - if (request.mergeBaseBranch !== undefined) { - return sdk.environments.update({ - environmentId: id, - mergeBaseBranch: request.mergeBaseBranch, - }); - } - throw new Error("Environment update requires at least one field"); - }, - onMutate: ({ - id, - name, - }): Promise | undefined => - name === undefined - ? undefined - : beginEnvironmentNameUpdateTransaction({ - environmentId: id, - name, - queryClient, - }), - onError: (_error, _variables, transaction) => { - rollbackEnvironmentNameUpdateTransaction({ queryClient, transaction }); - }, - onSuccess: (environment: Environment, _variables, transaction) => { - completeEnvironmentNameUpdateTransaction({ - environment, - queryClient, - transaction, - }); - }, - }); -} diff --git a/apps/app/src/hooks/useCommandSuggestions.ts b/apps/app/src/hooks/useCommandSuggestions.ts index db851cd769f..887338a9d52 100644 --- a/apps/app/src/hooks/useCommandSuggestions.ts +++ b/apps/app/src/hooks/useCommandSuggestions.ts @@ -27,7 +27,6 @@ export type CommandSuggestionSource = Omit< >; interface UseCommandSuggestionsResult { - triggers: readonly PromptMentionCommandTrigger[]; suggestions: ProviderCommandSuggestion[]; isLoading: boolean; isRefreshing: boolean; @@ -234,7 +233,6 @@ export function useCommandSuggestions( const isError = isActive && commandsQuery.isError; return { - triggers: args.skillsTriggers, suggestions, isLoading, isRefreshing, diff --git a/apps/app/src/lib/fixed-panel-tabs-state.ts b/apps/app/src/lib/fixed-panel-tabs-state.ts index 655ed0623d9..03e7296600d 100644 --- a/apps/app/src/lib/fixed-panel-tabs-state.ts +++ b/apps/app/src/lib/fixed-panel-tabs-state.ts @@ -13,7 +13,6 @@ export { buildFixedPanelTabId, createThreadInfoFixedPanelTab, createGitDiffFixedPanelTab, - isGitDiffFixedPanelTab, migrateLegacyFixedPanelTab, migrateLegacyFixedPanelTabId, createPluginFixedPanelTab, diff --git a/apps/app/src/test/fixtures/composer-search.ts b/apps/app/src/test/fixtures/composer-search.ts index 0807e8d7f7c..56f3ac1b96a 100644 --- a/apps/app/src/test/fixtures/composer-search.ts +++ b/apps/app/src/test/fixtures/composer-search.ts @@ -67,7 +67,6 @@ function fakeUseCommandSuggestions( ): ReturnType { composerSearchQueries.command(args.query, args.activeTrigger); return { - triggers: args.skillsTriggers, suggestions: [...state.commandSuggestions], isLoading: false, isRefreshing: false, diff --git a/apps/app/src/views/thread-detail/ThreadDetailView.tsx b/apps/app/src/views/thread-detail/ThreadDetailView.tsx index 68068ab4c53..a95e0c0c901 100644 --- a/apps/app/src/views/thread-detail/ThreadDetailView.tsx +++ b/apps/app/src/views/thread-detail/ThreadDetailView.tsx @@ -50,7 +50,6 @@ import { usePluginDetailTabOpener, } from "@/components/plugin/plugin-detail-navigation"; import { useForkThreadFromMessage } from "@/hooks/useForkThreadFromMessage"; -import { useUpdateEnvironment } from "../../hooks/mutations/environment-mutations"; import { useUpdateThread } from "../../hooks/mutations/thread-state-mutations"; import { useEnvironment } from "../../hooks/queries/environment-queries"; import { @@ -545,7 +544,6 @@ function ThreadDetailViewInternal( threadId, enabled: timelineEnabled, }); - const updateEnvironment = useUpdateEnvironment(); const updateThread = useUpdateThread({ errorMessage: "Failed to assign parent thread.", }); @@ -1764,8 +1762,7 @@ function ThreadDetailViewInternal( environmentProvisioningFailure, environmentDisplayHost: environmentDisplayHostContext, threadEnvironmentId: threadTabEnvironmentId, - updateThreadPending: - updateThread.isPending || updateEnvironment.isPending, + updateThreadPending: updateThread.isPending, storage: metadataStorage, onAssignParent: handleAssignParent, onParentSelectorOpenChange: handleParentSelectorOpenChange, diff --git a/docs/api_to_audit.md b/docs/api_to_audit.md index 0b3e17ee97b..1058bc2514c 100644 --- a/docs/api_to_audit.md +++ b/docs/api_to_audit.md @@ -3225,9 +3225,10 @@ hook on the initial attempt as an `experimental_submission` envelope carrying the submitting plugin's id. Core validates the data as JSON but neither persists nor interprets it. -There is one implementation. `PromptBoxInternal` publishes `submit` on the -composer editor bridge; it picks Enter's handler, the queue handler or the -steer handler and gates it exactly as the matching shortcut is gated, then +There is one implementation. The host's `ComposerBox` publishes `submit` on +the composer editor bridge for every composer plugin; it picks Enter's handler, +the queue handler or the steer handler and gates it exactly as the matching +shortcut is gated, then calls the same `onSubmit` or `onModifierSubmit` the shortcuts and the send button call, passing `sendAt` and the plugin submission. Only hosts that set `sendsOnEnter` (the thread, embedded thread chat and New thread composers) diff --git a/docs/vcs-process-admission.md b/docs/vcs-process-admission.md index ffc337239a1..2a8ba0c9705 100644 --- a/docs/vcs-process-admission.md +++ b/docs/vcs-process-admission.md @@ -30,6 +30,6 @@ use background priority. Git status and diff reads run in the Git plugin's host entry, which has its own budget in the plugin host worker and keeps those priorities. The CLI and SDK reach the same reads through the Git plugin. The daemon's `workspace.status`, `workspace.diff`, `workspace.diffFiles` and -`workspace.diffPatch` commands are gone (`HOST_DAEMON_PROTOCOL_VERSION` 252); +`workspace.diffPatch` commands are gone (`HOST_DAEMON_PROTOCOL_VERSION` 255); no user configuration changed. The Plugin Guide lists `experimental_runVcsProcess` for plugins that spawn their own git/gh commands. diff --git a/packages/client-core/src/panel/fixed-panel-tabs-state.ts b/packages/client-core/src/panel/fixed-panel-tabs-state.ts index e9961211125..8ee1dd132fc 100644 --- a/packages/client-core/src/panel/fixed-panel-tabs-state.ts +++ b/packages/client-core/src/panel/fixed-panel-tabs-state.ts @@ -593,16 +593,6 @@ export function createGitDiffFixedPanelTab(): PluginFixedPanelTab { }); } -export function isGitDiffFixedPanelTab( - tab: FixedPanelTab | null | undefined, -): boolean { - return ( - tab?.kind === "plugin-fixed" && - tab.pluginId === GIT_PLUGIN_ID && - tab.tabId === "diff" - ); -} - export function migrateLegacyFixedPanelTabId(id: string): string { if (id === THREAD_INFO_TAB_ID) return createThreadInfoFixedPanelTab().id; if (id === GIT_DIFF_TAB_ID || id === CORE_GIT_DIFF_TAB_ID) { diff --git a/packages/client-core/src/prompt/mentions/composer-mention.ts b/packages/client-core/src/prompt/mentions/composer-mention.ts index f4bd72a3d3c..e2957f26a2d 100644 --- a/packages/client-core/src/prompt/mentions/composer-mention.ts +++ b/packages/client-core/src/prompt/mentions/composer-mention.ts @@ -83,16 +83,6 @@ export function promptTextMentionFromComposerMention( }; } -export function composerDraftFromPromptDraft( - draft: PromptDraftState, -): ComposerDraftShape { - return { - text: draft.text, - mentions: draft.mentions.map(composerMentionFromPromptTextMention), - attachments: draft.attachments, - }; -} - export function promptDraftFromComposerDraft( draft: ComposerDraftShape, ): PromptDraftState { diff --git a/packages/client-core/src/prompt/mentions/mention-candidates.ts b/packages/client-core/src/prompt/mentions/mention-candidates.ts index b949f47d42f..85adad525c1 100644 --- a/packages/client-core/src/prompt/mentions/mention-candidates.ts +++ b/packages/client-core/src/prompt/mentions/mention-candidates.ts @@ -33,11 +33,6 @@ export interface OrderedMentionSuggestions { readonly suggestions: readonly PromptMentionSuggestion[]; } -export const EMPTY_ORDERED_MENTION_SUGGESTIONS: OrderedMentionSuggestions = { - groups: [], - suggestions: [], -}; - const MENTION_MATCH_RANK = { exact: 0, prefix: 1, diff --git a/packages/client-core/test/composer-mention.test.ts b/packages/client-core/test/composer-mention.test.ts index efd59606d3a..d1ae12cc806 100644 --- a/packages/client-core/test/composer-mention.test.ts +++ b/packages/client-core/test/composer-mention.test.ts @@ -4,7 +4,7 @@ import { orderMentionCandidates } from "../src/prompt/mentions/mention-candidate import { composerMentionGroupsFromOrdered } from "../src/prompt/mentions/composer-suggestions.js"; import type { PromptMentionSuggestion } from "../src/prompt/mentions/types.js"; import { - composerDraftFromPromptDraft, + composerMentionFromPromptTextMention, composerMentionTargetFromResource, promptDraftFromComposerDraft, promptMentionResourceFromComposerMention, @@ -54,7 +54,10 @@ describe("composer mention conversion", () => { { type: "localFile" as const, path: "a.txt", name: "a.txt" }, ], }; - const composer = composerDraftFromPromptDraft(draft); + const composer = { + ...draft, + mentions: draft.mentions.map(composerMentionFromPromptTextMention), + }; expect(composer.mentions[0]).toMatchObject({ from: 4, to: 11, diff --git a/packages/environment-provider-host/src/git.ts b/packages/environment-provider-host/src/git.ts index 0d47764d702..3fc5932c926 100644 --- a/packages/environment-provider-host/src/git.ts +++ b/packages/environment-provider-host/src/git.ts @@ -19,7 +19,7 @@ export interface RunGitOptions extends GitProcessOptions { signal?: AbortSignal; } -export type GitRepositoryState = "not_git" | "no_commits" | "has_commits"; +type GitRepositoryState = "not_git" | "no_commits" | "has_commits"; export function runGit( args: string[], diff --git a/packages/environment-provider-host/src/locks.ts b/packages/environment-provider-host/src/locks.ts index d138f66ce93..f0d8a45df9f 100644 --- a/packages/environment-provider-host/src/locks.ts +++ b/packages/environment-provider-host/src/locks.ts @@ -52,7 +52,7 @@ function getCheckoutMutationAdmissionLockSpec( }; } -async function withCheckoutMutationAdmission( +export async function withCheckoutMutationAdmission( checkoutPath: string, work: ProcessLocalQueuedLockWork, signal?: AbortSignal, diff --git a/packages/environment-provider-host/src/workspace-git.ts b/packages/environment-provider-host/src/workspace-git.ts index e1f73dcf9c8..53541168134 100644 --- a/packages/environment-provider-host/src/workspace-git.ts +++ b/packages/environment-provider-host/src/workspace-git.ts @@ -15,7 +15,7 @@ import { type WorkspaceResolutionFailure, } from "./git-types.js"; -export const DEFAULT_BUFFER_BYTES = 16 * 1024 * 1024; +const DEFAULT_BUFFER_BYTES = 16 * 1024 * 1024; export class WorkspaceError extends Error { readonly code: string; @@ -125,7 +125,7 @@ export function resolveGitProcessEnv( }; } -export function createGitCommandTimedOutError( +function createGitCommandTimedOutError( args: string[], timeoutMs: number, cause?: unknown, @@ -137,7 +137,7 @@ export function createGitCommandTimedOutError( ); } -export function createGitCommandCancelledError( +function createGitCommandCancelledError( args: string[], cause?: unknown, ): WorkspaceError { diff --git a/packages/host-workspace/src/checkout-mutation-lock.ts b/packages/host-workspace/src/checkout-mutation-lock.ts index dbc8a9d5cd8..2caa40b977f 100644 --- a/packages/host-workspace/src/checkout-mutation-lock.ts +++ b/packages/host-workspace/src/checkout-mutation-lock.ts @@ -1,56 +1,22 @@ -import path from "node:path"; +import { withCheckoutMutationAdmission } from "bb-environment-provider-host/locks"; import { withProcessLocalQueuedLocks, - type ProcessLocalQueuedLockSpec, type ProcessLocalQueuedLockWork, } from "bb-environment-provider-host/process-local-lock"; +import type { GitProcessOptions } from "bb-environment-provider-host/workspace-git"; import { getAbsoluteGitDir } from "./git.js"; -import type { - GitProcessOptions, -} from "bb-environment-provider-host/workspace-git"; - -type CheckoutMutationLockWork = ProcessLocalQueuedLockWork; - -const checkoutMutationAdmissionKeyPrefix = "checkout-mutation-admission:"; - -function getCheckoutMutationAdmissionLockSpec( - checkoutPath: string, -): ProcessLocalQueuedLockSpec { - return { - key: `${checkoutMutationAdmissionKeyPrefix}${path.resolve(checkoutPath)}`, - }; -} - -export async function withCheckoutMutationAdmission( - checkoutPath: string, - work: CheckoutMutationLockWork, - signal?: AbortSignal, -): Promise { - return withProcessLocalQueuedLocks({ - locks: [getCheckoutMutationAdmissionLockSpec(checkoutPath)], - signal, - work, - }); -} - -async function resolveCheckoutMutationLockSpec( - checkoutPath: string, - options: GitProcessOptions, -): Promise { - return { key: await getAbsoluteGitDir(checkoutPath, options) }; -} export async function withCheckoutMutationLock( checkoutPath: string, - work: CheckoutMutationLockWork, + work: ProcessLocalQueuedLockWork, signal?: AbortSignal, options: GitProcessOptions = {}, ): Promise { return withCheckoutMutationAdmission( checkoutPath, async () => { - const lock = await resolveCheckoutMutationLockSpec(checkoutPath, options); - return withProcessLocalQueuedLocks({ locks: [lock], signal, work }); + const key = await getAbsoluteGitDir(checkoutPath, options); + return withProcessLocalQueuedLocks({ locks: [{ key }], signal, work }); }, signal, ); diff --git a/packages/host-workspace/src/git.ts b/packages/host-workspace/src/git.ts index 685dec5e452..35d90ddd26e 100644 --- a/packages/host-workspace/src/git.ts +++ b/packages/host-workspace/src/git.ts @@ -10,7 +10,6 @@ import { type GitProcessOptions, type GitTimeoutOptions, parseOriginHeadBranchName, - type PorcelainEntry, resolveGitProcessEnv, resolvePreferredLocalDefaultBranch, runGit, @@ -49,11 +48,6 @@ interface WorkspaceGitOperationMarker { markerNames: string[]; } -interface ParsedPorcelainPathToken { - nextIndex: number; - value: string; -} - const CONFLICT_PORCELAIN_STATUSES = new Set([ "DD", "AU", @@ -71,18 +65,6 @@ const WORKSPACE_GIT_OPERATION_MARKERS: WorkspaceGitOperationMarker[] = [ { kind: "revert", markerNames: ["REVERT_HEAD"] }, ]; -const GIT_QUOTED_PATH_ESCAPE_BYTES = new Map([ - ['"', 34], - ["\\", 92], - ["a", 7], - ["b", 8], - ["f", 12], - ["n", 10], - ["r", 13], - ["t", 9], - ["v", 11], -]); - function isMissingGitBlobTargetError(stderr: string): boolean { return ( /^fatal: path '.+' does not exist in '.+'$/u.test(stderr) || @@ -245,132 +227,11 @@ export async function getCheckoutRef( }; } -function appendUtf8Bytes(bytes: number[], value: string): void { - bytes.push(...Buffer.from(value, "utf8")); -} - -function isOctalDigit(value: string | undefined): boolean { - return value !== undefined && value >= "0" && value <= "7"; -} - -function readEscapedPorcelainPathBytes( - bytes: number[], - rawPath: string, - startIndex: number, -): number { - const escapeChar = rawPath[startIndex + 1]; - if (escapeChar === undefined) { - return startIndex + 1; - } - if (isOctalDigit(escapeChar)) { - let octalValue = escapeChar; - let index = startIndex + 2; - while (octalValue.length < 3 && isOctalDigit(rawPath[index])) { - octalValue += rawPath[index] ?? ""; - index += 1; - } - bytes.push(Number.parseInt(octalValue, 8)); - return index; - } - const escapedByte = GIT_QUOTED_PATH_ESCAPE_BYTES.get(escapeChar); - if (escapedByte !== undefined) { - bytes.push(escapedByte); - } else { - appendUtf8Bytes(bytes, escapeChar); - } - return startIndex + 2; -} - -function parseQuotedPorcelainPathToken( - rawPath: string, - startIndex: number, -): ParsedPorcelainPathToken { - const bytes: number[] = []; - let index = startIndex + 1; - while (index < rawPath.length) { - const currentChar = rawPath[index]; - if (currentChar === '"') { - return { - nextIndex: index + 1, - value: Buffer.from(bytes).toString("utf8"), - }; - } - if (currentChar === "\\") { - index = readEscapedPorcelainPathBytes(bytes, rawPath, index); - continue; - } - const codePoint = rawPath.codePointAt(index); - if (codePoint === undefined) { - break; - } - const character = String.fromCodePoint(codePoint); - appendUtf8Bytes(bytes, character); - index += character.length; - } - return { - nextIndex: rawPath.length, - value: rawPath.slice(startIndex), - }; -} - -function parseUnquotedPorcelainPathToken( - rawPath: string, - startIndex: number, -): ParsedPorcelainPathToken { - const separatorIndex = rawPath.indexOf(" -> ", startIndex); - const endIndex = separatorIndex === -1 ? rawPath.length : separatorIndex; - return { - nextIndex: endIndex, - value: rawPath.slice(startIndex, endIndex), - }; -} - -function parsePorcelainPathToken( - rawPath: string, - startIndex: number, -): ParsedPorcelainPathToken { - if (rawPath[startIndex] === '"') { - return parseQuotedPorcelainPathToken(rawPath, startIndex); - } - return parseUnquotedPorcelainPathToken(rawPath, startIndex); -} - -function parsePorcelainPath(rawPath: string): string { - const sourcePath = parsePorcelainPathToken(rawPath, 0); - if ( - rawPath.slice(sourcePath.nextIndex, sourcePath.nextIndex + 4) !== " -> " - ) { - return sourcePath.value; - } - return parsePorcelainPathToken(rawPath, sourcePath.nextIndex + 4).value; -} - -export function parsePorcelainEntries(statusOutput: string): PorcelainEntry[] { - return statusOutput - .split("\n") - .filter((line) => line && !line.startsWith("##")) - .map((line) => { - const indexStatus = line[0] ?? " "; - const worktreeStatus = line[1] ?? " "; - const status = line.slice(0, 2).trim() || line.slice(0, 2); - const rawPath = line.slice(3).trim(); - - return { - path: parsePorcelainPath(rawPath), - status, - indexStatus, - worktreeStatus, - }; - }); -} - -function hasPorcelainConflict(entries: PorcelainEntry[]): boolean { - return entries.some( - (entry) => - entry.indexStatus === "U" || - entry.worktreeStatus === "U" || - CONFLICT_PORCELAIN_STATUSES.has(entry.status), - ); +function hasPorcelainConflict(statusOutput: string): boolean { + return statusOutput.split("\n").some((line) => { + const status = line.slice(0, 2); + return status.includes("U") || CONFLICT_PORCELAIN_STATUSES.has(status); + }); } function buildActiveWorkspaceGitOperation( @@ -407,9 +268,7 @@ export async function getWorkspaceGitOperation( { cwd, ...options }, ), ]); - const hasConflicts = hasPorcelainConflict( - parsePorcelainEntries(status.stdout), - ); + const hasConflicts = hasPorcelainConflict(status.stdout); const marker = await findWorkspaceGitOperationMarker(gitDir); if (!marker) { return { kind: "none" }; diff --git a/packages/host-workspace/src/index.ts b/packages/host-workspace/src/index.ts index 23ac24584e2..92daca11f8f 100644 --- a/packages/host-workspace/src/index.ts +++ b/packages/host-workspace/src/index.ts @@ -2,7 +2,6 @@ export { provisionWorkspace } from "./provision.js"; export type { HostWorkspace, ProvisionWorkspaceArgs } from "./provision.js"; export type { LocalStateSnapshot } from "./host-workspace.js"; -export { withGitRefMutationLock } from "bb-environment-provider-host/process-local-lock"; export { detectLinkedWorktree, diff --git a/packages/host-workspace/src/provision.ts b/packages/host-workspace/src/provision.ts index df6d61b0f01..7a5298a0b75 100644 --- a/packages/host-workspace/src/provision.ts +++ b/packages/host-workspace/src/provision.ts @@ -7,24 +7,11 @@ import { Workspace, } from "./host-workspace.js"; import { inspectGitRepository, type SharedGitRefsSnapshot } from "./git.js"; +import { throwIfProvisionAborted } from "bb-environment-provider-host/transcript"; import { WorkspaceError } from "bb-environment-provider-host/workspace-git"; type ProvisionProgressCallback = (entry: ProvisioningTranscriptEntry) => void; -function createProvisionCancelledError(cause?: unknown): WorkspaceError { - return new WorkspaceError( - "provision_cancelled", - "Workspace provisioning was cancelled", - { cause }, - ); -} - -export function throwIfProvisionAborted(signal: AbortSignal | undefined): void { - if (signal?.aborted) { - throw createProvisionCancelledError(signal.reason); - } -} - interface ProvisionBase { onProgress?: ProvisionProgressCallback; shellPath?: string; diff --git a/packages/host-workspace/test/git.test.ts b/packages/host-workspace/test/git.test.ts index 91449f325b0..c1068f86dc5 100644 --- a/packages/host-workspace/test/git.test.ts +++ b/packages/host-workspace/test/git.test.ts @@ -15,7 +15,6 @@ import { detectLinkedWorktree, getCheckoutRef, getWorkspaceGitOperation, - parsePorcelainEntries, readGitBlob, } from "../src/git.js"; @@ -253,70 +252,6 @@ describe("readGitBlob", () => { }); }); -describe("parsePorcelainEntries", () => { - it("parses ordinary entries and renamed targets", () => { - expect( - parsePorcelainEntries( - [ - " M README.md", - "R old-name.ts -> new-name.ts", - "D removed.txt", - ].join("\n"), - ), - ).toEqual([ - { - path: "README.md", - status: "M", - indexStatus: " ", - worktreeStatus: "M", - }, - { - path: "new-name.ts", - status: "R", - indexStatus: "R", - worktreeStatus: " ", - }, - { - path: "removed.txt", - status: "D", - indexStatus: "D", - worktreeStatus: " ", - }, - ]); - }); - - it("decodes quoted git paths and octal escapes", () => { - expect( - parsePorcelainEntries( - [ - '?? "a b.txt"', - '?? "quote\\\\and\\\"slash.txt"', - 'R "old\\040name.txt" -> "new\\040name.txt"', - ].join("\n"), - ), - ).toEqual([ - { - path: "a b.txt", - status: "??", - indexStatus: "?", - worktreeStatus: "?", - }, - { - path: 'quote\\and"slash.txt', - status: "??", - indexStatus: "?", - worktreeStatus: "?", - }, - { - path: "new name.txt", - status: "R", - indexStatus: "R", - worktreeStatus: " ", - }, - ]); - }); -}); - describe("detectLinkedWorktree", () => { it("tells a linked worktree apart from an ordinary checkout", async () => { const { worktreePath } = await initBareWorktreeLayout(); diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 2c3d482d237..eb479af1378 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -243,39 +243,6 @@ importers: '@tanstack/react-virtual': specifier: 3.14.20 version: 3.14.20(react-dom@19.3.0(react@19.3.0))(react@19.3.0) - '@tiptap/core': - specifier: ^3.26.0 - version: 3.26.0(@tiptap/pm@3.26.0) - '@tiptap/extension-blockquote': - specifier: ^3.26.0 - version: 3.26.0(patch_hash=5ybzdv3kkwrykbgdydwjdtpqom)(@tiptap/core@3.26.0(@tiptap/pm@3.26.0)) - '@tiptap/extension-document': - specifier: ^3.26.0 - version: 3.26.0(@tiptap/core@3.26.0(@tiptap/pm@3.26.0)) - '@tiptap/extension-hard-break': - specifier: ^3.26.0 - version: 3.26.0(@tiptap/core@3.26.0(@tiptap/pm@3.26.0)) - '@tiptap/extension-mention': - specifier: ^3.26.0 - version: 3.26.0(@tiptap/core@3.26.0(@tiptap/pm@3.26.0))(@tiptap/pm@3.26.0)(@tiptap/suggestion@3.26.0(@tiptap/core@3.26.0(@tiptap/pm@3.26.0))(@tiptap/pm@3.26.0)) - '@tiptap/extension-paragraph': - specifier: ^3.26.0 - version: 3.26.0(@tiptap/core@3.26.0(@tiptap/pm@3.26.0)) - '@tiptap/extension-text': - specifier: ^3.26.0 - version: 3.26.0(@tiptap/core@3.26.0(@tiptap/pm@3.26.0)) - '@tiptap/extensions': - specifier: ^3.26.0 - version: 3.26.0(@tiptap/core@3.26.0(@tiptap/pm@3.26.0))(@tiptap/pm@3.26.0) - '@tiptap/pm': - specifier: ^3.26.0 - version: 3.26.0 - '@tiptap/react': - specifier: ^3.26.0 - version: 3.26.0(@floating-ui/dom@1.7.6)(@tiptap/core@3.26.0(@tiptap/pm@3.26.0))(@tiptap/pm@3.26.0)(@types/react-dom@19.2.7(@types/react@19.3.0))(@types/react@19.3.0)(react-dom@19.3.0(react@19.3.0))(react@19.3.0) - '@tiptap/suggestion': - specifier: ^3.26.0 - version: 3.26.0(@tiptap/core@3.26.0(@tiptap/pm@3.26.0))(@tiptap/pm@3.26.0) '@xterm/addon-fit': specifier: 0.12.0-beta.292 version: 0.12.0-beta.292(@xterm/xterm@6.1.0-beta.292) @@ -421,6 +388,12 @@ importers: '@testing-library/react': specifier: ^16.3.2 version: 16.3.2(@testing-library/dom@10.4.1)(@types/react-dom@19.2.7(@types/react@19.3.0))(@types/react@19.3.0)(react-dom@19.3.0(react@19.3.0))(react@19.3.0) + '@tiptap/core': + specifier: ^3.26.0 + version: 3.26.0(@tiptap/pm@3.26.0) + '@tiptap/pm': + specifier: ^3.26.0 + version: 3.26.0 '@types/cacache': specifier: ^20.0.1 version: 20.0.1 From f16a5d4c20b37634455ac7398164c79183f860df Mon Sep 17 00:00:00 2001 From: Michael Yong Date: Tue, 3 Nov 2026 12:55:24 -0800 Subject: [PATCH 2/2] Consolidate git helpers duplicated across core and plugins - Implement checkout-ref, dirty and in-progress-operation inspection once in createGitQueries, so the daemon's host.inspect_git_source and the project-checkout plugin share it while each keeps its own git priority. Both callers already confirm a work tree first, so dropping the extra ensureGitRepo probe leaves results unchanged. getAbsoluteGitDir and pathExists move there too. - In the Git plugin's workspace reads, make the HEAD-to-empty-tree fallback generic over the result type so the record-limited diff reuses it, share one rangeGitRunner, one lstat helper and sumNumstatLines, and drop local copies of contract types and unused exports. - Build Ladle's makeWorkspaceStatus on the Git plugin's testing builders. Co-Authored-By: Claude Opus 5.5 --- apps/app/.ladle/story-fixtures.ts | 45 +-- .../src/command-handlers/host-branches.ts | 8 +- packages/environment-provider-host/src/git.ts | 6 +- .../src/workspace-git.ts | 163 +++++++++++ .../src/checkout-mutation-lock.ts | 6 +- packages/host-workspace/src/git.ts | 189 +----------- packages/host-workspace/src/index.ts | 8 +- .../src/workspace-write-roots.ts | 2 +- packages/host-workspace/test/git.test.ts | 7 +- .../host/checkout.ts | 25 +- .../environment-project-checkout/host/git.ts | 132 --------- plugins/git/host/workspace-reads.ts | 269 ++++++------------ 12 files changed, 299 insertions(+), 561 deletions(-) delete mode 100644 plugins/environment-project-checkout/host/git.ts diff --git a/apps/app/.ladle/story-fixtures.ts b/apps/app/.ladle/story-fixtures.ts index 9e77a1d6b82..7cbe0950a33 100644 --- a/apps/app/.ladle/story-fixtures.ts +++ b/apps/app/.ladle/story-fixtures.ts @@ -35,6 +35,10 @@ import type { TypeaheadConfig, } from "../src/components/promptbox/ComposerBox"; import type { WorkspaceStatus } from "bb-plugin-bb--git/contract"; +import { + makeWorkspaceMergeBase, + makeWorkspaceStatus as makeGitWorkspaceStatus, +} from "bb-plugin-bb--git/testing"; const noop = () => {}; @@ -603,16 +607,7 @@ export function makeEnvironment( export function makeWorkspaceStatus( overrides: Partial = {}, ): WorkspaceStatus { - const base: Omit = { - workingTree: { - hasUncommittedChanges: false, - state: "clean", - insertions: 0, - deletions: 0, - lineStatsComplete: true, - fileCount: 0, - files: [], - }, + return makeGitWorkspaceStatus({ branch: { currentBranch: BRANCH_NAMES.feature, defaultBranch: BRANCH_NAMES.default, @@ -622,34 +617,10 @@ export function makeWorkspaceStatus( branchName: BRANCH_NAMES.feature, headSha: null, }, - mergeBase: { + mergeBase: makeWorkspaceMergeBase({ mergeBaseBranch: BRANCH_NAMES.default, baseRef: null, - aheadCount: 0, - behindCount: 0, - squashMergeCheckComplete: true, - hasCommittedUnmergedChanges: false, - commits: [], - insertions: 0, - deletions: 0, - lineStatsComplete: true, - fileCount: 0, - files: [], - }, - }; - const workingTree = overrides.workingTree ?? base.workingTree; - const mergeBase = - overrides.mergeBase === undefined ? base.mergeBase : overrides.mergeBase; - const committed = mergeBase?.hasCommittedUnmergedChanges ? mergeBase : null; - return { - ...base, - allChanges: { - insertions: workingTree.insertions + (committed?.insertions ?? 0), - deletions: workingTree.deletions + (committed?.deletions ?? 0), - lineStatsComplete: - workingTree.lineStatsComplete && (committed?.lineStatsComplete ?? true), - fileCount: workingTree.fileCount + (committed?.fileCount ?? 0), - }, + }), ...overrides, - }; + }); } diff --git a/apps/host-daemon/src/command-handlers/host-branches.ts b/apps/host-daemon/src/command-handlers/host-branches.ts index a5cab10815c..dba8699ca30 100644 --- a/apps/host-daemon/src/command-handlers/host-branches.ts +++ b/apps/host-daemon/src/command-handlers/host-branches.ts @@ -13,14 +13,12 @@ import { } from "bb-environment-provider-host/branch-options"; import { detectGitRepoKind, - readDefaultBranchRefs, -} from "bb-environment-provider-host/workspace-git"; -import { - detectLinkedWorktree, getCheckoutRef, getWorkspaceGitOperation, hasUncommittedChanges, -} from "@bb/host-workspace"; + readDefaultBranchRefs, +} from "bb-environment-provider-host/workspace-git"; +import { detectLinkedWorktree } from "@bb/host-workspace"; const NO_GIT_OPERATION: WorkspaceGitOperation = { kind: "none" }; diff --git a/packages/environment-provider-host/src/git.ts b/packages/environment-provider-host/src/git.ts index 3fc5932c926..6596f4dbb55 100644 --- a/packages/environment-provider-host/src/git.ts +++ b/packages/environment-provider-host/src/git.ts @@ -5,10 +5,11 @@ import { type GitTimeoutOptions, type DefaultBranchRefs, createGitQueries, + pathExists, runGit as runSharedGit, trimOutput, } from "./workspace-git.js"; -export { WorkspaceError }; +export { pathExists, WorkspaceError }; export type { GitCommandResult, GitProcessOptions, DefaultBranchRefs }; export interface RunGitOptions extends GitProcessOptions { @@ -70,8 +71,11 @@ export const { detectGitRepo, detectGitSource, ensureGitRepo, + getCheckoutRef, getCurrentBranch, getGitCommonDir, + getWorkspaceGitOperation, + hasUncommittedChanges, hasRef, readBranchRelation, readDefaultBranch, diff --git a/packages/environment-provider-host/src/workspace-git.ts b/packages/environment-provider-host/src/workspace-git.ts index 53541168134..74f9e8b8bc3 100644 --- a/packages/environment-provider-host/src/workspace-git.ts +++ b/packages/environment-provider-host/src/workspace-git.ts @@ -1,3 +1,4 @@ +import fs from "node:fs/promises"; import path from "node:path"; import { experimental_runVcsProcess as runVcsProcess, @@ -461,6 +462,55 @@ export function parseOriginHeadBranchName(output: string): string | undefined { return undefined; } +export type GitCheckoutState = + | { kind: "branch"; branchName: string; headSha: string } + | { kind: "unborn"; branchName: string } + | { kind: "detached"; headSha: string } + | { kind: "unknown"; reason: string }; + +export type GitOperationState = + | { kind: "none" } + | { + kind: "rebase" | "merge" | "cherry-pick" | "revert"; + hasConflicts: boolean; + }; + +const GIT_OPERATION_MARKERS: ReadonlyArray<{ + kind: "rebase" | "merge" | "cherry-pick" | "revert"; + markerNames: readonly string[]; +}> = [ + { kind: "rebase", markerNames: ["rebase-merge", "rebase-apply"] }, + { kind: "merge", markerNames: ["MERGE_HEAD"] }, + { kind: "cherry-pick", markerNames: ["CHERRY_PICK_HEAD"] }, + { kind: "revert", markerNames: ["REVERT_HEAD"] }, +]; + +const CONFLICT_PORCELAIN_STATUSES = new Set([ + "DD", + "AU", + "UD", + "UA", + "DU", + "AA", + "UU", +]); + +function hasPorcelainConflict(statusOutput: string): boolean { + return statusOutput.split("\n").some((line) => { + const status = line.slice(0, 2); + return status.includes("U") || CONFLICT_PORCELAIN_STATUSES.has(status); + }); +} + +export async function pathExists(targetPath: string): Promise { + try { + await fs.access(targetPath); + return true; + } catch { + return false; + } +} + type GitQueryRunner = ( args: string[], options: GitTimeoutOptions & { @@ -541,6 +591,111 @@ export function createGitQueries(run: GitQueryRunner) { return branchName || undefined; } + async function getAbsoluteGitDir( + cwd: string, + options: GitProcessOptions = {}, + ): Promise { + const result = await run(["rev-parse", "--absolute-git-dir"], { + cwd, + ...options, + }); + const gitDir = result.stdout.trim(); + if (!gitDir) { + throw new WorkspaceError( + "git_command_failed", + `git rev-parse --absolute-git-dir returned no path for ${cwd}`, + ); + } + return path.resolve(gitDir); + } + + async function readHeadSha( + cwd: string, + options: GitTimeoutOptions, + ): Promise { + const result = await run(["rev-parse", "--verify", "HEAD"], { + cwd, + ...options, + allowFailure: true, + }); + if (result.exitCode !== 0) { + return null; + } + return trimOutput(result.stdout) || null; + } + + async function getCheckoutRef( + cwd: string, + options: GitTimeoutOptions = {}, + ): Promise { + if (!(await detectGitSource(cwd, options))) { + return { kind: "unknown", reason: "Path is not a git repository" }; + } + const [symbolicRef, headSha] = await Promise.all([ + run(["symbolic-ref", "--quiet", "--short", "HEAD"], { + cwd, + ...options, + allowFailure: true, + }), + readHeadSha(cwd, options), + ]); + const branchName = trimOutput(symbolicRef.stdout); + if (symbolicRef.exitCode === 0 && branchName) { + return headSha === null + ? { kind: "unborn", branchName } + : { kind: "branch", branchName, headSha }; + } + if (headSha !== null) { + return { kind: "detached", headSha }; + } + return { + kind: "unknown", + reason: "HEAD is not symbolic and no commit is checked out", + }; + } + + async function readPorcelainStatus( + cwd: string, + options: GitProcessOptions, + ): Promise { + const status = await run( + [ + "--no-optional-locks", + "status", + "--porcelain=v1", + "--untracked-files=all", + ], + { cwd, ...options }, + ); + return status.stdout; + } + + async function hasUncommittedChanges( + cwd: string, + options: GitProcessOptions = {}, + ): Promise { + return (await readPorcelainStatus(cwd, options)).trim().length > 0; + } + + async function getWorkspaceGitOperation( + cwd: string, + options: GitProcessOptions = {}, + ): Promise { + const [gitDir, status] = await Promise.all([ + getAbsoluteGitDir(cwd, options), + readPorcelainStatus(cwd, options), + ]); + const hasConflicts = hasPorcelainConflict(status); + for (const marker of GIT_OPERATION_MARKERS) { + for (const markerName of marker.markerNames) { + if (await pathExists(path.join(gitDir, markerName))) { + return { kind: marker.kind, hasConflicts }; + } + } + } + return { kind: "none" }; + } + async function getGitCommonDir( cwd: string, options: GitProcessOptions & { signal?: AbortSignal } = {}, @@ -764,8 +919,12 @@ export function createGitQueries(run: GitQueryRunner) { detectGitRepo, detectGitSource, ensureGitRepo, + getAbsoluteGitDir, + getCheckoutRef, getCurrentBranch, getGitCommonDir, + getWorkspaceGitOperation, + hasUncommittedChanges, hasRef, readBranchRelation, readOriginHeadBranchName, @@ -781,8 +940,12 @@ export const { detectGitRepo, detectGitSource, ensureGitRepo, + getAbsoluteGitDir, + getCheckoutRef, getCurrentBranch, getGitCommonDir, + getWorkspaceGitOperation, + hasUncommittedChanges, hasRef, readBranchRelation, readOriginHeadBranchName, diff --git a/packages/host-workspace/src/checkout-mutation-lock.ts b/packages/host-workspace/src/checkout-mutation-lock.ts index 2caa40b977f..6093e69ae04 100644 --- a/packages/host-workspace/src/checkout-mutation-lock.ts +++ b/packages/host-workspace/src/checkout-mutation-lock.ts @@ -3,8 +3,10 @@ import { withProcessLocalQueuedLocks, type ProcessLocalQueuedLockWork, } from "bb-environment-provider-host/process-local-lock"; -import type { GitProcessOptions } from "bb-environment-provider-host/workspace-git"; -import { getAbsoluteGitDir } from "./git.js"; +import { + getAbsoluteGitDir, + type GitProcessOptions, +} from "bb-environment-provider-host/workspace-git"; export async function withCheckoutMutationLock( checkoutPath: string, diff --git a/packages/host-workspace/src/git.ts b/packages/host-workspace/src/git.ts index 35d90ddd26e..e8525c3b0bf 100644 --- a/packages/host-workspace/src/git.ts +++ b/packages/host-workspace/src/git.ts @@ -1,15 +1,13 @@ -import fs from "node:fs/promises"; import path from "node:path"; import type { ExecFileException } from "node:child_process"; import { execHostFileBuffer, runVcsProcess } from "@bb/process-utils"; -import type { GitCheckoutRef, WorkspaceGitOperation } from "@bb/domain"; import { createGitCommandFailedError, - detectGitSource, ensureGitRepo, type GitProcessOptions, type GitTimeoutOptions, parseOriginHeadBranchName, + pathExists, resolveGitProcessEnv, resolvePreferredLocalDefaultBranch, runGit, @@ -29,42 +27,6 @@ function isMaxBufferExceededError(error: unknown): boolean { ); } -async function pathExists(targetPath: string): Promise { - try { - await fs.access(targetPath); - return true; - } catch { - return false; - } -} - -type ActiveWorkspaceGitOperationKind = Exclude< - WorkspaceGitOperation["kind"], - "none" | "unknown" ->; - -interface WorkspaceGitOperationMarker { - kind: ActiveWorkspaceGitOperationKind; - markerNames: string[]; -} - -const CONFLICT_PORCELAIN_STATUSES = new Set([ - "DD", - "AU", - "UD", - "UA", - "DU", - "AA", - "UU", -]); - -const WORKSPACE_GIT_OPERATION_MARKERS: WorkspaceGitOperationMarker[] = [ - { kind: "rebase", markerNames: ["rebase-merge", "rebase-apply"] }, - { kind: "merge", markerNames: ["MERGE_HEAD"] }, - { kind: "cherry-pick", markerNames: ["CHERRY_PICK_HEAD"] }, - { kind: "revert", markerNames: ["REVERT_HEAD"] }, -]; - function isMissingGitBlobTargetError(stderr: string): boolean { return ( /^fatal: path '.+' does not exist in '.+'$/u.test(stderr) || @@ -73,37 +35,6 @@ function isMissingGitBlobTargetError(stderr: string): boolean { ); } -export async function getAbsoluteGitDir( - cwd: string, - options: GitProcessOptions = {}, -): Promise { - const result = await runGit(["rev-parse", "--absolute-git-dir"], { - cwd, - ...options, - }); - const gitDir = result.stdout.trim(); - if (!gitDir) { - throw new WorkspaceError( - "git_command_failed", - `git rev-parse --absolute-git-dir returned no path for ${cwd}`, - ); - } - return path.resolve(gitDir); -} - -async function findWorkspaceGitOperationMarker( - gitDir: string, -): Promise { - for (const marker of WORKSPACE_GIT_OPERATION_MARKERS) { - for (const markerName of marker.markerNames) { - if (await pathExists(path.join(gitDir, markerName))) { - return marker; - } - } - } - return undefined; -} - export async function inspectGitRepository( cwd: string, options: GitTimeoutOptions = {}, @@ -175,107 +106,6 @@ export async function detectLinkedWorktree( return gitDirResult.stdout.trim().includes("/worktrees/"); } -async function readHeadSha( - cwd: string, - options: GitTimeoutOptions = {}, -): Promise { - const result = await runGit(["rev-parse", "--verify", "HEAD"], { - cwd, - ...options, - allowFailure: true, - }); - if (result.exitCode !== 0) { - return null; - } - - const sha = trimOutput(result.stdout); - return sha || null; -} - -export async function getCheckoutRef( - cwd: string, - options: GitTimeoutOptions = {}, -): Promise { - if (!(await detectGitSource(cwd, options))) { - return { kind: "unknown", reason: "Path is not a git repository" }; - } - - const [symbolicRef, headSha] = await Promise.all([ - runGit(["symbolic-ref", "--quiet", "--short", "HEAD"], { - cwd, - ...options, - allowFailure: true, - }), - readHeadSha(cwd, options), - ]); - - const branchName = trimOutput(symbolicRef.stdout); - if (symbolicRef.exitCode === 0 && branchName) { - if (headSha === null) { - return { kind: "unborn", branchName }; - } - return { kind: "branch", branchName, headSha }; - } - - if (headSha !== null) { - return { kind: "detached", headSha }; - } - - return { - kind: "unknown", - reason: "HEAD is not symbolic and no commit is checked out", - }; -} - -function hasPorcelainConflict(statusOutput: string): boolean { - return statusOutput.split("\n").some((line) => { - const status = line.slice(0, 2); - return status.includes("U") || CONFLICT_PORCELAIN_STATUSES.has(status); - }); -} - -function buildActiveWorkspaceGitOperation( - kind: ActiveWorkspaceGitOperationKind, - hasConflicts: boolean, -): WorkspaceGitOperation { - switch (kind) { - case "merge": - return { kind: "merge", hasConflicts }; - case "rebase": - return { kind: "rebase", hasConflicts }; - case "cherry-pick": - return { kind: "cherry-pick", hasConflicts }; - case "revert": - return { kind: "revert", hasConflicts }; - } -} - -export async function getWorkspaceGitOperation( - cwd: string, - options: GitProcessOptions = {}, -): Promise { - await ensureGitRepo(cwd, options); - - const [gitDir, status] = await Promise.all([ - getAbsoluteGitDir(cwd, options), - runGit( - [ - "--no-optional-locks", - "status", - "--porcelain=v1", - "--untracked-files=all", - ], - { cwd, ...options }, - ), - ]); - const hasConflicts = hasPorcelainConflict(status.stdout); - const marker = await findWorkspaceGitOperationMarker(gitDir); - if (!marker) { - return { kind: "none" }; - } - return buildActiveWorkspaceGitOperation(marker.kind, hasConflicts); -} - export interface SharedGitRefsSnapshot { fingerprint: string; defaultBranch: string | null; @@ -452,20 +282,3 @@ export async function readGitBlob( ); } } - -export async function hasUncommittedChanges( - cwd: string, - options: GitProcessOptions = {}, -): Promise { - await ensureGitRepo(cwd, options); - const status = await runGit( - [ - "--no-optional-locks", - "status", - "--porcelain=v1", - "--untracked-files=all", - ], - { cwd, ...options }, - ); - return status.stdout.trim().length > 0; -} diff --git a/packages/host-workspace/src/index.ts b/packages/host-workspace/src/index.ts index 92daca11f8f..e1d3de7ca35 100644 --- a/packages/host-workspace/src/index.ts +++ b/packages/host-workspace/src/index.ts @@ -3,11 +3,5 @@ export type { HostWorkspace, ProvisionWorkspaceArgs } from "./provision.js"; export type { LocalStateSnapshot } from "./host-workspace.js"; -export { - detectLinkedWorktree, - getCheckoutRef, - getWorkspaceGitOperation, - hasUncommittedChanges, - readGitBlob, -} from "./git.js"; +export { detectLinkedWorktree, readGitBlob } from "./git.js"; export type { SharedGitRefsSnapshot } from "./git.js"; diff --git a/packages/host-workspace/src/workspace-write-roots.ts b/packages/host-workspace/src/workspace-write-roots.ts index de0bfb63ee2..73fe89ad87a 100644 --- a/packages/host-workspace/src/workspace-write-roots.ts +++ b/packages/host-workspace/src/workspace-write-roots.ts @@ -1,6 +1,6 @@ import path from "node:path"; -import { getAbsoluteGitDir } from "./git.js"; import { + getAbsoluteGitDir, getGitCommonDir, type GitProcessOptions, } from "bb-environment-provider-host/workspace-git"; diff --git a/packages/host-workspace/test/git.test.ts b/packages/host-workspace/test/git.test.ts index c1068f86dc5..510a21b995b 100644 --- a/packages/host-workspace/test/git.test.ts +++ b/packages/host-workspace/test/git.test.ts @@ -10,13 +10,12 @@ import { it, vi, } from "vitest"; -import { runGit } from "bb-environment-provider-host/workspace-git"; import { - detectLinkedWorktree, getCheckoutRef, getWorkspaceGitOperation, - readGitBlob, -} from "../src/git.js"; + runGit, +} from "bb-environment-provider-host/workspace-git"; +import { detectLinkedWorktree, readGitBlob } from "../src/git.js"; const tempDirs: string[] = []; diff --git a/plugins/environment-project-checkout/host/checkout.ts b/plugins/environment-project-checkout/host/checkout.ts index 7c7fad08d11..dcc48d7fb1c 100644 --- a/plugins/environment-project-checkout/host/checkout.ts +++ b/plugins/environment-project-checkout/host/checkout.ts @@ -1,5 +1,10 @@ import { detectGitRepo, + getCheckoutRef, + getWorkspaceGitOperation, + hasRef, + hasUncommittedChanges, + pathExists, runGit, WorkspaceError, } from "bb-environment-provider-host/git"; @@ -9,13 +14,6 @@ import { throwIfProvisionAborted, type ProgressCallback, } from "bb-environment-provider-host/transcript"; -import { - getCheckoutRef, - getWorkspaceGitOperation, - hasUncommittedChanges, - locateBranch, - pathExists, -} from "./git.js"; import type { CheckoutBranch, CheckoutInspection } from "../contract.js"; interface AttachCheckoutArgs { @@ -54,6 +52,19 @@ function checkoutLabel( return `${verb} branch ${branch.name}`; } +async function locateBranch( + cwd: string, + name: string, +): Promise<"local" | "origin" | "missing"> { + if (await hasRef(cwd, `refs/heads/${name}`)) { + return "local"; + } + if (await hasRef(cwd, `refs/remotes/origin/${name}`)) { + return "origin"; + } + return "missing"; +} + async function assertSwitchable( cwd: string, branch: CheckoutBranch, diff --git a/plugins/environment-project-checkout/host/git.ts b/plugins/environment-project-checkout/host/git.ts deleted file mode 100644 index 97b527a9a11..00000000000 --- a/plugins/environment-project-checkout/host/git.ts +++ /dev/null @@ -1,132 +0,0 @@ -import { - detectGitRepo, - hasRef, - runGit, -} from "bb-environment-provider-host/git"; -import fs from "node:fs/promises"; -import path from "node:path"; -import type { GitCheckoutRef, WorkspaceGitOperation } from "../contract.js"; - -export async function pathExists(targetPath: string): Promise { - try { - await fs.access(targetPath); - return true; - } catch { - return false; - } -} - -async function readHeadSha(cwd: string): Promise { - const result = await runGit(["rev-parse", "--verify", "HEAD"], { - cwd, - allowFailure: true, - }); - if (result.exitCode !== 0) { - return null; - } - const sha = result.stdout.trim(); - return sha || null; -} - -export async function getCheckoutRef(cwd: string): Promise { - if (!(await detectGitRepo(cwd))) { - return { kind: "unknown", reason: "Path is not a git repository" }; - } - const [symbolicRef, headSha] = await Promise.all([ - runGit(["symbolic-ref", "--quiet", "--short", "HEAD"], { - cwd, - allowFailure: true, - }), - readHeadSha(cwd), - ]); - const branchName = symbolicRef.stdout.trim(); - if (symbolicRef.exitCode === 0 && branchName) { - return headSha === null - ? { kind: "unborn", branchName } - : { kind: "branch", branchName, headSha }; - } - if (headSha !== null) { - return { kind: "detached", headSha }; - } - return { - kind: "unknown", - reason: "HEAD is not symbolic and no commit is checked out", - }; -} - -export async function locateBranch( - cwd: string, - name: string, -): Promise<"local" | "origin" | "missing"> { - if (await hasRef(cwd, `refs/heads/${name}`)) { - return "local"; - } - if (await hasRef(cwd, `refs/remotes/origin/${name}`)) { - return "origin"; - } - return "missing"; -} - -const CONFLICT_PORCELAIN_STATUSES = new Set([ - "DD", - "AU", - "UD", - "UA", - "DU", - "AA", - "UU", -]); - -const GIT_OPERATION_MARKERS: ReadonlyArray<{ - kind: "rebase" | "merge" | "cherry-pick" | "revert"; - markerNames: readonly string[]; -}> = [ - { kind: "rebase", markerNames: ["rebase-merge", "rebase-apply"] }, - { kind: "merge", markerNames: ["MERGE_HEAD"] }, - { kind: "cherry-pick", markerNames: ["CHERRY_PICK_HEAD"] }, - { kind: "revert", markerNames: ["REVERT_HEAD"] }, -]; - -async function readPorcelainStatus(cwd: string): Promise { - const status = await runGit( - [ - "--no-optional-locks", - "status", - "--porcelain=v1", - "--untracked-files=all", - ], - { cwd }, - ); - return status.stdout; -} - -export async function hasUncommittedChanges(cwd: string): Promise { - return (await readPorcelainStatus(cwd)).trim().length > 0; -} - -export async function getWorkspaceGitOperation( - cwd: string, -): Promise { - const [gitDirResult, status] = await Promise.all([ - runGit(["rev-parse", "--absolute-git-dir"], { cwd }), - readPorcelainStatus(cwd), - ]); - const gitDir = gitDirResult.stdout.trim(); - const hasConflicts = status - .split("\n") - .filter((line) => line.length >= 2) - .some( - (line) => - line[0] === "U" || - line[1] === "U" || - CONFLICT_PORCELAIN_STATUSES.has(line.slice(0, 2)), - ); - for (const marker of GIT_OPERATION_MARKERS) { - for (const markerName of marker.markerNames) { - if (await pathExists(path.join(gitDir, markerName))) { - return { kind: marker.kind, hasConflicts }; - } - } - } - return { kind: "none" }; -} diff --git a/plugins/git/host/workspace-reads.ts b/plugins/git/host/workspace-reads.ts index 205fe2482ff..8048823172f 100644 --- a/plugins/git/host/workspace-reads.ts +++ b/plugins/git/host/workspace-reads.ts @@ -32,8 +32,10 @@ import { readSquashRangePatchId, type CommitGitRunner, } from "./commit-cache.js"; +import type { Stats } from "node:fs"; import fs from "node:fs/promises"; import type { + DiffPatchEntry, GitReadFreshness, RawDiffFileStat, ThreadGitDiffResponse, @@ -46,69 +48,49 @@ import type { } from "../contract.js"; import type { GitCheckoutRef } from "bb-environment-provider-host/git-types"; -export interface DiffOptions { - freshness: ReadFreshness; +interface DiffOptions { + freshness: GitReadFreshness; target: WorkspaceDiffTarget; maxDiffBytes: number; maxFileListBytes: number; maxUntrackedFiles: number; } -export type ReadFreshness = GitReadFreshness; - -export interface StatusOptions { - freshness: ReadFreshness; +interface StatusOptions { + freshness: GitReadFreshness; mergeBaseBranch?: string; maxFiles?: number; maxUntrackedLineStatFiles?: number; maxUntrackedLineStatBytes?: number; } -export type DiffResult = ThreadGitDiffResponse; - - -export interface DiffFilesArgs { - freshness: ReadFreshness; +interface DiffFilesArgs { + freshness: GitReadFreshness; target: WorkspaceDiffTarget; maxFiles: number; ignoreWhitespace: boolean; } -export interface DiffFilesResult { +interface DiffFilesResult { files: RawDiffFileStat[]; shortstat: string; mergeBaseRef: string | null; truncated: boolean; } -export interface DiffPatchArgs { - freshness: ReadFreshness; +interface DiffPatchArgs { + freshness: GitReadFreshness; target: WorkspaceDiffTarget; paths: string[]; maxBytesPerFile: number; ignoreWhitespace: boolean; } -export interface DiffPatchEntry { - path: string; - patch: string; - truncated: boolean; -} - - - - - - - - - type TruncatedOutput = { value: string; truncated: boolean; }; - type BoundedDiffStatArtifacts = { trackedEntries: RawDiffEntry[]; numstat: string; @@ -123,7 +105,7 @@ type UntrackedStatusNumstatEnrichment = { }; type ReadTrackedPatchByPathArgs = { - freshness: ReadFreshness; + freshness: GitReadFreshness; target: WorkspaceDiffTarget; paths: string[]; maxBytesPerFile: number; @@ -137,7 +119,6 @@ type ResolvedTrackedDiffRange = { mergeBaseRef: string | null; }; - type SquashMergeCheck = { merged: boolean | null; timedOut: boolean }; type MergeBaseStatusComputation = { status: WorkspaceStatus["mergeBase"]; @@ -425,7 +406,6 @@ function resolveWorkspaceState(args: { return "committed_unmerged"; } - function formatShortstat(args: { changedFiles: number; deletions: number; @@ -541,24 +521,26 @@ async function readEmptyTreeSha( return emptyTreeSha; } -type UncommittedDiffRunner = ( - buildArgs: (baseRef: string) => string[], - options: RunGitOptions, -) => Promise; - -function createUncommittedDiffRunner( +function createUncommittedDiffRunner( workspacePath: string, run: GitRunner, -): UncommittedDiffRunner { + runDiff: (args: string[], options: RunGitOptions) => Promise, +): ( + buildArgs: (baseRef: string) => string[], + options: RunGitOptions, +) => Promise { let emptyTreeShaPromise: Promise | null = null; return async (buildArgs, options) => { if (emptyTreeShaPromise !== null) { - return run(buildArgs(await emptyTreeShaPromise), options); + return runDiff(buildArgs(await emptyTreeShaPromise), options); } const headArgs = buildArgs("HEAD"); - const headResult = await run(headArgs, { ...options, allowFailure: true }); + const headResult = await runDiff(headArgs, { + ...options, + allowFailure: true, + }); if (headResult.exitCode === 0) { return headResult; } @@ -575,7 +557,7 @@ function createUncommittedDiffRunner( run, options.timeoutMs, ); - return run(buildArgs(await emptyTreeShaPromise), options); + return runDiff(buildArgs(await emptyTreeShaPromise), options); }; } @@ -691,7 +673,7 @@ export class WorkspaceReads { } private async resolveMergeBaseRef( - freshness: ReadFreshness, + freshness: GitReadFreshness, mergeBaseBranch: string, ): Promise { const snapshot = await this.requireStatusSnapshot(freshness.work); @@ -711,31 +693,24 @@ export class WorkspaceReads { private async fileSignature( relativePath: string, ): Promise<{ signature: string; racy: boolean } | null> { - try { - const signedAt = Date.now(); - const stats = await fs.lstat(path.join(this.path, relativePath)); - if (!stats.isFile() && !stats.isSymbolicLink()) return null; - return { - signature: [ - stats.mode, - stats.size, - stats.mtimeMs, - stats.ctimeMs, - stats.ino, - ].join(":"), - racy: - Math.max(stats.mtimeMs, stats.ctimeMs) >= - signedAt - - (stats.mtimeMs % 1_000 === 0 - ? COARSE_RACY_SIGNATURE_WINDOW_MS - : FINE_RACY_SIGNATURE_WINDOW_MS), - }; - } catch (error) { - if (error instanceof Error && "code" in error && error.code === "ENOENT") { - return null; - } - throw error; - } + const signedAt = Date.now(); + const stats = await lstatFileOrSymlink(path.join(this.path, relativePath)); + if (stats === null) return null; + return { + signature: [ + stats.mode, + stats.size, + stats.mtimeMs, + stats.ctimeMs, + stats.ino, + ].join(":"), + racy: + Math.max(stats.mtimeMs, stats.ctimeMs) >= + signedAt - + (stats.mtimeMs % 1_000 === 0 + ? COARSE_RACY_SIGNATURE_WINDOW_MS + : FINE_RACY_SIGNATURE_WINDOW_MS), + }; } private async readUntrackedStats( @@ -897,6 +872,9 @@ export class WorkspaceReads { await fs.rm(retained.dir, { recursive: true, force: true }); } + private readonly gitRunner: GitRunner = (args, options) => + this.runGit(args, options); + private runGit( args: string[], options: RunGitOptions, @@ -1032,12 +1010,10 @@ export class WorkspaceReads { const { freshness } = options; const snapshotRead = this.statusSnapshot(freshness.work); const otherReads = Promise.all([ - createUncommittedDiffRunner(this.path, (gitArgs, gitOptions) => - this.runGit(gitArgs, gitOptions), - )((baseRef) => ["diff", "--numstat", "-z", baseRef, "--"], { - cwd: this.path, - timeoutMs: WORKSPACE_STATUS_GIT_TIMEOUT_MS, - }).then((result) => result.stdout), + createUncommittedDiffRunner(this.path, this.gitRunner, this.gitRunner)( + (baseRef) => ["diff", "--numstat", "-z", baseRef, "--"], + { cwd: this.path, timeoutMs: WORKSPACE_STATUS_GIT_TIMEOUT_MS }, + ).then((result) => result.stdout), this.defaultBranch(freshness.refs), mergeBaseBranch ? snapshotRead.then((snapshot) => @@ -1185,11 +1161,11 @@ export class WorkspaceReads { }; } - async getDiff(options: DiffOptions): Promise { + async getDiff(options: DiffOptions): Promise { const { target, freshness, maxDiffBytes, maxFileListBytes } = options; assertPositiveInteger(options.maxUntrackedFiles, "maxUntrackedFiles"); const range = await this.resolveTrackedDiffRange(target, freshness); - const runRange = this.rangeGitRunner(range); + const runRange = this.rangeGitRunner(range, this.gitRunner); const includesUntracked = this.targetIncludesUntracked(target); const [trackedDiff, trackedStat, trackedFiles] = await Promise.all([ runRange( @@ -1271,18 +1247,22 @@ export class WorkspaceReads { }; } - private rangeGitRunner(range: ResolvedTrackedDiffRange) { + private rangeGitRunner( + range: ResolvedTrackedDiffRange, + runDiff: (args: string[], options: RunGitOptions) => Promise, + ) { const runUncommittedDiff = createUncommittedDiffRunner( this.path, - (gitArgs, options) => this.runGit(gitArgs, options), + this.gitRunner, + runDiff, ); return ( buildArgs: (rangeArgs: string[]) => string[], options: RunGitOptions, - ): Promise => + ): Promise => range.usesUncommittedHead ? runUncommittedDiff((baseRef) => buildArgs([baseRef]), options) - : this.runGit(buildArgs(range.rangeArgs), options); + : runDiff(buildArgs(range.rangeArgs), options); } async diffFiles(args: DiffFilesArgs): Promise { @@ -1421,7 +1401,6 @@ export class WorkspaceReads { return entries; } - private async readMergeBaseStatus( mergeBaseBranch: string, maxFiles: number | undefined, @@ -1622,13 +1601,9 @@ export class WorkspaceReads { }; }) : []; - let effectiveInsertions = 0; - let effectiveDeletions = 0; + let { insertions: effectiveInsertions, deletions: effectiveDeletions } = + sumNumstatLines(numstatEntries); let effectiveLineStatsComplete = numstat.exitCode === 0; - for (const entry of numstatEntries) { - if (entry.insertions !== null) effectiveInsertions += entry.insertions; - if (entry.deletions !== null) effectiveDeletions += entry.deletions; - } let squashMergeCheckComplete = true; let retryable = nameStatus.exitCode !== 0 || numstat.exitCode !== 0; @@ -1822,21 +1797,10 @@ export class WorkspaceReads { try { const candidates = await Promise.all( args.paths.map(async (relativePath) => { - try { - const stats = await fs.lstat(path.join(this.path, relativePath)); - return stats.isFile() || stats.isSymbolicLink() - ? { path: relativePath, size: stats.size } - : null; - } catch (error) { - if ( - error instanceof Error && - "code" in error && - error.code === "ENOENT" - ) { - return null; - } - throw error; - } + const stats = await lstatFileOrSymlink( + path.join(this.path, relativePath), + ); + return stats === null ? null : { path: relativePath, size: stats.size }; }), ); const eligible = candidates.filter( @@ -1879,7 +1843,7 @@ export class WorkspaceReads { target: WorkspaceDiffTarget, maxFiles: number, ignoreWhitespace: boolean, - freshness: ReadFreshness, + freshness: GitReadFreshness, ): Promise { const range = await this.resolveTrackedDiffRange(target, freshness); @@ -1953,47 +1917,16 @@ export class WorkspaceReads { recordFormat: GitNullRecordFormat; maxRecords: number; }): Promise { - const buildArgs = (rangeArgs: string[]): string[] => [ - ...args.range.baseArgs, - ...args.outputArgs, - ...rangeArgs, - ]; - if (!args.range.usesUncommittedHead) { - return this.runGitWithNullRecordLimit( - buildArgs(args.range.rangeArgs), - { cwd: this.path }, + return this.rangeGitRunner(args.range, (gitArgs, options) => + this.runGitWithNullRecordLimit( + gitArgs, + options, args.recordFormat, args.maxRecords, - ); - } - - const headArgs = buildArgs(["HEAD"]); - const headResult = await this.runGitWithNullRecordLimit( - headArgs, - { cwd: this.path, allowFailure: true }, - args.recordFormat, - args.maxRecords, - ); - if (headResult.exitCode === 0) { - return headResult; - } - if (!isMissingHeadRevisionError(headResult.stderr)) { - const detail = headResult.stderr.trim(); - throw new WorkspaceError( - "git_command_failed", - `git ${headArgs.join(" ")} failed${detail ? `: ${detail}` : ""}`, - ); - } - - const emptyTreeSha = await readEmptyTreeSha( - this.path, - (gitArgs, options) => this.runGit(gitArgs, options), - ); - return this.runGitWithNullRecordLimit( - buildArgs([emptyTreeSha]), + ), + )( + (rangeArgs) => [...args.range.baseArgs, ...args.outputArgs, ...rangeArgs], { cwd: this.path }, - args.recordFormat, - args.maxRecords, ); } @@ -2158,17 +2091,7 @@ export class WorkspaceReads { args.freshness, ); - const runUncommittedDiff = createUncommittedDiffRunner( - this.path, - (gitArgs, options) => this.runGit(gitArgs, options), - ); - const runRangeGit = ( - buildArgs: (rangeArgs: string[]) => string[], - options: RunGitOptions, - ): Promise => - range.usesUncommittedHead - ? runUncommittedDiff((baseRef) => buildArgs([baseRef]), options) - : this.runGit(buildArgs(range.rangeArgs), options); + const runRangeGit = this.rangeGitRunner(range, this.gitRunner); const whitespaceArgs = whitespaceDiffArgs(args.ignoreWhitespace); const requested = new Set(args.paths); @@ -2296,7 +2219,7 @@ export class WorkspaceReads { private async resolveTrackedDiffRange( target: WorkspaceDiffTarget, - freshness: ReadFreshness, + freshness: GitReadFreshness, ): Promise { const diffBase = ["diff", "--no-ext-diff"]; switch (target.type) { @@ -2338,12 +2261,6 @@ export class WorkspaceReads { } } - - - - - - private async withTemporaryUntrackedIndex( relativePaths: readonly string[], work: ( @@ -2422,29 +2339,27 @@ export class WorkspaceReads { relativePaths: readonly string[], ): Promise { const existing = await Promise.all( - relativePaths.map(async (relativePath) => { - try { - const stats = await fs.lstat(path.join(this.path, relativePath)); - return stats.isFile() || stats.isSymbolicLink() ? relativePath : null; - } catch (error) { - if ( - error instanceof Error && - "code" in error && - error.code === "ENOENT" - ) { - return null; - } - throw error; - } - }), + relativePaths.map(async (relativePath) => + (await lstatFileOrSymlink(path.join(this.path, relativePath))) === null + ? null + : relativePath, + ), ); return existing.filter((value): value is string => value !== null); } - - - } +async function lstatFileOrSymlink(absolutePath: string): Promise { + try { + const stats = await fs.lstat(absolutePath); + return stats.isFile() || stats.isSymbolicLink() ? stats : null; + } catch (error) { + if (error instanceof Error && "code" in error && error.code === "ENOENT") { + return null; + } + throw error; + } +} function joinDiffArtifactLines(parts: string[]): string { return parts