Файли
openidea/src/features/tools/xcodeBsp.ts
T
LU XIANGRUIтаwildcatDownstairs 1425bfe8ae feat(xcode): build in the background for code insight before the first build (#7339)
Opening an Xcode project with no build log builds its first scheme once in the background, so xcode-build-server has compiler arguments and sourcekit-lsp gives cross-target insight before the first Run. The build is cancellable, waits for Xcode's own build database, restarts sourcekit-lsp when it ends, and foreground builds cancel and reap it first. Xcode process execution lives in ide-run.

Closes #7337

Co-authored-by: wildcatDownstairs <[email protected]>
2026-12-02 16:32:55 +08:00

145 рядки
5.8 KiB
TypeScript
Неформатований Анотація Історія

Цей файл містить неоднозначні символи Юнікоду
Цей файл містить символи Юнікоду, які можна сплутати з іншими символами. Якщо ви вважаєте, що це зроблено навмисно, можете сміливо ігнорувати це попередження. Щоб показати їх, скористайтеся кнопкою Escape.
/**
* Xcode projects (#6787): sourcekit-lsp reads an `.xcodeproj` / `.xcworkspace` only through a
* Build Server Protocol config (`buildServer.json`, `.bsp/`). A trusted project root with an Xcode
* project and no config gets one, without asking, from xcode-build-server or sourcekit-xcode-bsp,
* whichever is on PATH; the backend keeps it out of Git (`.git/info/exclude`) and restarts
* sourcekit-lsp. A config that exists is never replaced. With neither tool installed it says,
* once per root, how to install one: the IDE does not install them itself.
*
* xcode-build-server reads compiler arguments from the project's last build, so until then
* cross-file code insight doesn't work. Unless Settings › Build › Compiler turns it off, the
* backend builds what Run builds in the background (`xcodeIndexBuild`) when there is no build yet.
*/
import { registerActions } from "@/platform/actions";
import { tx } from "@/platform/i18n";
import { call, commands, isTauri } from "@/platform/ipc";
import { useProject } from "@/platform/project";
import { workflowSettings } from "@/platform/workflowSettings";
import { notifications } from "@/workbench/contributions";
// v2: v1 remembered every root it offered to generate for, which would now skip generating.
const STORE_KEY = "openidea.xcodeBsp.v2";
const hintKey = (root: string) => `xcode-bsp:${root}`;
function hinted(): string[] {
try {
const value: unknown = JSON.parse(globalThis.localStorage?.getItem(STORE_KEY) ?? "[]");
return Array.isArray(value) ? value.filter((v): v is string => typeof v === "string") : [];
} catch {
return [];
}
}
function rememberHint(root: string) {
try {
globalThis.localStorage?.setItem(STORE_KEY, JSON.stringify([...hinted(), root]));
} catch {
// Storage unavailable: the hint may come back in a later session.
}
}
/**
* What opening `project` does about its build server config: `generate` it with the tool on
* PATH, `hint` how to install one, or nothing. Untrusted projects run no tool; after a failed
* generation or a hint, the root is remembered so neither repeats on every open, unless `again`.
*/
export function bspStep(
trusted: boolean,
setup: { tool: string | null } | null,
remembered: boolean,
again: boolean,
): "generate" | "hint" | null {
if (!trusted || !setup || (remembered && !again)) return null;
return setup.tool ? "generate" : "hint";
}
/** Builds the open project once in the background when its build server has no build to read. */
async function indexBuild(root: string) {
if (!workflowSettings().build.xcodeIndexBuild) return;
let result;
try {
result = await call(commands.xcodeIndexBuild());
} catch (e) {
result = { kind: "failed" as const, message: e instanceof Error ? e.message : String(e) };
}
if (result.kind !== "failed" || useProject.getState().project?.root !== root) return;
notifications().notify({
group: "tools",
level: "warning",
key: hintKey(root),
title: "Background build for code insight failed",
body: `${tx("Code insight reads what it built. Run shows the whole build log.")}\n\n${result.message}`,
});
}
async function generate(root: string, tool: string, container: string) {
const key = hintKey(root);
try {
await call(commands.xcodeBspGenerate(tool, container));
notifications().notify({
group: "tools",
level: "info",
key,
title: "Build server config generated",
body: workflowSettings().build.xcodeIndexBuild
? tx`Code insight for ${container} reads its last build. Without one yet, it is built in the background.`
: tx`Code insight for ${container} reads its last build: Run, or a build in Xcode, refreshes it.`,
});
await indexBuild(root);
} catch (e) {
rememberHint(root);
notifications().notify({
group: "tools",
level: "error",
key,
title: "Could not generate a build server config",
body: e instanceof Error ? e.message : String(e),
actions: [{ label: "Try Again", run: () => void generate(root, tool, container) }],
});
}
}
/** Generates the open project's config, or says how to install a generator ([`bspStep`]). */
export async function checkXcodeBsp(again = false) {
const project = useProject.getState().project;
if (!project?.trusted || !isTauri()) return;
const setup = await call(commands.xcodeBspSetup());
if (useProject.getState().project?.root !== project.root) return;
// Configured already (or no Xcode project: the backend does nothing then).
if (!setup) return indexBuild(project.root);
const step = bspStep(project.trusted, setup, hinted().includes(project.root), again);
if (!step) return;
const { container, tool } = setup;
if (step === "generate" && tool) return generate(project.root, tool, container);
rememberHint(project.root);
notifications().notify({
group: "tools",
level: "info",
key: hintKey(project.root),
title: "Xcode project needs a build server config",
body: tx`Cross-file code insight for ${container} needs a Build Server Protocol config. Install xcode-build-server (brew install xcode-build-server) to generate one.`,
actions: [{ label: "Check Again", run: () => void checkXcodeBsp(true).catch(() => {}) }],
});
}
export function installXcodeBspHint(): () => void {
void checkXcodeBsp().catch(() => {});
const actions = registerActions([
{
// Shows the hint again, e.g. after `pod install` added a workspace (run/cocoapodsActions.ts).
id: "xcode.bsp.check",
title: "Check Xcode Build Server Config",
hidden: true,
run: () => checkXcodeBsp(true),
},
]);
const off = useProject.subscribe((s, prev) => {
if (s.project?.root !== prev.project?.root || s.project?.trusted !== prev.project?.trusted)
void checkXcodeBsp().catch(() => {});
});
return () => {
off();
actions();
};
}