ccgo 3.8.0

A high-performance C++ cross-platform build CLI
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
//! CMake configuration and execution
//!
//! This module handles invoking CMake for configure, build, and install steps.

use std::path::PathBuf;
use std::process::{Command, Stdio};

use anyhow::{bail, Context, Result};

/// CMake build type
#[derive(Debug, Clone, Copy, Default)]
pub enum BuildType {
    Debug,
    #[default]
    Release,
    RelWithDebInfo,
    MinSizeRel,
}

impl std::fmt::Display for BuildType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            BuildType::Debug => write!(f, "Debug"),
            BuildType::Release => write!(f, "Release"),
            BuildType::RelWithDebInfo => write!(f, "RelWithDebInfo"),
            BuildType::MinSizeRel => write!(f, "MinSizeRel"),
        }
    }
}

/// CMake configuration builder
#[derive(Debug, Default)]
pub struct CMakeConfig {
    /// Source directory (where CMakeLists.txt is located)
    source_dir: PathBuf,
    /// Build directory
    build_dir: PathBuf,
    /// Install prefix
    install_prefix: Option<PathBuf>,
    /// Build type
    build_type: BuildType,
    /// CMake variables (-D options)
    variables: Vec<(String, String)>,
    /// CMake cache variables (-D with type)
    cache_variables: Vec<(String, String, String)>,
    /// Generator (e.g., "Ninja", "Unix Makefiles")
    generator: Option<String>,
    /// Toolchain file
    toolchain_file: Option<PathBuf>,
    /// Number of parallel jobs
    jobs: Option<usize>,
    /// Verbose output
    verbose: bool,
    /// Compile definitions to add
    compile_definitions: Vec<String>,
    /// Compiler cache configuration
    compiler_cache: Option<super::cache::CacheConfig>,
    /// User-specified raw cmake arguments (from [build.cmake] / [platforms.X.build.cmake])
    user_arguments: Vec<String>,
    /// User-specified extra C compiler flags
    user_c_flags: Vec<String>,
    /// User-specified extra C++ compiler flags
    user_cpp_flags: Vec<String>,
    /// Explicit cmake script files from [build].cmake_file / [platforms.X.build].cmake_file.
    /// None = auto-discover; Some(vec![]) = suppress; Some(paths) = include these files.
    user_cmake_files: Option<Vec<PathBuf>>,
}

impl CMakeConfig {
    /// Create a new CMake configuration
    pub fn new(source_dir: PathBuf, build_dir: PathBuf) -> Self {
        Self {
            source_dir,
            build_dir,
            build_type: BuildType::Release,
            ..Default::default()
        }
    }

    /// Set the build type
    pub fn build_type(mut self, build_type: BuildType) -> Self {
        self.build_type = build_type;
        self
    }

    /// Set the install prefix
    pub fn install_prefix(mut self, prefix: PathBuf) -> Self {
        self.install_prefix = Some(prefix);
        self
    }

    /// Set a CMake variable
    pub fn variable(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
        self.variables.push((name.into(), value.into()));
        self
    }

    /// Set multiple CMake variables
    pub fn variables(mut self, vars: Vec<(String, String)>) -> Self {
        self.variables.extend(vars);
        self
    }

    /// Set a cache variable with type
    pub fn cache_variable(
        mut self,
        name: impl Into<String>,
        value: impl Into<String>,
        var_type: impl Into<String>,
    ) -> Self {
        self.cache_variables
            .push((name.into(), value.into(), var_type.into()));
        self
    }

    /// Set the generator
    pub fn generator(mut self, generator: impl Into<String>) -> Self {
        self.generator = Some(generator.into());
        self
    }

    /// Set the toolchain file
    pub fn toolchain_file(mut self, path: PathBuf) -> Self {
        self.toolchain_file = Some(path);
        self
    }

    /// Set number of parallel jobs
    pub fn jobs(mut self, jobs: usize) -> Self {
        self.jobs = Some(jobs);
        self
    }

    /// Enable verbose output
    pub fn verbose(mut self, verbose: bool) -> Self {
        self.verbose = verbose;
        self
    }

    /// Add a compile definition
    pub fn compile_definition(mut self, definition: impl Into<String>) -> Self {
        self.compile_definitions.push(definition.into());
        self
    }

    /// Add multiple compile definitions
    pub fn compile_definitions(mut self, definitions: Vec<String>) -> Self {
        self.compile_definitions.extend(definitions);
        self
    }

    /// Add feature-based compile definitions from a semicolon-separated string
    ///
    /// This is used to pass feature flags from BuildContext to CMake.
    /// Example input: "CCGO_FEATURE_NETWORKING;CCGO_FEATURE_ADVANCED"
    pub fn feature_definitions(mut self, features_str: &str) -> Self {
        if !features_str.is_empty() {
            for def in features_str.split(';') {
                if !def.is_empty() {
                    self.compile_definitions.push(def.to_string());
                }
            }
        }
        self
    }

    /// Set compiler cache configuration (ccache, sccache)
    pub fn compiler_cache(mut self, cache: super::cache::CacheConfig) -> Self {
        self.compiler_cache = Some(cache);
        self
    }

    /// Append user-specified raw cmake arguments (from CCGO.toml `[build.cmake].arguments`).
    pub fn user_arguments(mut self, args: Vec<String>) -> Self {
        self.user_arguments.extend(args);
        self
    }

    /// Append user-specified C compiler flags (from CCGO.toml `[build.cmake].c_flags`).
    pub fn user_c_flags(mut self, flags: Vec<String>) -> Self {
        self.user_c_flags.extend(flags);
        self
    }

    /// Append user-specified C++ compiler flags (from CCGO.toml `[build.cmake].cpp_flags`).
    pub fn user_cpp_flags(mut self, flags: Vec<String>) -> Self {
        self.user_cpp_flags.extend(flags);
        self
    }

    /// Set explicit cmake file list from CCGO.toml `[build].cmake_file`.
    /// `None` = auto-discover; `Some(vec![])` = suppress; `Some(paths)` = use these files.
    pub fn user_cmake_files(mut self, files: Option<Vec<PathBuf>>) -> Self {
        self.user_cmake_files = files;
        self
    }

    /// Find CMake executable
    fn find_cmake() -> Result<PathBuf> {
        which::which("cmake").context("CMake not found. Please install CMake and add it to PATH.")
    }

    /// Run CMake configure step
    pub fn configure(&self) -> Result<()> {
        let cmake = Self::find_cmake()?;

        // Create build directory if it doesn't exist
        std::fs::create_dir_all(&self.build_dir)
            .context("Failed to create CMake build directory")?;

        let mut cmd = Command::new(&cmake);
        cmd.current_dir(&self.build_dir);

        // Source directory
        cmd.arg("-S").arg(&self.source_dir);
        cmd.arg("-B").arg(&self.build_dir);

        // Build type
        cmd.arg(format!("-DCMAKE_BUILD_TYPE={}", self.build_type));

        // Install prefix
        if let Some(prefix) = &self.install_prefix {
            cmd.arg(format!("-DCMAKE_INSTALL_PREFIX={}", prefix.display()));
        }

        // Generator
        if let Some(generator) = &self.generator {
            cmd.arg("-G").arg(generator);
        }

        // Toolchain file
        if let Some(toolchain) = &self.toolchain_file {
            cmd.arg(format!("-DCMAKE_TOOLCHAIN_FILE={}", toolchain.display()));
        }

        // Variables
        for (name, value) in &self.variables {
            cmd.arg(format!("-D{}={}", name, value));
        }

        // Cache variables with type
        for (name, value, var_type) in &self.cache_variables {
            cmd.arg(format!("-D{}:{}={}", name, var_type, value));
        }

        // Compiler cache (ccache/sccache)
        if let Some(cache) = &self.compiler_cache {
            if cache.is_enabled() {
                // Print cache info
                println!(
                    "   🚀 Using {} for compilation caching",
                    cache.cache_type().name()
                );

                // Add CMake compiler launcher variables
                for (name, value) in cache.cmake_variables() {
                    cmd.arg(format!("-D{}={}", name, value));
                }
            }
        }

        // Add compile definitions (for features)
        if !self.compile_definitions.is_empty() {
            // Pass as CCGO_FEATURE_DEFINITIONS which CMake can use
            let definitions = self.compile_definitions.join(";");
            cmd.arg(format!("-DCCGO_FEATURE_DEFINITIONS={}", definitions));
        }

        // User-specified flags from [build.cmake] / [platforms.X.build.cmake].
        // Emitted last so they can override earlier -D settings.
        //
        // Print a visible summary so the user can confirm their CCGO.toml
        // cmake settings were picked up.
        if !self.user_arguments.is_empty()
            || !self.user_c_flags.is_empty()
            || !self.user_cpp_flags.is_empty()
            || self.user_cmake_files.is_some()
        {
            println!("   📋 Custom CMake settings from CCGO.toml:");
            if !self.user_arguments.is_empty() {
                println!("      arguments : [{}]", self.user_arguments.join(", "));
            }
            if !self.user_c_flags.is_empty() {
                println!("      c_flags   : [{}]", self.user_c_flags.join(", "));
            }
            if !self.user_cpp_flags.is_empty() {
                println!("      cpp_flags : [{}]", self.user_cpp_flags.join(", "));
            }
            if let Some(files) = &self.user_cmake_files {
                if files.is_empty() {
                    println!("      cmake_file: (suppressed)");
                } else {
                    for f in files {
                        println!("      cmake_file: {}", f.display());
                    }
                }
            }
        }
        for arg in &self.user_arguments {
            cmd.arg(arg);
        }
        if !self.user_c_flags.is_empty() {
            cmd.arg(format!(
                "-DCMAKE_C_FLAGS:STRING={}",
                self.user_c_flags.join(" ")
            ));
        }
        if !self.user_cpp_flags.is_empty() {
            cmd.arg(format!(
                "-DCMAKE_CXX_FLAGS:STRING={}",
                self.user_cpp_flags.join(" ")
            ));
        }
        if let Some(files) = &self.user_cmake_files {
            let list = files
                .iter()
                .map(|f| f.to_string_lossy().into_owned())
                .collect::<Vec<_>>()
                .join(";");
            cmd.arg(format!("-DCCGO_USER_CMAKE_FILES={}", list));
        }

        if self.verbose {
            eprintln!("Running: {:?}", cmd);
        }

        let status = cmd
            .stdin(Stdio::null())
            .status()
            .context("Failed to run CMake configure")?;

        if !status.success() {
            bail!("CMake configure failed with exit code: {:?}", status.code());
        }

        Ok(())
    }

    /// Run CMake build step
    pub fn build(&self) -> Result<()> {
        let cmake = Self::find_cmake()?;

        let mut cmd = Command::new(&cmake);
        cmd.arg("--build").arg(&self.build_dir);

        // Parallel jobs
        if let Some(jobs) = self.jobs {
            cmd.arg("-j").arg(jobs.to_string());
        } else {
            cmd.arg("-j");
        }

        // Verbose
        if self.verbose {
            cmd.arg("--verbose");
        }

        if self.verbose {
            eprintln!("Running: {:?}", cmd);
        }

        let status = cmd
            .stdin(Stdio::null())
            .status()
            .context("Failed to run CMake build")?;

        if !status.success() {
            bail!("CMake build failed with exit code: {:?}", status.code());
        }

        Ok(())
    }

    /// Run CMake install step
    pub fn install(&self) -> Result<()> {
        let cmake = Self::find_cmake()?;

        let mut cmd = Command::new(&cmake);
        cmd.arg("--install").arg(&self.build_dir);

        if self.verbose {
            eprintln!("Running: {:?}", cmd);
        }

        let status = cmd
            .stdin(Stdio::null())
            .status()
            .context("Failed to run CMake install")?;

        if !status.success() {
            bail!("CMake install failed with exit code: {:?}", status.code());
        }

        Ok(())
    }

    /// Run configure, build, and install in sequence
    pub fn configure_build_install(&self) -> Result<()> {
        self.configure()?;
        self.build()?;
        self.install()?;
        Ok(())
    }
}

/// Check if CMake is available
pub fn is_cmake_available() -> bool {
    which::which("cmake").is_ok()
}

/// Get CMake version
pub fn cmake_version() -> Option<String> {
    let output = Command::new("cmake").arg("--version").output().ok()?;
    let stdout = String::from_utf8_lossy(&output.stdout);
    // Parse "cmake version X.Y.Z"
    stdout
        .lines()
        .next()
        .and_then(|line| line.strip_prefix("cmake version "))
        .map(|v| v.to_string())
}