From abfca1a10e222fd26d4ac58762cc4d32d36f4ef2 Mon Sep 17 00:00:00 2001 From: Michael Yong Date: Wed, 18 Nov 2026 12:42:14 -0800 Subject: [PATCH 1/2] Make bb's git reads ignore user git display settings Every git process bb spawns through the shared runGit now carries one set of command-scope config overrides (no colour, a/ b/ prefixes, suppressBlankEmpty and relative off, short submodule format), merged with any GIT_CONFIG_* entries already present, plus LANGUAGE=C so error matching sees English while hooks keep the user's LANG/LC_*. New worktrees refresh their index after git worktree add, waiting into the next second when needed, so status stops re-hashing racily clean files. Co-Authored-By: Claude Opus 5.5 --- .../src/workspace-git.ts | 62 +++++++- .../test/workspace-git.test.ts | 142 ++++++++++++++++++ plugins/environment-git-worktree/host.test.ts | 34 +++++ .../environment-git-worktree/host/worktree.ts | 37 +++++ 4 files changed, 269 insertions(+), 6 deletions(-) diff --git a/packages/environment-provider-host/src/workspace-git.ts b/packages/environment-provider-host/src/workspace-git.ts index 5e0bf831d36..07f441024df 100644 --- a/packages/environment-provider-host/src/workspace-git.ts +++ b/packages/environment-provider-host/src/workspace-git.ts @@ -120,16 +120,66 @@ export function trimOutput(value: string): string { return value.trim().replace(/\n+$/u, ""); } +type GitConfigEntry = readonly [key: string, value: string]; + +const MACHINE_READ_GIT_CONFIG: readonly GitConfigEntry[] = [ + ["color.ui", "never"], + ["color.diff", "never"], + ["color.branch", "never"], + ["color.status", "never"], + ["diff.noprefix", "false"], + ["diff.mnemonicPrefix", "false"], + ["diff.srcPrefix", "a/"], + ["diff.dstPrefix", "b/"], + ["diff.suppressBlankEmpty", "false"], + ["diff.relative", "false"], + ["diff.submodule", "short"], +]; + +const GIT_CONFIG_ENV_KEY = /^GIT_CONFIG_(?:COUNT|KEY_\d+|VALUE_\d+)$/u; + +function readGitConfigEnv(env: NodeJS.ProcessEnv): GitConfigEntry[] { + const count = Number(env.GIT_CONFIG_COUNT ?? "0"); + if (!Number.isSafeInteger(count) || count < 0) return []; + const entries: GitConfigEntry[] = []; + for (let index = 0; index < count; index += 1) { + const key = env[`GIT_CONFIG_KEY_${index}`]; + if (key === undefined) continue; + entries.push([key, env[`GIT_CONFIG_VALUE_${index}`] ?? ""]); + } + return entries; +} + +function withoutGitConfigEnv(env: NodeJS.ProcessEnv): NodeJS.ProcessEnv { + return Object.fromEntries( + Object.entries(env).filter(([key]) => !GIT_CONFIG_ENV_KEY.test(key)), + ); +} + export function resolveGitProcessEnv( args: ResolveGitProcessEnvArgs, ): NodeJS.ProcessEnv { - return { - ...sanitizeInheritedChildProcessEnv({ - env: process.env, - ...(args.shellPath !== undefined ? { shellPath: args.shellPath } : {}), - }), - ...args.env, + const inherited = sanitizeInheritedChildProcessEnv({ + env: process.env, + ...(args.shellPath !== undefined ? { shellPath: args.shellPath } : {}), + }); + const requested = args.env ?? {}; + const config = [ + ...readGitConfigEnv(inherited), + ...MACHINE_READ_GIT_CONFIG, + ...readGitConfigEnv(requested), + ]; + const env: NodeJS.ProcessEnv = { + ...withoutGitConfigEnv(inherited), + LANGUAGE: "C", + ...withoutGitConfigEnv(requested), + GIT_CONFIG_COUNT: String(config.length), }; + config.forEach(([key, value], index) => { + env[`GIT_CONFIG_KEY_${index}`] = key; + env[`GIT_CONFIG_VALUE_${index}`] = value; + }); + return env; } function createGitCommandTimedOutError( diff --git a/packages/environment-provider-host/test/workspace-git.test.ts b/packages/environment-provider-host/test/workspace-git.test.ts index e068d20fa77..4047778ba77 100644 --- a/packages/environment-provider-host/test/workspace-git.test.ts +++ b/packages/environment-provider-host/test/workspace-git.test.ts @@ -15,6 +15,7 @@ import { detectGitRepoKind, ensureGitRepo, hasUncommittedChanges, + isMissingHeadRevisionError, parsePorcelainV2StatusZ, readDefaultBranchRefs, runGit, @@ -157,6 +158,147 @@ describe("runGit", () => { }); }); +describe("user Git settings on machine reads", () => { + let templatePath: string; + + beforeAll(async () => { + templatePath = await fs.mkdtemp(path.join(os.tmpdir(), "bb-git-display-")); + await runGit(["init", "-b", "main"], { cwd: templatePath }); + await writeTestIdentity(templatePath); + await fs.mkdir(path.join(templatePath, "app")); + await fs.mkdir(path.join(templatePath, "sub")); + await fs.writeFile(path.join(templatePath, "blank.txt"), "a\n\nb\n"); + await fs.writeFile(path.join(templatePath, "app", "inner.txt"), "one\n"); + await runGit( + ["update-index", "--add", "--cacheinfo", `160000,${"1".repeat(40)},sub`], + { cwd: templatePath }, + ); + await runGit(["add", "."], { cwd: templatePath }); + await runGit(["commit", "-m", "base"], { cwd: templatePath }); + await fs.writeFile(path.join(templatePath, "blank.txt"), "a\n\nB\n"); + await fs.writeFile(path.join(templatePath, "app", "inner.txt"), "two\n"); + await runGit( + ["update-index", "--cacheinfo", `160000,${"2".repeat(40)},sub`], + { cwd: templatePath }, + ); + await runGit(["commit", "-am", "change"], { cwd: templatePath }); + await fs.writeFile(path.join(templatePath, "blank.txt"), "a\n\nC\n"); + }); + + afterAll(() => fs.rm(templatePath, { recursive: true, force: true })); + + async function repoWithConfig(config: Record) { + const parent = await fs.mkdtemp(path.join(os.tmpdir(), "bb-git-display-")); + tempDirs.push(parent); + const repoPath = path.join(parent, "repo"); + await fs.cp(templatePath, repoPath, { recursive: true }); + for (const [key, value] of Object.entries(config)) { + await runGit(["config", key, value], { cwd: repoPath }); + } + return repoPath; + } + + async function readPatches(repoPath: string) { + const cwd = path.join(repoPath, "app"); + const diff = await runGit(["diff", "HEAD~1", "HEAD"], { cwd }); + const log = await runGit(["log", "-p", "-1", "--format=%s"], { cwd }); + const show = await runGit(["show", "--format=%s", "HEAD"], { cwd }); + const worktree = await runGit(["diff", "HEAD", "--", ":/"], { cwd }); + return { + diff: diff.stdout, + log: log.stdout, + show: show.stdout, + worktree: worktree.stdout, + }; + } + + it.for<[string, Record]>([ + ["color.ui=always", { "color.ui": "always" }], + ["color.diff=always", { "color.ui": "never", "color.diff": "always" }], + ["diff.noprefix", { "diff.noprefix": "true" }], + ["diff.mnemonicPrefix", { "diff.mnemonicPrefix": "true" }], + [ + "diff.srcPrefix/dstPrefix", + { "diff.srcPrefix": "x/", "diff.dstPrefix": "y/" }, + ], + ["diff.suppressBlankEmpty", { "diff.suppressBlankEmpty": "true" }], + ["diff.relative", { "diff.relative": "true" }], + ["diff.submodule=log", { "diff.submodule": "log" }], + ["diff.submodule=diff", { "diff.submodule": "diff" }], + ])("keeps the standard patch format under %s", async ([, config]) => { + const expected = await readPatches(await repoWithConfig({})); + expect(expected.diff).toContain("diff --git a/blank.txt b/blank.txt"); + expect(expected.diff).toContain(" a\n \n-b\n+B\n"); + expect(expected.diff).toContain("+Subproject commit 2222"); + expect(expected.diff).toContain("diff --git a/app/inner.txt"); + expect(expected.worktree).toContain("--- a/blank.txt\n+++ b/blank.txt"); + + await expect(readPatches(await repoWithConfig(config))).resolves.toEqual( + expected, + ); + }); + + it.skipIf(process.platform === "win32")( + "reads Git messages in English when the user's language is translated", + async () => { + const binPath = await fs.mkdtemp(path.join(os.tmpdir(), "bb-git-lang-")); + tempDirs.push(binPath); + await fs.writeFile( + path.join(binPath, "git"), + [ + "#!/bin/sh", + 'if [ "$LANGUAGE" = C ]; then', + " echo \"fatal: ambiguous argument 'HEAD': unknown revision or path not in the working tree.\" >&2", + "else", + " echo \"Schwerwiegend: mehrdeutiges Argument 'HEAD': unbekannter Commit\" >&2", + "fi", + 'printf "%s|%s" "$LANG" "$LC_ALL"', + "exit 128", + "", + ].join("\n"), + { mode: 0o755 }, + ); + vi.stubEnv("LANG", "de_DE.UTF-8"); + vi.stubEnv("LANGUAGE", "de"); + vi.stubEnv("LC_ALL", "de_DE.UTF-8"); + + const result = await runGit(["rev-parse", "HEAD"], { + cwd: binPath, + shellPath: binPath, + allowFailure: true, + }); + + expect(isMissingHeadRevisionError(result.stderr)).toBe(true); + expect(result.stdout).toBe("de_DE.UTF-8|de_DE.UTF-8"); + }, + ); + + it("keeps inherited and caller Git config alongside the overrides", async () => { + const repoPath = await repoWithConfig({}); + vi.stubEnv("GIT_CONFIG_COUNT", "1"); + vi.stubEnv("GIT_CONFIG_KEY_0", "bb.inherited"); + vi.stubEnv("GIT_CONFIG_VALUE_0", "machine"); + + const readConfig = async (key: string) => + ( + await runGit(["config", "--get", key], { + cwd: repoPath, + env: { + GIT_CONFIG_COUNT: "1", + GIT_CONFIG_KEY_0: "core.splitIndex", + GIT_CONFIG_VALUE_0: "false", + }, + }) + ).stdout.trim(); + + await expect( + Promise.all( + ["bb.inherited", "color.ui", "core.splitIndex"].map(readConfig), + ), + ).resolves.toEqual(["machine", "never", "false"]); + }); +}); + describe("detectGitRepoKind", () => { it("tells a bare repository root apart from its worktrees and plain directories", async () => { const { root, worktreePath } = await initBareWorktreeLayout(); diff --git a/plugins/environment-git-worktree/host.test.ts b/plugins/environment-git-worktree/host.test.ts index 2c80a704471..9055e203d7f 100644 --- a/plugins/environment-git-worktree/host.test.ts +++ b/plugins/environment-git-worktree/host.test.ts @@ -9,6 +9,7 @@ import { readdir, realpath, rm, + stat, symlink, writeFile, } from "node:fs/promises"; @@ -274,6 +275,39 @@ describe.concurrent("worktree host entry", () => { }, ); + it("writes a new worktree's index after its checkout second so status does not re-hash files", async ({ + onTestFinished, + }) => { + const { sourcePath, dataDir } = + await createSourceRepository(onTestFinished); + const harness = createHarness(dataDir); + onTestFinished(() => harness.experimental_dispose()); + const created = await harness.experimental_call( + "create", + createInput({ + operationId: "create-refreshed", + sourcePath, + pathKey: "refreshed", + branchName: "bb/refreshed", + }), + ); + if (created.status !== "created") throw new Error(created.message); + const indexPath = ( + await git( + created.path, + "rev-parse", + "--path-format=absolute", + "--git-path", + "index", + ) + ).trim(); + const indexSecond = Math.floor((await stat(indexPath)).mtimeMs / 1000); + const fileSecond = Math.floor( + (await stat(join(created.path, "README.md"))).mtimeMs / 1000, + ); + expect(indexSecond).toBeGreaterThan(fileSecond); + }); + it.for(["main", "release", "origin/main", "refs/heads/main"])( "resolves and fetches a stale named base %s", async (base, { onTestFinished }) => { diff --git a/plugins/environment-git-worktree/host/worktree.ts b/plugins/environment-git-worktree/host/worktree.ts index ec5e3389d44..6d3219c7d35 100644 --- a/plugins/environment-git-worktree/host/worktree.ts +++ b/plugins/environment-git-worktree/host/worktree.ts @@ -65,6 +65,8 @@ interface RemoveWorktreeArgs { } const REMOTE_BASE_FETCH_TIMEOUT_MS = 60_000; +const RACY_INDEX_CLOCK_MARGIN_MS = 50; +const RACY_INDEX_MAX_WAIT_MS = 2_000; const REMOTE_REF_LOCK_RETRY_INTERVAL_MS = 200; const REMOTE_REF_LOCK_RETRY_TIMEOUT_MS = 2_000; const WORKTREE_INCLUDE_TRANSCRIPT_PATH_LIMIT = 20; @@ -501,7 +503,42 @@ async function readCompletedBranch( } } +async function indexMtimeSecond(indexPath: string): Promise { + return Math.floor((await fs.stat(indexPath)).mtimeMs / 1000); +} + +async function refreshWorktreeIndex( + worktreePath: string, + signal: AbortSignal | undefined, +): Promise { + const options = { cwd: worktreePath, ...signalOptions(signal) }; + const refresh = () => + runGit(["update-index", "-q", "--refresh", "--force-write-index"], { + ...options, + allowFailure: true, + }); + try { + const indexPath = path.resolve( + worktreePath, + ( + await runGit(["rev-parse", "--git-path", "index"], options) + ).stdout.trim(), + ); + const checkoutSecond = await indexMtimeSecond(indexPath); + await refresh(); + if ((await indexMtimeSecond(indexPath)) !== checkoutSecond) return; + const waitMs = + (checkoutSecond + 1) * 1000 + RACY_INDEX_CLOCK_MARGIN_MS - Date.now(); + if (waitMs >= RACY_INDEX_MAX_WAIT_MS) return; + if (waitMs > 0) await delay(waitMs, undefined, signalOptions(signal)); + await refresh(); + } catch (error) { + if (signal?.aborted) throw createProvisionCancelledError(error); + } +} + async function finishWorktreeSetup(args: CreateWorktreeArgs): Promise { + await refreshWorktreeIndex(args.targetPath, args.signal); emitCwd({ onProgress: args.onProgress, keySuffix: "target", From d2164e72f161f7b1deaed49a85bdad361cdcbbf2 Mon Sep 17 00:00:00 2001 From: Michael Yong Date: Wed, 18 Nov 2026 13:41:34 -0800 Subject: [PATCH 2/2] Refresh a new worktree's index once and pin log.showSignature A second, delayed refresh only ran when checkout and the first refresh finished within the same second, which happens only for small repos whose racily clean entries cost almost nothing to re-hash. It added up to about a second to worktree setup for no measurable status gain. log.showSignature=true made every bb log/show verify commit signatures and print the result into output bb parses. Co-Authored-By: Claude Opus 5.5 --- .../src/workspace-git.ts | 1 + .../test/workspace-git.test.ts | 48 +++++++++++++++++++ plugins/environment-git-worktree/host.test.ts | 34 ------------- .../environment-git-worktree/host/worktree.ts | 29 ++--------- 4 files changed, 53 insertions(+), 59 deletions(-) diff --git a/packages/environment-provider-host/src/workspace-git.ts b/packages/environment-provider-host/src/workspace-git.ts index 07f441024df..56b3b9fe6e5 100644 --- a/packages/environment-provider-host/src/workspace-git.ts +++ b/packages/environment-provider-host/src/workspace-git.ts @@ -134,6 +134,7 @@ const MACHINE_READ_GIT_CONFIG: readonly GitConfigEntry[] = [ ["diff.suppressBlankEmpty", "false"], ["diff.relative", "false"], ["diff.submodule", "short"], + ["log.showSignature", "false"], ]; const GIT_CONFIG_ENV_KEY = /^GIT_CONFIG_(?:COUNT|KEY_\d+|VALUE_\d+)$/u; diff --git a/packages/environment-provider-host/test/workspace-git.test.ts b/packages/environment-provider-host/test/workspace-git.test.ts index 4047778ba77..881de74379f 100644 --- a/packages/environment-provider-host/test/workspace-git.test.ts +++ b/packages/environment-provider-host/test/workspace-git.test.ts @@ -1,6 +1,8 @@ +import { execFile } from "node:child_process"; import fs from "node:fs/promises"; import os from "node:os"; import path from "node:path"; +import { promisify } from "node:util"; import { afterAll, afterEach, @@ -22,6 +24,7 @@ import { } from "../src/workspace-git.js"; import { fetchRemoteBranches } from "../src/branch-options.js"; +const execFileAsync = promisify(execFile); const tempDirs: string[] = []; async function initReadGitBlobRepo() { @@ -297,6 +300,51 @@ describe("user Git settings on machine reads", () => { ), ).resolves.toEqual(["machine", "never", "false"]); }); + + it.skipIf(process.platform === "win32")( + "leaves signature checks out of log and show output under log.showSignature", + async () => { + const repoPath = await repoWithConfig({}); + const keyPath = path.join(path.dirname(repoPath), "signing-key"); + await execFileAsync("ssh-keygen", [ + "-q", + "-t", + "ed25519", + "-N", + "", + "-f", + keyPath, + ]); + const allowedSigners = path.join(path.dirname(repoPath), "signers"); + await fs.writeFile( + allowedSigners, + `bb@example.com ${await fs.readFile(`${keyPath}.pub`, "utf8")}`, + ); + for (const [key, value] of [ + ["gpg.format", "ssh"], + ["user.signingKey", `${keyPath}.pub`], + ["gpg.ssh.allowedSignersFile", allowedSigners], + ["log.showSignature", "true"], + ]) { + await runGit(["config", key, value], { cwd: repoPath }); + } + await runGit(["commit", "-S", "--allow-empty", "-m", "signed"], { + cwd: repoPath, + }); + const sha = ( + await runGit(["rev-parse", "HEAD"], { cwd: repoPath }) + ).stdout.trim(); + + const log = await runGit(["log", "-1", "--format=%H"], { + cwd: repoPath, + }); + const show = await runGit(["show", "--format=%H", "--no-patch", "HEAD"], { + cwd: repoPath, + }); + + expect([log.stdout, show.stdout]).toEqual([`${sha}\n`, `${sha}\n`]); + }, + ); }); describe("detectGitRepoKind", () => { diff --git a/plugins/environment-git-worktree/host.test.ts b/plugins/environment-git-worktree/host.test.ts index 9055e203d7f..2c80a704471 100644 --- a/plugins/environment-git-worktree/host.test.ts +++ b/plugins/environment-git-worktree/host.test.ts @@ -9,7 +9,6 @@ import { readdir, realpath, rm, - stat, symlink, writeFile, } from "node:fs/promises"; @@ -275,39 +274,6 @@ describe.concurrent("worktree host entry", () => { }, ); - it("writes a new worktree's index after its checkout second so status does not re-hash files", async ({ - onTestFinished, - }) => { - const { sourcePath, dataDir } = - await createSourceRepository(onTestFinished); - const harness = createHarness(dataDir); - onTestFinished(() => harness.experimental_dispose()); - const created = await harness.experimental_call( - "create", - createInput({ - operationId: "create-refreshed", - sourcePath, - pathKey: "refreshed", - branchName: "bb/refreshed", - }), - ); - if (created.status !== "created") throw new Error(created.message); - const indexPath = ( - await git( - created.path, - "rev-parse", - "--path-format=absolute", - "--git-path", - "index", - ) - ).trim(); - const indexSecond = Math.floor((await stat(indexPath)).mtimeMs / 1000); - const fileSecond = Math.floor( - (await stat(join(created.path, "README.md"))).mtimeMs / 1000, - ); - expect(indexSecond).toBeGreaterThan(fileSecond); - }); - it.for(["main", "release", "origin/main", "refs/heads/main"])( "resolves and fetches a stale named base %s", async (base, { onTestFinished }) => { diff --git a/plugins/environment-git-worktree/host/worktree.ts b/plugins/environment-git-worktree/host/worktree.ts index 6d3219c7d35..69820f80457 100644 --- a/plugins/environment-git-worktree/host/worktree.ts +++ b/plugins/environment-git-worktree/host/worktree.ts @@ -65,8 +65,6 @@ interface RemoveWorktreeArgs { } const REMOTE_BASE_FETCH_TIMEOUT_MS = 60_000; -const RACY_INDEX_CLOCK_MARGIN_MS = 50; -const RACY_INDEX_MAX_WAIT_MS = 2_000; const REMOTE_REF_LOCK_RETRY_INTERVAL_MS = 200; const REMOTE_REF_LOCK_RETRY_TIMEOUT_MS = 2_000; const WORKTREE_INCLUDE_TRANSCRIPT_PATH_LIMIT = 20; @@ -503,35 +501,16 @@ async function readCompletedBranch( } } -async function indexMtimeSecond(indexPath: string): Promise { - return Math.floor((await fs.stat(indexPath)).mtimeMs / 1000); -} - async function refreshWorktreeIndex( worktreePath: string, signal: AbortSignal | undefined, ): Promise { - const options = { cwd: worktreePath, ...signalOptions(signal) }; - const refresh = () => - runGit(["update-index", "-q", "--refresh", "--force-write-index"], { - ...options, + try { + await runGit(["update-index", "-q", "--refresh", "--force-write-index"], { + cwd: worktreePath, allowFailure: true, + ...signalOptions(signal), }); - try { - const indexPath = path.resolve( - worktreePath, - ( - await runGit(["rev-parse", "--git-path", "index"], options) - ).stdout.trim(), - ); - const checkoutSecond = await indexMtimeSecond(indexPath); - await refresh(); - if ((await indexMtimeSecond(indexPath)) !== checkoutSecond) return; - const waitMs = - (checkoutSecond + 1) * 1000 + RACY_INDEX_CLOCK_MARGIN_MS - Date.now(); - if (waitMs >= RACY_INDEX_MAX_WAIT_MS) return; - if (waitMs > 0) await delay(waitMs, undefined, signalOptions(signal)); - await refresh(); } catch (error) { if (signal?.aborted) throw createProvisionCancelledError(error); }