feat(cmake): Reload CMake Project and Reset Cache and Reload (#7537)

Adds Reload CMake Project, which configures the active profile again and refreshes its targets and compile_commands.json, and Reset Cache and Reload CMake Project, which first deletes the build directory's CMakeCache.txt and CMakeFiles through the new cmake_reset_cache command and keeps the build type the cache held. A failed delete is reported and nothing is configured. Both are in a Build > CMake submenu shown while the project has CMake configurations, in Find Action and in the title-bar CMake profile switcher; the configure output shows in the Run window.

Co-authored-by: yohannlog <[email protected]>
Цей коміт міститься в:
Yohann CATHERINEтаyohannlog authored and GitHub committed 2026-12-02 22:05:29 +08:00
1 джерело a2bf7fb0c4
коміт 0303a513cd
17 files changed
+288 -2

No files matched your search

+7
Переглянути файл
@@ -178,6 +178,11 @@ pub const FLUTTER_BUILD_MENU: &str = "build.flutter";
pub const DYNAMIC_XCODE_BUILD: &str = "xcodeBuild";
/// Id (and `menu.` label key) of the Build › Xcode submenu.
pub const XCODE_BUILD_MENU: &str = "build.xcode";
/// Build › CMake: Reload CMake Project, Reset Cache and Reload, CMake Settings, filled only when
/// the project has CMake configurations. A submenu after Build › Xcode when it has items.
pub const DYNAMIC_CMAKE_BUILD: &str = "cmakeBuild";
/// Id (and `menu.` label key) of the Build › CMake submenu.
pub const CMAKE_BUILD_MENU: &str = "build.cmake";
/// The submenu (id, English label) a dynamic slot is shown as when it has items, followed by a
/// separator; `None`: its items are listed in place.
@@ -185,6 +190,7 @@ pub fn dynamic_submenu(slot: &str) -> Option<(&'static str, &'static str)> {
match slot {
DYNAMIC_FLUTTER_BUILD => Some((FLUTTER_BUILD_MENU, "Flutter")),
DYNAMIC_XCODE_BUILD => Some((XCODE_BUILD_MENU, "Xcode")),
DYNAMIC_CMAKE_BUILD => Some((CMAKE_BUILD_MENU, "CMake")),
_ => None,
}
}
@@ -655,6 +661,7 @@ pub fn spec(os: Os) -> Vec<Entry> {
vec![
Entry::Dynamic(DYNAMIC_FLUTTER_BUILD),
Entry::Dynamic(DYNAMIC_XCODE_BUILD),
Entry::Dynamic(DYNAMIC_CMAKE_BUILD),
act("build.buildProject", "Build Project"),
act("build.buildModule", "Build Module"),
act("build.compileFile", "Recompile"),
+49
Переглянути файл
@@ -238,6 +238,32 @@ pub async fn cmake_cache(
.await
}
/// Build › CMake › Reset Cache and Reload: deletes `CMakeCache.txt` and `CMakeFiles` of `build_dir`
/// (relative to the project, or absolute) for good — they are build output, so neither the Trash
/// nor Local History keeps them — and returns the build type the cache held (empty when none), for
/// the configure that follows to keep it. Nothing else in the directory is touched.
#[command(trust = trusted)]
pub async fn cmake_reset_cache(host: &Host, window: &str, build_dir: String) -> IdeResult<String> {
let root = host.project(window)?.root.clone();
blocking(move || reset_cmake_cache(&root.join(build_dir.trim()))).await
}
fn reset_cmake_cache(build: &std::path::Path) -> IdeResult<String> {
let cache = build.join("CMakeCache.txt");
let build_type = std::fs::read_to_string(&cache)
.ok()
.and_then(|text| ide_run::cmake_cache::parse(&text).into_iter().find(|e| e.name == "CMAKE_BUILD_TYPE"))
.map(|e| e.value)
.unwrap_or_default();
let gone = |r: std::io::Result<()>| match r {
Err(e) if e.kind() != std::io::ErrorKind::NotFound => Err(ide_core::IdeError::from(e)),
_ => Ok(()),
};
gone(std::fs::remove_file(&cache))?;
gone(std::fs::remove_dir_all(build.join("CMakeFiles")))?;
Ok(build_type)
}
/// One tool of a toolchain as Settings › Toolchains shows it: the executable used (chosen, from the
/// MinGW directory, else found on `PATH`) and its version, or why it cannot be used.
#[derive(Clone, Debug, Default, serde::Serialize, specta::Type)]
@@ -1871,6 +1897,7 @@ ide_command::domain!(
build_sync,
cmake_cache,
cmake_profiles,
cmake_reset_cache,
gradle_dependencies,
gradle_link_projects,
gradle_published_catalog,
@@ -1883,3 +1910,25 @@ ide_command::domain!(
toolchain_check,
toolchains_detect,
);
#[cfg(test)]
mod cmake_reset_tests {
use super::reset_cmake_cache;
#[test]
fn resetting_deletes_the_cache_and_returns_its_build_type() {
let dir = tempfile::tempdir().unwrap();
let build = dir.path();
std::fs::write(build.join("CMakeCache.txt"), "CMAKE_BUILD_TYPE:STRING=Release\nFOO:BOOL=ON\n").unwrap();
std::fs::create_dir_all(build.join("CMakeFiles/app.dir")).unwrap();
std::fs::write(build.join("CMakeFiles/app.dir/main.o"), b"o").unwrap();
std::fs::write(build.join("app"), b"bin").unwrap();
assert_eq!(reset_cmake_cache(build).unwrap(), "Release");
assert!(!build.join("CMakeCache.txt").exists());
assert!(!build.join("CMakeFiles").exists());
assert!(build.join("app").exists(), "other build output stays");
// Nothing left to delete: not an error, and no build type.
assert_eq!(reset_cmake_cache(build).unwrap(), "");
assert_eq!(reset_cmake_cache(&build.join("never-configured")).unwrap(), "");
}
}
+2
Переглянути файл
@@ -84,6 +84,8 @@ The targets come from CMake's File API, so they appear after the first configure
Without saved profiles or enabled presets, the IDE uses every subdirectory of the project that contains a `CMakeCache.txt`, or `build/` when there is none.
**Reload CMake Project** (in **Build › CMake**, Find Action and the CMake profile switcher in the title bar) configures the active profile again, which refreshes its targets and `compile_commands.json`. **Reset Cache and Reload CMake Project** first deletes the build directory's `CMakeCache.txt` and `CMakeFiles`. The configure output shows in the Run window.
#### CMake profiles
To control the build directories yourself, add profiles in **Settings › Build, Execution, Deployment › CMake**, laid out as in CLion: one list holds the saved profiles and the presets, with **Add**, **Remove**, **Copy** (<kbd>Ctrl+D</kbd>), **Move Up** and **Move Down**. Each profile has:
+2
Переглянути файл
@@ -84,6 +84,8 @@ Xcode 和 Command Line Tools 自带的 `clangd` 不运行 clang-tidy。如果项
没有已保存的配置也没有启用的预设时,IDE 使用项目中所有含 `CMakeCache.txt` 的子目录;一个都没有时使用 `build/`。
**重新加载 CMake 项目**(在 **构建 › CMake**、“查找操作”和标题栏的 CMake 配置切换器中)会重新配置当前配置,刷新其目标和 `compile_commands.json`。**重置缓存并重新加载 CMake 项目** 会先删除构建目录中的 `CMakeCache.txt` 和 `CMakeFiles`。配置输出显示在运行窗口中。
#### CMake 配置
要自己控制构建目录,可在 **设置 › 构建、执行、部署 › CMake** 中添加配置。页面布局与 CLion 相同:同一个列表包含已保存的配置和预设,提供 **添加**、**移除**、**复制**(<kbd>Ctrl+D</kbd>)、**上移**、**下移**。每个配置包含:
+1
Переглянути файл
@@ -1403,6 +1403,7 @@ mod tests {
DYNAMIC_STATUS_BAR_WIDGETS,
DYNAMIC_FLUTTER_BUILD,
DYNAMIC_XCODE_BUILD,
DYNAMIC_CMAKE_BUILD,
DYNAMIC_PLUGIN_TOOLS,
DYNAMIC_LAYOUTS
],
+1
Переглянути файл
@@ -142,6 +142,7 @@ clipboard_write_text always desktop bin
close_project always project_host bindings spawn
cmake_cache always project_host bindings async
cmake_profiles always project_host bindings async
cmake_reset_cache trusted project_host bindings async
coverage_collect trusted project_host bindings async
coverage_import always project_host bindings async
coverage_prepare trusted project_host bindings async
+7
Переглянути файл
@@ -440,6 +440,13 @@ export const commands = {
cmakeCache: (buildDir: string) => typedError<CacheEntry[], IdeError>(__TAURI_INVOKE("cmake_cache", { buildDir })),
/** Reading the profiles runs nothing, so an untrusted project lists them too. */
cmakeProfiles: () => typedError<CMakeProfileList_Serialize, IdeError>(__TAURI_INVOKE("cmake_profiles")),
/**
* Build › CMake › Reset Cache and Reload: deletes `CMakeCache.txt` and `CMakeFiles` of `build_dir`
* (relative to the project, or absolute) for good — they are build output, so neither the Trash
* nor Local History keeps them — and returns the build type the cache held (empty when none), for
* the configure that follows to keep it. Nothing else in the directory is touched.
*/
cmakeResetCache: (buildDir: string) => typedError<string, IdeError>(__TAURI_INVOKE("cmake_reset_cache", { buildDir })),
/** Reads the report a coverage run left behind. */
coverageCollect: (report: CoverageReportSpec) => typedError<CoverageSuite, IdeError>(__TAURI_INVOKE("coverage_collect", { report })),
/**
+2
Переглянути файл
@@ -70,6 +70,8 @@ function Chooser({ active }: { active: string }) {
...(profiles === null ? [{ label: tx("Loading…"), disabled: true }] : []),
...(problem ? [{ label: problem, verbatim: true, disabled: true }] : []),
{ kind: "separator" },
{ kind: "action", action: "run.cmakeReload" },
{ kind: "action", action: "run.cmakeResetCache" },
{ kind: "action", action: "run.cmakeSettings" },
];
return (
+65 -1
Переглянути файл
@@ -4,7 +4,14 @@ import { setContext } from "@/platform/context";
import type { RunConfig } from "@/platform/ipc";
import { provideNotificationService } from "@/workbench/contributions";
import { validateConfig } from "./configs";
import { cmakeBuildId, isCMakeBuild, NEEDS_CONFIGURE, reloadCMakeProjects } from "./cmake";
import {
cmakeBuildId,
cmakeConfigureConfigs,
isCMakeBuild,
NEEDS_CONFIGURE,
reloadCMakeProject,
reloadCMakeProjects,
} from "./cmake";
import { runBeforeLaunch, taskLabel } from "./beforeLaunch";
import { resetRuns, startRun, useRun } from "./store";
@@ -120,3 +127,60 @@ it("configures once the build directories CMake never described, as CLion reload
reloadCMakeProjects("/reload", [{ ...stale, args: ["--preset", "release"] }], start);
expect(start).toHaveBeenCalledTimes(2);
});
it("reloads the active profile's CMake projects, resetting their cache first on reset", async () => {
const withDir = (c: RunConfig, buildDir: string, cwd: string | null = null): RunConfig => ({
...c,
cwd,
params: { buildDir },
});
const app = withDir(configure, "cmake-build-debug");
const lib = withDir({ ...configure, id: "cmake:lib:configure" }, "out/build", "C:/work/lib");
const preset = withDir({ ...configure, id: "cmake:preset:configure", args: ["--preset", "dev"] }, "/abs/build/");
const configs = [app, lib, preset, build, config("other", "cargo")];
const started: RunConfig[] = [];
const reset: string[] = [];
const cached: Record<string, string> = { "C:/work/app/cmake-build-debug": "Release" };
const run = (resetCache: boolean, list = configs) =>
reloadCMakeProject(
"C:/work/app",
list,
async (c) => started.push(c),
async (dir) => {
reset.push(dir);
return cached[dir] ?? "";
},
resetCache,
);
expect(await run(false)).toBe(3);
expect(started.map((c) => c.id)).toEqual([app.id, lib.id, preset.id]);
expect(started[0]!.args).toEqual(app.args);
expect(reset).toEqual([]);
started.length = 0;
await run(true);
expect(reset).toEqual(["C:/work/app/cmake-build-debug", "C:/work/lib/out/build", "/abs/build"]);
// The build type the cache held comes back; Debug when it held none; a preset sets its own.
expect(started.map((c) => c.args.at(-1))).toEqual(["-DCMAKE_BUILD_TYPE=Release", "-DCMAKE_BUILD_TYPE=Debug", "dev"]);
// Arguments that already set it (either spelling) are kept as they are.
started.length = 0;
const typed = { ...app, args: [...app.args, "-D", "CMAKE_BUILD_TYPE=MinSizeRel"] };
await run(true, [typed]);
expect(started[0]!.args).toEqual(typed.args);
// A failed reset (a locked cache) configures nothing and reaches the caller.
started.length = 0;
await expect(
reloadCMakeProject(
"/p",
[app],
async (c) => started.push(c),
async () => Promise.reject(new Error("locked")),
true,
),
).rejects.toThrow("locked");
expect(started).toEqual([]);
expect(cmakeConfigureConfigs([build, config("x", "cmake", ["-S", "."])])).toEqual([]);
});
+52
Переглянути файл
@@ -49,3 +49,55 @@ export function reloadCMakeProjects(
void start(config).catch(() => {});
}
}
/** The configure configurations of the active profile (one per CMake project of the window). */
export function cmakeConfigureConfigs(configs: readonly RunConfig[]): RunConfig[] {
return configs.filter(
(c) => c.kind === "cmake" && ["-S", "--preset"].includes(c.args[0] ?? "") && c.params?.buildDir,
);
}
/** The build directory of a configure configuration, absolute (`buildDir` may be relative to its `cwd`). */
export function cmakeBuildDirectory(config: RunConfig, root: string): string {
const dir = config.params!.buildDir!.replace(/\\/g, "/");
if (/^([A-Za-z]:\/|\/)/.test(dir)) return dir.replace(/\/+$/, "");
const base = (config.cwd || root).replace(/\\/g, "/").replace(/\/+$/, "");
return `${base}/${dir.replace(/^\.\//, "")}`.replace(/\/+$/, "");
}
/** Whether configure arguments set the build type (`-DCMAKE_BUILD_TYPE=…` or `-D CMAKE_BUILD_TYPE=…`). */
const setsBuildType = (args: readonly string[]) =>
args.some(
(a, i) => a.startsWith("-DCMAKE_BUILD_TYPE") || (a === "-D" && args[i + 1]?.startsWith("CMAKE_BUILD_TYPE")),
);
/**
* Reload CMake Project: configure the active profile again, which refreshes the targets and
* `compile_commands.json`. With `resetCache` (Reset Cache and Reload Project), `reset` first deletes
* the build directory's `CMakeCache.txt` and `CMakeFiles` and answers the build type the cache
* held: a directory detected with a cache has none in its arguments, so the configure gets that one
* back (Debug when there was none, as on a first configure). Returns how many CMake projects were
* configured; a failed reset rejects, before anything is configured.
*/
export async function reloadCMakeProject(
root: string,
configs: readonly RunConfig[],
start: (config: RunConfig) => Promise<unknown>,
reset: (buildDir: string) => Promise<string>,
resetCache = false,
): Promise<number> {
const configures = cmakeConfigureConfigs(configs);
const ready = resetCache
? await Promise.all(
configures.map(async (config) => {
const buildType = await reset(cmakeBuildDirectory(config, root));
return config.args[0] === "-S" && !setsBuildType(config.args)
? { ...config, args: [...config.args, `-DCMAKE_BUILD_TYPE=${buildType || "Debug"}`] }
: config;
}),
)
: configures;
// Each project has its own build directory: they reload side by side.
await Promise.all(ready.map((config) => start(config)));
return configures.length;
}
+78 -1
Переглянути файл
@@ -20,6 +20,7 @@ import {
provideRunConfigurationLookup,
provideRunOutput,
registerMenuGroup,
registerMenuSlotItem,
registerOverlay,
registerRunAnythingProvider,
registerRunConfigType,
@@ -89,7 +90,7 @@ import {
import { hotReload, hotReloadSession, hotRestart, syncFlutterRunApps } from "./flutterHotReload";
import { registerFlutterBuildActions } from "./flutterBuild";
import { selectCMakeProfile, toggleCMakeProfiles } from "./CMakeProfileChooser";
import { reloadCMakeProjects } from "./cmake";
import { cmakeConfigureConfigs, reloadCMakeProject, reloadCMakeProjects } from "./cmake";
import { registerXcodeCleanActions } from "./xcodeClean";
import { npmGutter } from "./npmGutter";
import { launchSettingsGutter } from "./launchSettingsGutter";
@@ -329,6 +330,66 @@ async function flutterAttachSelected() {
await executeAction("debug.startConfig", { ...config, params: { ...config.params, request: "attach" } });
}
/** The native Build menu's CMake submenu (`ide_host::menu::DYNAMIC_CMAKE_BUILD`). */
const CMAKE_BUILD_SLOT = "cmakeBuild";
/**
* Lists Reload CMake Project, Reset Cache and Reload and CMake Settings in Build › CMake while the
* project has CMake configure configurations: the title-bar switcher only shows with a profile.
*/
function syncCMakeBuildMenu(): () => void {
let inMenu: (() => void)[] = [];
const sync = () => {
const cmake = cmakeConfigureConfigs(useRun.getState().configs).length > 0;
if (cmake === inMenu.length > 0) return;
inMenu.forEach((d) => d());
inMenu = cmake
? [
registerMenuSlotItem(CMAKE_BUILD_SLOT, { action: "run.cmakeReload", label: "Reload CMake Project" }),
registerMenuSlotItem(CMAKE_BUILD_SLOT, {
action: "run.cmakeResetCache",
label: "Reset Cache and Reload CMake Project",
}),
registerMenuSlotItem(CMAKE_BUILD_SLOT, { action: "run.cmakeSettings", label: "CMake Settings…" }),
]
: [];
};
sync();
const off = useRun.subscribe((s, old) => {
if (s.configs !== old.configs) sync();
});
return () => {
off();
inMenu.forEach((d) => d());
};
}
/** Reload CMake Project / Reset Cache and Reload: configure the active profile again, in the Run window. */
async function reloadCMake(resetCache: boolean) {
const root = useProject.getState().project?.root;
if (!root) return;
await ensureConfigs();
try {
const count = await reloadCMakeProject(
root,
useRun.getState().configs,
(config) => startRun(config),
(buildDir) => call(commands.cmakeResetCache(buildDir)),
resetCache,
);
if (!count)
notifications().notify({
group: "run",
level: "info",
title: "No CMake project",
body: "This project has no CMakeLists.txt to configure, or its CMake profiles are all disabled.",
key: "cmake-reload",
});
} catch (e) {
notifications().notify({ level: "error", title: "Cannot reload the CMake project", body: String(e) });
}
}
function nothingToRun() {
notifications().notify({
group: "run",
@@ -494,6 +555,7 @@ export function activate(): () => void {
registerSwiftPackageActions(),
registerFlutterBuildActions(),
registerXcodeCleanActions(),
syncCMakeBuildMenu(),
registerCocoaPodsActions(),
registerRunTabActions(),
registerComposerInstall(),
@@ -675,6 +737,21 @@ export function activate(): () => void {
category: "Run",
run: () => void executeAction("file.settings", "build.cmake"),
},
{
id: "run.cmakeReload",
title: "Reload CMake Project",
category: "Build",
icon: "refresh",
keywords: ["cmake", "configure", "reload", "compile_commands"],
run: () => void reloadCMake(false),
},
{
id: "run.cmakeResetCache",
title: "Reset Cache and Reload CMake Project",
category: "Build",
keywords: ["cmake", "cache", "CMakeCache.txt", "clean", "reconfigure"],
run: () => void reloadCMake(true),
},
{
id: "run.flutterChooseDevice",
title: "Select Flutter Device…",
+1
Переглянути файл
@@ -452,6 +452,7 @@
"menu.build.buildArtifacts": "Build Artifacts",
"menu.build.flutter": "Flutter",
"menu.build.xcode": "Xcode",
"menu.build.cmake": "CMake",
"menu.toolwindow.build": "Build",
"menu.find.structural": "Search Structurally…",
"menu.find.replaceStructural": "Replace Structurally…",
+5
Переглянути файл
@@ -2582,6 +2582,11 @@
"Not Now": "Not Now",
"Introspect All Databases": "Introspect All Databases",
"Add Interpreter…": "Add Interpreter…",
"Reload CMake Project": "Reload CMake Project",
"Reset Cache and Reload CMake Project": "Reset Cache and Reload CMake Project",
"No CMake project": "No CMake project",
"This project has no CMakeLists.txt to configure, or its CMake profiles are all disabled.": "This project has no CMakeLists.txt to configure, or its CMake profiles are all disabled.",
"Cannot reload the CMake project": "Cannot reload the CMake project",
"Interpreters": "Interpreters",
"Remove Interpreter": "Remove Interpreter",
"Refresh Interpreters": "Refresh Interpreters",
+5
Переглянути файл
@@ -2981,6 +2981,11 @@
"Run a Java main class": "Exécuter une classe principale Java",
"Run a Spring Boot application": "Exécuter une application Spring Boot",
"Passed to the JVM that spring-boot:run or the tests start, not to Maven": "Passé à la JVM démarrée par spring-boot:run ou les tests, pas à Maven",
"Reload CMake Project": "Recharger le projet CMake",
"Reset Cache and Reload CMake Project": "Vider le cache et recharger le projet CMake",
"No CMake project": "Aucun projet CMake",
"This project has no CMakeLists.txt to configure, or its CMake profiles are all disabled.": "Ce projet n’a pas de CMakeLists.txt à configurer, ou tous ses profils CMake sont désactivés.",
"Cannot reload the CMake project": "Impossible de recharger le projet CMake",
"Passed to the JVMs the tasks start (bootRun, run, test), not to Gradle": "Passé aux JVM démarrées par les tâches (bootRun, run, test), pas à Gradle",
"Run a package.json script": "Exécuter un script package.json",
"package.json directory": "Répertoire de package.json",
+5
Переглянути файл
@@ -4867,6 +4867,11 @@
"Godot command line options, e.g. --debug-collisions": "Godot 命令列選項,例如 --debug-collisions",
"Bookmark description": "書籤描述",
"Cannot open {path}": "無法開啟 {path}",
"Reload CMake Project": "重新載入 CMake 專案",
"Reset Cache and Reload CMake Project": "重設快取並重新載入 CMake 專案",
"No CMake project": "沒有 CMake 專案",
"This project has no CMakeLists.txt to configure, or its CMake profiles are all disabled.": "此專案沒有可設定的 CMakeLists.txt,或其 CMake 設定檔皆已停用。",
"Cannot reload the CMake project": "無法重新載入 CMake 專案",
"Search context": "搜尋上下文",
"not": "非",
"and": "與",
+5
Переглянути файл
@@ -6034,6 +6034,11 @@
"Remove {shortcut}": "移除 {shortcut}",
"Keyboard Shortcut": "键盘快捷键",
"Mouse Shortcut": "鼠标快捷键",
"Reload CMake Project": "重新加载 CMake 项目",
"Reset Cache and Reload CMake Project": "重置缓存并重新加载 CMake 项目",
"No CMake project": "没有 CMake 项目",
"This project has no CMakeLists.txt to configure, or its CMake profiles are all disabled.": "此项目没有可配置的 CMakeLists.txt,或其 CMake 配置文件均已禁用。",
"Cannot reload the CMake project": "无法重新加载 CMake 项目",
"Keyboard Shortcut: {action}": "键盘快捷键:{action}",
"Remove content root {path}": "移除内容根 {path}",
"Unmark {folder}": "取消标记 {folder}",
+1
Переглянути файл
@@ -452,6 +452,7 @@
"menu.build.buildArtifacts": "构建工件",
"menu.build.flutter": "Flutter",
"menu.build.xcode": "Xcode",
"menu.build.cmake": "CMake",
"menu.toolwindow.build": "构建",
"menu.find.structural": "结构化搜索…",
"menu.find.replaceStructural": "结构化替换…",