From b4d2859277b2e6479bc5bfcb48ec75b115ffa19c Mon Sep 17 00:00:00 2001 From: HandsomeXi <42278397+HandsomeXi@users.noreply.github.com> Date: Sat, 28 Nov 2026 14:36:10 +0800 Subject: [PATCH] fix(build): give cmake --build one job per logical CPU (#6629) Build Project, Build , Rebuild and the generated CMake Build run configurations ran `cmake --build` without a job count, so the default Makefile generator compiled one file at a time. Every cmake build step now gets `-j ` before a `--` separator; a count the profile's build arguments already set (-j, -jN, --parallel, --jobs) is left alone. CTest steps are unchanged. Co-authored-by: HandsomeXi <42278397+HandsomeXi@users.noreply.github.com> --- crates/ide-build/src/compile/mod.rs | 12 +++-- crates/ide-core/src/build_jobs.rs | 74 +++++++++++++++++++++++++++++ crates/ide-core/src/lib.rs | 1 + crates/ide-run/src/detect/cmake.rs | 4 ++ crates/ide-run/tests/detect.rs | 20 ++++++++ 5 files changed, 107 insertions(+), 4 deletions(-) create mode 100644 crates/ide-core/src/build_jobs.rs diff --git a/crates/ide-build/src/compile/mod.rs b/crates/ide-build/src/compile/mod.rs index e67f9080e..a9a4af49c 100644 --- a/crates/ide-build/src/compile/mod.rs +++ b/crates/ide-build/src/compile/mod.rs @@ -29,6 +29,7 @@ pub use up_to_date::{menu_up_to_date, record_menu_build}; use crate::process::{self, Stream}; use crate::{BuildModel, maven}; +use ide_core::build_jobs::append_default_jobs; use ide_core::settings::CMakeProfile; use ide_core::{CancellationToken, Diagnostic, IdeError, IdeResult, Pos, Range, Severity}; use parse::{ColUnit, Format, OutputParser, RawMessage}; @@ -420,7 +421,8 @@ fn cargo_steps(dir: &Path, kind: BuildKind) -> Vec { } /// CLion's Build Project for a CMake project: configures the build directory when it has no -/// `CMakeCache.txt` yet, then `cmake --build` (`--clean-first` to rebuild). The directory and +/// `CMakeCache.txt` yet, then `cmake --build` (`--clean-first` to rebuild), one job per +/// logical CPU unless the profile's build arguments choose a count. The directory and /// options come from the CMake profile; without one, a configured directory of the project /// (the first by name), else `build`, as the generated run configurations use. fn cmake_steps(dir: &Path, kind: BuildKind, profile: Option<&CMakeProfile>) -> Vec { @@ -458,6 +460,7 @@ fn cmake_steps(dir: &Path, kind: BuildKind, profile: Option<&CMakeProfile>) -> V build.args.push("--clean-first".into()); } build.args.extend(profile.map(|p| p.build_args.clone()).unwrap_or_default()); + append_default_jobs(&mut build.args); build.env = env; steps.push(build); steps @@ -1508,14 +1511,15 @@ mod tests { let cm = tmp.path().join("cm"); write(&cm, "CMakeLists.txt", "project(app)"); let args = |p: &BuildPlan| p.steps.iter().map(|s| s.args.join(" ")).collect::>(); + let jobs = format!("-j {}", ide_core::build_jobs::default_jobs()); let p = plan(&cm, &BuildModel::default(), BuildKind::Build, None, None, None, &CancellationToken::new()).unwrap(); assert_eq!(p.system, BuildSystem::CMake); assert_eq!( args(&p), [ - "-S . -B build -DCMAKE_BUILD_TYPE=Debug -DCMAKE_EXPORT_COMPILE_COMMANDS=ON", - "--build build --config Debug" + "-S . -B build -DCMAKE_BUILD_TYPE=Debug -DCMAKE_EXPORT_COMPILE_COMMANDS=ON".to_owned(), + format!("--build build --config Debug {jobs}"), ], "an unconfigured project is configured first" ); @@ -1524,7 +1528,7 @@ mod tests { plan(&cm, &BuildModel::default(), BuildKind::Rebuild, None, None, None, &CancellationToken::new()).unwrap(); assert_eq!( args(&p), - ["--build cmake-build-release --config Debug --clean-first"], + [format!("--build cmake-build-release --config Debug --clean-first {jobs}")], "a configured directory is reused" ); let profile = CMakeProfile { diff --git a/crates/ide-core/src/build_jobs.rs b/crates/ide-core/src/build_jobs.rs new file mode 100644 index 000000000..91e4ca136 --- /dev/null +++ b/crates/ide-core/src/build_jobs.rs @@ -0,0 +1,74 @@ +//! Parallelism for build tools whose default is one compiler process at a time. +//! +//! `cmake --build` with a Makefile generator (the default) compiles one file at a +//! time unless it is given `-j N`; the IDE asks for one job per logical CPU. A count +//! the user wrote into the build arguments is left alone. + +/// Jobs a native build tool gets when the user did not choose a count. +pub fn default_jobs() -> usize { + std::thread::available_parallelism().map_or(1, |jobs| jobs.get()) +} + +/// Appends `-j ` unless `args` already carries the user's own count. The count +/// goes before a `--` separator, so cmake's own options stay cmake's and the native +/// build tool's options stay last. +pub fn append_default_jobs(args: &mut Vec) { + if args.iter().any(|arg| is_jobs_flag(arg)) { + return; + } + let jobs = default_jobs().to_string(); + let at = args.iter().position(|arg| arg == "--").unwrap_or(args.len()); + args.splice(at..at, ["-j".to_owned(), jobs]); +} + +/// `-j`, `-j8`, `--parallel`, `--parallel=8`, `--jobs`, `--jobs=8`. +fn is_jobs_flag(arg: &str) -> bool { + let count = |rest: &str| rest.chars().all(|c| c.is_ascii_digit()); + arg.strip_prefix("-j").is_some_and(count) + || arg.strip_prefix("--parallel=").is_some_and(count) + || arg.strip_prefix("--jobs=").is_some_and(count) + || arg == "--parallel" + || arg == "--jobs" +} + +#[cfg(test)] +mod tests { + use super::*; + + fn args_of(values: &[&str]) -> Vec { + values.iter().map(|value| (*value).to_owned()).collect() + } + + #[test] + fn the_default_is_one_job_per_logical_cpu() { + let expected = std::thread::available_parallelism().map_or(1, |jobs| jobs.get()); + assert_eq!(default_jobs(), expected); + } + + #[test] + fn a_build_without_a_count_gets_one() { + let mut argv = args_of(&["--build", "build", "--config", "Debug"]); + append_default_jobs(&mut argv); + assert_eq!(argv, args_of(&["--build", "build", "--config", "Debug", "-j", &default_jobs().to_string()])); + } + + #[test] + fn a_count_the_user_chose_is_left_alone() { + let own: [&[&str]; 6] = + [&["-j", "2"], &["-j8"], &["-j", "2"], &["--parallel", "2"], &["--parallel=2"], &["--jobs=2"]]; + for flags in own { + let mut argv = args_of(&["--build", "build"]); + argv.extend(flags.iter().map(|value| (*value).to_owned())); + let expected = argv.clone(); + append_default_jobs(&mut argv); + assert_eq!(argv, expected, "the build arguments set the count"); + } + } + + #[test] + fn the_count_stays_before_native_build_tool_options() { + let mut argv = args_of(&["--build", "build", "--", "VERBOSE=1"]); + append_default_jobs(&mut argv); + assert_eq!(argv, args_of(&["--build", "build", "-j", &default_jobs().to_string(), "--", "VERBOSE=1"])); + } +} diff --git a/crates/ide-core/src/lib.rs b/crates/ide-core/src/lib.rs index 3e4f843af..6649e236c 100644 --- a/crates/ide-core/src/lib.rs +++ b/crates/ide-core/src/lib.rs @@ -4,6 +4,7 @@ //! feature crates depend on `ide-core` and never on each other's internals. //! All IPC-facing types derive `specta::Type`, which generates `src/bindings.ts`. +pub mod build_jobs; pub mod cli_process; pub mod editor_settings; pub mod error; diff --git a/crates/ide-run/src/detect/cmake.rs b/crates/ide-run/src/detect/cmake.rs index 3892e51f0..c0aa4c404 100644 --- a/crates/ide-run/src/detect/cmake.rs +++ b/crates/ide-run/src/detect/cmake.rs @@ -2,6 +2,7 @@ use super::{ConfigExt, config}; use crate::{BeforeLaunchTask, RunConfig}; +use ide_core::build_jobs::append_default_jobs; use ide_core::settings::CMakeProfile; use serde_json::Value; use std::fs; @@ -108,6 +109,7 @@ fn detect_configs(root: &Path, profiles: Option<&[CMakeProfile]>, out: &mut Vec< names.push(out, configure, &dir, ""); let mut all = config(&build_id, "CMake Build", "cmake", "cmake", &["--build", &dir, "--config", &configuration]); + append_default_jobs(&mut all.args); // `cmake --build` regenerates by itself once a build directory is configured. if !build.join("CMakeCache.txt").is_file() { before(&mut all, &configure_id); @@ -149,6 +151,7 @@ fn detect_profile(root: &Path, profile: &CMakeProfile, index: usize, out: &mut V let mut all = config(&build_id, "CMake Build", "cmake", "cmake", &["--build", &dir, "--config", &profile.build_type]); all.args.extend_from_slice(&profile.build_args); + append_default_jobs(&mut all.args); if !build.join("CMakeCache.txt").is_file() { before(&mut all, &configure_id); } @@ -236,6 +239,7 @@ fn targets( before(&mut build_config, &format!("{prefix}:configure")); } } + append_default_jobs(&mut build_config.args); let label = profile.map_or(name, |p| p.name.as_str()); names.push(out, build_config, dir, label); let binary = build.join(artifact); diff --git a/crates/ide-run/tests/detect.rs b/crates/ide-run/tests/detect.rs index e46b623ef..1e9f1a586 100644 --- a/crates/ide-run/tests/detect.rs +++ b/crates/ide-run/tests/detect.rs @@ -1029,6 +1029,26 @@ fn cmake_configures_before_the_first_build() { assert_eq!(build.extras.before_launch[0].target, "cmake:build:configure"); } +#[test] +fn cmake_builds_ask_for_one_job_per_logical_cpu() { + let default = ide_core::build_jobs::default_jobs().to_string(); + let jobs = |args: &[String]| { + let tail = &args[args.len() - 2..]; + assert_eq!(tail[0], "-j", "{args:?}"); + tail[1].clone() + }; + let dir = project(&[("CMakeLists.txt", "project(demo)")]); + cmake_reply(dir.path(), "build", &[("Debug", &["hello"])]); + let configs = detect(dir.path()); + assert_eq!(jobs(&find(&configs, "cmake:build:build").args), default); + let target = find(&configs, "cmake:build:Debug:hello:build"); + assert_eq!(jobs(&target.args), default); + assert!( + !find(&configs, "cmake:build:test").args.iter().any(|arg| arg == "-j"), + "CTest runs the build itself; it is not a compiler build" + ); +} + #[test] fn cmake_ignores_malformed_file_api_replies() { let dir = project(&[