Skip to content

Commit efdda5e

Browse files
t3dotggclaude
andauthored
perf(server): skip the macOS xcrun git shim (pingdotgg#22759)
Co-authored-by: Claude Opus 5.5 <[email protected]>
1 parent 848e352 commit efdda5e

3 files changed

Lines changed: 149 additions & 31 deletions

File tree

Lines changed: 0 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,3 @@
1-
// @effect-diagnostics nodeBuiltinImport:off - runs once at test setup, outside any Effect runtime.
2-
import * as NodeChildProcess from "node:child_process";
3-
import * as NodeFS from "node:fs";
4-
import * as NodePath from "node:path";
5-
import * as HostProcess from "@t3tools/shared/HostProcess";
6-
71
// Git for Windows installs with core.autocrlf=true, which checks committed LF
82
// files out as CRLF and breaks every byte-exact content assertion; a signing
93
// key or a non-default init branch on the developer's machine breaks fixtures
@@ -24,24 +18,3 @@ entries.forEach(([key, value], index) => {
2418
process.env[`GIT_CONFIG_KEY_${existing + index}`] = key;
2519
process.env[`GIT_CONFIG_VALUE_${existing + index}`] = value;
2620
});
27-
28-
// Without Homebrew git, macOS resolves `git` to /usr/bin/git, an xcrun shim that costs
29-
// about 8 ms per spawn against 3 ms for the real binary. Git-heavy files such as
30-
// GitVcsDriverCore.test.ts and GitManager.test.ts run twice as fast with the real one.
31-
if (HostProcess.Platform.defaultValue() === "darwin") {
32-
const gitOnPath = (process.env.PATH ?? "")
33-
.split(NodePath.delimiter)
34-
.map((dir) => NodePath.join(dir, "git"))
35-
.find((candidate) => NodeFS.existsSync(candidate));
36-
if (gitOnPath === "/usr/bin/git") {
37-
try {
38-
const realGit = NodeChildProcess.execFileSync("xcrun", ["-f", "git"], {
39-
encoding: "utf8",
40-
stdio: ["ignore", "pipe", "ignore"],
41-
}).trim();
42-
if (NodePath.isAbsolute(realGit)) {
43-
process.env.PATH = `${NodePath.dirname(realGit)}${NodePath.delimiter}${process.env.PATH}`;
44-
}
45-
} catch {}
46-
}
47-
}

‎packages/shared/src/shell.test.ts‎

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@ import {
3030
WindowsShellEnvironment,
3131
withPathDirectoryListings,
3232
type WindowsShellEnvironmentReader,
33+
XcodeGitLocation,
3334
} from "./shell.ts";
3435

3536
const withWindowsEnvironmentMocks = <A, E, R>(
@@ -634,6 +635,77 @@ effectIt.layer(NodeServices.layer)("resolveSpawnCommand", (it) => {
634635
}),
635636
);
636637

638+
describe("macOS git", () => {
639+
// Files that exist, the git first on PATH, and what `xcrun --find git` prints.
640+
const setup = (options: {
641+
readonly platform?: NodeJS.Platform;
642+
readonly gitOnPath: string;
643+
readonly xcrunGit: string | undefined;
644+
}) => {
645+
const files = new Set([options.gitOnPath, ...(options.xcrunGit ? [options.xcrunGit] : [])]);
646+
const host = { xcrunGit: options.xcrunGit, xcrunCalls: 0 };
647+
const resolve = resolveSpawnCommand("git", ["status"], { env: { PATH: "/fake/bin" } }).pipe(
648+
Effect.map((resolved) => resolved.command),
649+
Effect.provideService(HostProcess.Platform, options.platform ?? "darwin"),
650+
Effect.provideService(SpawnExecutableResolution, (command) =>
651+
command === "git" ? options.gitOnPath : files.has(command) ? command : undefined,
652+
),
653+
Effect.provideService(XcodeGitLocation, () => {
654+
host.xcrunCalls += 1;
655+
return host.xcrunGit;
656+
}),
657+
);
658+
return { files, host, resolve };
659+
};
660+
661+
const XCODE_GIT = "/Applications/Xcode.app/Contents/Developer/usr/bin/git";
662+
663+
it.effect("runs the git behind the xcrun shim and looks it up once", () =>
664+
Effect.gen(function* () {
665+
const { host, resolve } = setup({ gitOnPath: "/usr/bin/git", xcrunGit: XCODE_GIT });
666+
expect(yield* resolve).toBe(XCODE_GIT);
667+
expect(yield* resolve).toBe(XCODE_GIT);
668+
expect(host.xcrunCalls).toBe(1);
669+
}).pipe(Effect.provideService(CommandResolutionCache, new Map())),
670+
);
671+
672+
it.effect("keeps git when PATH has another git or the host is not macOS", () =>
673+
Effect.gen(function* () {
674+
const homebrew = setup({ gitOnPath: "/opt/homebrew/bin/git", xcrunGit: XCODE_GIT });
675+
expect(yield* homebrew.resolve).toBe("git");
676+
expect(homebrew.host.xcrunCalls).toBe(0);
677+
678+
const linux = setup({ platform: "linux", gitOnPath: "/usr/bin/git", xcrunGit: XCODE_GIT });
679+
expect(yield* linux.resolve).toBe("git");
680+
}).pipe(Effect.provideService(CommandResolutionCache, new Map())),
681+
);
682+
683+
it.effect("keeps git when xcrun fails or names a missing file", () =>
684+
Effect.gen(function* () {
685+
const failed = setup({ gitOnPath: "/usr/bin/git", xcrunGit: undefined });
686+
expect(yield* failed.resolve).toBe("git");
687+
688+
const missing = setup({ gitOnPath: "/usr/bin/git", xcrunGit: XCODE_GIT });
689+
missing.files.delete(XCODE_GIT);
690+
expect(yield* missing.resolve).toBe("git");
691+
}).pipe(Effect.provideService(CommandResolutionCache, new Map())),
692+
);
693+
694+
it.effect("looks again when the resolved git disappears", () =>
695+
Effect.gen(function* () {
696+
const betaGit = "/Applications/Xcode-beta.app/Contents/Developer/usr/bin/git";
697+
const { files, host, resolve } = setup({ gitOnPath: "/usr/bin/git", xcrunGit: XCODE_GIT });
698+
expect(yield* resolve).toBe(XCODE_GIT);
699+
700+
files.delete(XCODE_GIT);
701+
files.add(betaGit);
702+
host.xcrunGit = betaGit;
703+
expect(yield* resolve).toBe(betaGit);
704+
expect(host.xcrunCalls).toBe(2);
705+
}).pipe(Effect.provideService(CommandResolutionCache, new Map())),
706+
);
707+
});
708+
637709
it.effect("does not fall back to a shell for unresolved Windows commands", () =>
638710
Effect.gen(function* () {
639711
const command = yield* resolveSpawnCommand("missing & calc", ["unsafe & value"], {

‎packages/shared/src/shell.ts‎

Lines changed: 77 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -549,11 +549,11 @@ export const withPathDirectoryListings =
549549
return yield* effect.pipe(Effect.provideService(PathDirectoryListings, listings));
550550
});
551551

552-
// An injected resolver may answer differently for the same search, so its
552+
// An injected resolver or locator may answer differently for the same search, so its
553553
// entries are kept apart from every other resolver's.
554554
let spawnResolverCacheIdCount = 0;
555-
const spawnResolverCacheIds = new WeakMap<SpawnExecutableResolver, number>();
556-
function spawnResolverCacheId(resolver: SpawnExecutableResolver): number {
555+
const spawnResolverCacheIds = new WeakMap<SpawnExecutableResolver | XcodeGitLocator, number>();
556+
function spawnResolverCacheId(resolver: SpawnExecutableResolver | XcodeGitLocator): number {
557557
const known = spawnResolverCacheIds.get(resolver);
558558
if (known !== undefined) return known;
559559
const id = spawnResolverCacheIdCount++;
@@ -765,6 +765,71 @@ export function npmShimExecutable(
765765
return isFile(executable) ? executable : undefined;
766766
}
767767

768+
export type XcodeGitLocator = (env: NodeJS.ProcessEnv) => string | undefined;
769+
770+
// xcrun honors DEVELOPER_DIR and the `xcode-select` choice, as the shim does.
771+
function locateXcodeGitWithXcrun(env: NodeJS.ProcessEnv): string | undefined {
772+
try {
773+
const located = NodeChildProcess.execFileSync("/usr/bin/xcrun", ["--find", "git"], {
774+
encoding: "utf8",
775+
env,
776+
timeout: 5_000,
777+
stdio: ["ignore", "pipe", "ignore"],
778+
}).trim();
779+
return NodePath.isAbsolute(located) ? located : undefined;
780+
} catch {
781+
return undefined;
782+
}
783+
}
784+
785+
export const XcodeGitLocation = Context.Reference<XcodeGitLocator>(
786+
"@t3tools/shared/shell/XcodeGitLocation",
787+
{ defaultValue: () => locateXcodeGitWithXcrun },
788+
);
789+
790+
const MACOS_GIT_SHIM = "/usr/bin/git";
791+
792+
/**
793+
* /usr/bin/git is an xcrun shim that finds the active developer directory on
794+
* every run: about 8 ms per spawn, against under 3 ms for the git behind it.
795+
* Only the shim is replaced, so a git the user put first on PATH (Homebrew,
796+
* Nix) still wins, and git's own children keep the same PATH. Any lookup
797+
* failure keeps plain `git`.
798+
*/
799+
const resolveMacosGit = Effect.fnUntraced(function* (
800+
env: NodeJS.ProcessEnv,
801+
resolveExecutable: SpawnExecutableResolver,
802+
) {
803+
const locateXcodeGit = yield* XcodeGitLocation;
804+
const cache = yield* CommandResolutionCache;
805+
const cacheKey = [
806+
"xcode-git",
807+
String(spawnResolverCacheId(resolveExecutable)),
808+
String(spawnResolverCacheId(locateXcodeGit)),
809+
resolvePathEnvironmentVariable(env),
810+
env.DEVELOPER_DIR ?? "",
811+
].join(COMMAND_RESOLUTION_CACHE_KEY_SEPARATOR);
812+
const nowNanos = yield* Clock.currentTimeNanos;
813+
const cached = cache.get(cacheKey);
814+
// An Xcode update or removal deletes the binary; look again instead of failing the spawn.
815+
if (
816+
cached !== undefined &&
817+
cached.expiresAtNanos > nowNanos &&
818+
(cached.resolvedPath === null ||
819+
resolveExecutable(cached.resolvedPath, "darwin", env) !== undefined)
820+
) {
821+
return cached.resolvedPath ?? "git";
822+
}
823+
const located =
824+
resolveExecutable("git", "darwin", env) === MACOS_GIT_SHIM ? locateXcodeGit(env) : undefined;
825+
const realGit =
826+
located !== undefined && resolveExecutable(located, "darwin", env) !== undefined
827+
? located
828+
: null;
829+
cacheCommandResolution(cache, cacheKey, realGit, nowNanos);
830+
return realGit ?? "git";
831+
});
832+
768833
export interface SpawnCommandOptions extends CommandAvailabilityOptions {
769834
/** Run the executable behind an npm cmd-shim directly (see `npmShimExecutable`). */
770835
readonly bypassNpmShim?: boolean;
@@ -776,7 +841,8 @@ export const resolveSpawnCommand = Effect.fnUntraced(function* (
776841
options: SpawnCommandOptions = {},
777842
): Effect.fn.Return<ResolvedSpawnCommand> {
778843
const platform = yield* HostProcess.Platform;
779-
if (platform !== "win32") {
844+
const isMacosGit = platform === "darwin" && command === "git";
845+
if (platform !== "win32" && !isMacosGit) {
780846
return { command, args: [...args], shell: false };
781847
}
782848

@@ -788,6 +854,13 @@ export const resolveSpawnCommand = Effect.fnUntraced(function* (
788854
? { ...hostEnvironment, ...options.env }
789855
: options.env;
790856
const resolveExecutable = yield* SpawnExecutableResolution;
857+
if (isMacosGit) {
858+
return {
859+
command: yield* resolveMacosGit(env, resolveExecutable),
860+
args: [...args],
861+
shell: false,
862+
};
863+
}
791864
// The scan is synchronous and runs before every child process, so it shares
792865
// the PATH scan cache above. Explicit paths stay uncached for the same reason,
793866
// and so do misses: a failed spawn is how providers report "not installed",

0 commit comments

Comments
 (0)