ccgo 3.8.12

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
//! Test command implementation
//!
//! Provides comprehensive testing functionality including:
//! - GoogleTest and Catch2 test discovery
//! - Test execution with filtering
//! - Code coverage reporting
//! - Result aggregation and CI integration

use std::path::{Path, PathBuf};

use anyhow::Result;
use clap::{Args, ValueEnum};

use crate::builder::platforms::tests::TestsBuilder;
use crate::builder::{BuildContext, BuildOptions, PlatformBuilder};
use crate::commands::build::{BuildTarget, LinkType, WindowsToolchain};
use crate::config::CcgoConfig;
use crate::testing::ci::{CiFormat, CiReporter};
use crate::testing::coverage::{CoverageCollector, CoverageConfig, CoverageFormat};
use crate::testing::discovery::TestDiscovery;
use crate::testing::results::TestResultAggregator;

/// Coverage output format for CLI
#[derive(Debug, Clone, Copy, ValueEnum, Default)]
pub enum CoverageOutputFormat {
    /// HTML report
    #[default]
    Html,
    /// LCOV format
    Lcov,
    /// JSON format
    Json,
    /// Cobertura XML
    Cobertura,
    /// Console summary only
    Summary,
}

impl From<CoverageOutputFormat> for CoverageFormat {
    fn from(f: CoverageOutputFormat) -> Self {
        match f {
            CoverageOutputFormat::Html => CoverageFormat::Html,
            CoverageOutputFormat::Lcov => CoverageFormat::Lcov,
            CoverageOutputFormat::Json => CoverageFormat::Json,
            CoverageOutputFormat::Cobertura => CoverageFormat::Cobertura,
            CoverageOutputFormat::Summary => CoverageFormat::Summary,
        }
    }
}

/// Run GoogleTest unit tests
#[derive(Args, Debug)]
pub struct TestCommand {
    /// Test filter pattern (e.g., TestSuite.TestCase, *Sort*)
    #[arg(long)]
    pub filter: Option<String>,

    /// Generate IDE project for tests instead of running
    #[arg(long)]
    pub ide_project: bool,

    /// Build tests without running them
    #[arg(long)]
    pub build_only: bool,

    /// Run tests without building (assumes already built)
    #[arg(long)]
    pub run_only: bool,

    /// Number of parallel jobs for building
    #[arg(short, long)]
    pub jobs: Option<usize>,

    /// Build in release mode
    #[arg(long)]
    pub release: bool,

    /// Named build profile (`[profile.<name>]` in CCGO.toml); composes with mode and sanitizer.
    /// The names `debug` and `release` are reserved — use the mode flags instead.
    #[arg(long)]
    pub profile: Option<String>,

    /// List all discovered tests without running
    #[arg(long)]
    pub list: bool,

    /// Enable code coverage collection
    #[arg(long)]
    pub coverage: bool,

    /// Coverage output format
    #[arg(long, value_enum, default_value = "html")]
    pub coverage_format: CoverageOutputFormat,

    /// Coverage output directory
    #[arg(long, default_value = "coverage")]
    pub coverage_dir: PathBuf,

    /// Minimum coverage threshold (0-100)
    #[arg(long)]
    pub coverage_threshold: Option<f64>,

    /// Fail if coverage is below threshold
    #[arg(long)]
    pub fail_under_coverage: bool,

    /// Aggregate results from multiple test runs
    #[arg(long)]
    pub aggregate: bool,

    /// Output format for CI integration
    #[arg(long)]
    pub ci_format: Option<String>,

    /// Write JUnit XML report to path
    #[arg(long)]
    pub junit_xml: Option<PathBuf>,

    /// Enable AddressSanitizer (ASan). Composes with `--debug`/`--release` and `--profile`.
    /// Output: `ccgo_build/{mode}[-{profile}]-asan/`. Mutually exclusive with `--tsan`.
    #[arg(long, conflicts_with = "tsan")]
    pub asan: bool,

    /// Enable ThreadSanitizer (TSan). Composes with `--debug`/`--release` and `--profile`.
    /// Output: `ccgo_build/{mode}[-{profile}]-tsan/`. Mutually exclusive with `--asan`.
    #[arg(long, conflicts_with = "asan")]
    pub tsan: bool,
}

impl TestCommand {
    /// Execute the test command
    /// Which sanitizer the CLI flags select, if any.
    fn sanitizer_kind(&self) -> Option<crate::builder::sanitizer::SanitizerKind> {
        if self.asan {
            Some(crate::builder::sanitizer::SanitizerKind::Address)
        } else if self.tsan {
            Some(crate::builder::sanitizer::SanitizerKind::Thread)
        } else {
            None
        }
    }

    /// Reject `--profile debug` / `--profile release`: those names are the
    /// build modes themselves and are selected with `--release` instead.
    fn validate_profile_name(&self) -> Result<()> {
        if let Some(ref pname) = self.profile {
            if matches!(pname.as_str(), "debug" | "release") {
                anyhow::bail!(
                    "'--profile {pname}' is reserved; use --release (or omit for debug) instead"
                );
            }
        }
        Ok(())
    }

    pub fn execute(self, verbose: bool) -> Result<()> {
        // Load project configuration
        let config = CcgoConfig::load()?;
        let project_root = std::env::current_dir()?;

        let sanitizer = self.sanitizer_kind();
        self.validate_profile_name()?;

        let release = self.release; // mode is CLI-only; profile.release is never applied
        let profile_name = self.profile.clone();

        // Create build context for tests
        let options = BuildOptions {
            // Placeholder: host builds have no BuildTarget. The build directory
            // name comes from new_with_platform_name() below, not from this.
            target: BuildTarget::Linux,
            architectures: vec![],
            link_type: LinkType::Both,
            use_docker: false,
            auto_docker: false,
            jobs: self.jobs,
            ide_project: self.ide_project,
            release,
            native_only: false,
            toolchain: WindowsToolchain::Auto,
            verbose,
            dev: false,
            features: vec![],
            use_default_features: true,
            all_features: false,
            cache: Some("auto".to_string()),
            analytics: false,
            linkage_default: None,
            linkage_overrides: std::collections::HashMap::new(),
            sanitizer,
            profile_name,
            ..BuildOptions::default()
        };

        let ctx = BuildContext::new_with_platform_name(
            project_root.clone(),
            config,
            options,
            "tests".to_string(),
        );
        let builder = TestsBuilder::new();

        // Use the build directory from the build context (respects config and profile).
        let build_dir = ctx.cmake_build_dir.clone();

        // Handle list command
        if self.list {
            return self.list_tests(&build_dir, verbose);
        }

        // Handle IDE project generation
        if self.ide_project {
            return builder.generate_ide_project(&ctx);
        }

        self.build_and_run(&builder, &ctx, verbose)?;
        self.report_results(&project_root, &build_dir, verbose)
    }

    /// Build the test binaries and run them, honouring --build-only/--run-only.
    fn build_and_run(
        &self,
        builder: &TestsBuilder,
        ctx: &BuildContext,
        verbose: bool,
    ) -> Result<()> {
        if !self.run_only {
            if verbose {
                eprintln!("Building tests...");
            }

            // Add coverage flags if enabled
            if self.coverage {
                // Note: Coverage requires special CMake flags
                // This would be passed via cmake_extra_flags in a real implementation
                eprintln!("📊 Coverage collection enabled");
            }

            builder.build(ctx)?;
        }

        if !self.build_only {
            if verbose {
                eprintln!("Running tests...");
            }
            builder.run_tests(ctx, self.filter.as_deref())?;
        }

        Ok(())
    }

    /// Everything that consumes the test run's output: aggregation, CI
    /// reporting and coverage collection.
    fn report_results(&self, project_root: &Path, build_dir: &Path, verbose: bool) -> Result<()> {
        if self.aggregate {
            self.aggregate_results(build_dir, verbose)?;
        }

        if self.ci_format.is_some() || self.junit_xml.is_some() {
            self.report_to_ci(build_dir, verbose)?;
        }

        if self.coverage && !self.build_only {
            self.collect_coverage(project_root, build_dir, verbose)?;
        }

        Ok(())
    }

    /// List discovered tests
    fn list_tests(&self, build_dir: &Path, verbose: bool) -> Result<()> {
        let discovery = TestDiscovery::new(build_dir.to_path_buf(), verbose);

        println!("Discovering tests...");

        let tests = if let Some(ref pattern) = self.filter {
            discovery.filter(pattern)?
        } else {
            discovery.discover_all()?
        };

        discovery.print_tests(&tests);

        // Also show by suite
        println!("\nTests by Suite:");
        let by_suite = discovery.list_by_suite()?;
        for (suite, suite_tests) in by_suite {
            println!("  {} ({} tests)", suite, suite_tests.len());
        }

        Ok(())
    }

    /// Aggregate test results
    fn aggregate_results(&self, build_dir: &Path, verbose: bool) -> Result<()> {
        let mut aggregator = TestResultAggregator::new(verbose);
        aggregator.find_results(build_dir)?;

        let summary = aggregator.aggregate()?;
        summary.print_summary();

        // Write JUnit XML if requested
        if let Some(ref junit_path) = self.junit_xml {
            std::fs::write(junit_path, summary.to_junit_xml())?;
            eprintln!("JUnit XML written to: {}", junit_path.display());
        }

        if !summary.all_passed() {
            anyhow::bail!("{} test(s) failed", summary.failed + summary.errors);
        }

        Ok(())
    }

    /// Report results to CI
    fn report_to_ci(&self, build_dir: &Path, verbose: bool) -> Result<()> {
        let mut aggregator = TestResultAggregator::new(verbose);
        aggregator.find_results(build_dir)?;
        let summary = aggregator.aggregate()?;

        // Determine CI format
        let format = if let Some(ref fmt) = self.ci_format {
            fmt.parse::<CiFormat>()?
        } else {
            CiFormat::detect()
        };

        let reporter = CiReporter::new(format);
        reporter.report_tests(&summary);

        // Write JUnit XML if requested
        if let Some(ref junit_path) = self.junit_xml {
            reporter.write_junit_xml(&summary, junit_path)?;
            eprintln!("JUnit XML written to: {}", junit_path.display());
        }

        Ok(())
    }

    /// Collect code coverage
    fn collect_coverage(&self, project_root: &Path, build_dir: &Path, verbose: bool) -> Result<()> {
        eprintln!("\n📊 Collecting code coverage...");

        let config = CoverageConfig {
            source_dir: project_root.to_path_buf(),
            build_dir: build_dir.to_path_buf(),
            output_dir: self.coverage_dir.clone(),
            format: self.coverage_format.into(),
            threshold: self.coverage_threshold,
            fail_under: self.fail_under_coverage,
            ..Default::default()
        };

        let collector = CoverageCollector::new(config, verbose);

        match collector.collect() {
            Ok(report) => {
                report.print_summary();

                // Generate HTML if requested
                if matches!(self.coverage_format, CoverageOutputFormat::Html) {
                    match collector.generate_html(&report) {
                        Ok(html_path) => {
                            eprintln!("\n📄 HTML report: {}", html_path.display());

                            // Try to open in browser
                            #[cfg(target_os = "macos")]
                            {
                                let _ = std::process::Command::new("open").arg(&html_path).status();
                            }
                        }
                        Err(e) => {
                            eprintln!("Warning: Could not generate HTML report: {}", e);
                        }
                    }
                }

                // Check threshold
                if let Some(threshold) = self.coverage_threshold {
                    if !report.meets_threshold(threshold) {
                        let msg = format!(
                            "Coverage {:.1}% is below threshold {:.1}%",
                            report.line_coverage_percent(),
                            threshold
                        );
                        if self.fail_under_coverage {
                            anyhow::bail!(msg);
                        } else {
                            eprintln!("⚠️  {}", msg);
                        }
                    }
                }

                // CI reporting for coverage
                if self.ci_format.is_some() {
                    let format = if let Some(ref fmt) = self.ci_format {
                        fmt.parse::<CiFormat>()?
                    } else {
                        CiFormat::detect()
                    };
                    let reporter = CiReporter::new(format);
                    reporter.report_coverage(&report);
                }

                Ok(())
            }
            Err(e) => {
                eprintln!("⚠️  Coverage collection failed: {}", e);
                eprintln!("   Make sure tests were built with coverage flags:");
                eprintln!("   -DCMAKE_CXX_FLAGS=\"--coverage\" -DCMAKE_C_FLAGS=\"--coverage\"");
                Ok(()) // Don't fail the test run
            }
        }
    }
}