diff --git a/packages/environment-provider-host/src/workspace-git.ts b/packages/environment-provider-host/src/workspace-git.ts index 5e0bf831d36..56b3b9fe6e5 100644 --- a/packages/environment-provider-host/src/workspace-git.ts +++ b/packages/environment-provider-host/src/workspace-git.ts @@ -120,16 +120,67 @@ 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"], + ["log.showSignature", "false"], +]; + +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..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, @@ -15,12 +17,14 @@ import { detectGitRepoKind, ensureGitRepo, hasUncommittedChanges, + isMissingHeadRevisionError, parsePorcelainV2StatusZ, readDefaultBranchRefs, runGit, } from "../src/workspace-git.js"; import { fetchRemoteBranches } from "../src/branch-options.js"; +const execFileAsync = promisify(execFile); const tempDirs: string[] = []; async function initReadGitBlobRepo() { @@ -157,6 +161,192 @@ 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"]); + }); + + 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", () => { 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/worktree.ts b/plugins/environment-git-worktree/host/worktree.ts index ec5e3389d44..69820f80457 100644 --- a/plugins/environment-git-worktree/host/worktree.ts +++ b/plugins/environment-git-worktree/host/worktree.ts @@ -501,7 +501,23 @@ async function readCompletedBranch( } } +async function refreshWorktreeIndex( + worktreePath: string, + signal: AbortSignal | undefined, +): Promise { + try { + await runGit(["update-index", "-q", "--refresh", "--force-write-index"], { + cwd: worktreePath, + allowFailure: true, + ...signalOptions(signal), + }); + } 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",