ccgo 3.6.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
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
//! Build failure diagnostics and pattern matching
//!
//! This module analyzes build errors and provides actionable solutions
//! based on common failure patterns.

use regex::Regex;
use std::path::Path;

/// Build error category
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ErrorCategory {
    /// Missing dependency
    MissingDependency,
    /// Compiler error
    CompilerError,
    /// Linker error
    LinkerError,
    /// CMake configuration error
    CMakeError,
    /// Android NDK error
    AndroidNdkError,
    /// Xcode/Apple toolchain error
    XcodeError,
    /// Permission error
    PermissionError,
    /// Disk space error
    DiskSpaceError,
    /// Unknown error
    Unknown,
}

/// Diagnostic result with suggested solutions
#[derive(Debug, Clone)]
pub struct Diagnostic {
    /// Error category
    pub category: ErrorCategory,
    /// Brief description of the issue
    pub description: String,
    /// Suggested solutions (ordered by likelihood)
    pub solutions: Vec<String>,
    /// Original error messages that matched
    pub matched_errors: Vec<String>,
}

impl Diagnostic {
    /// Create a new diagnostic
    pub fn new(
        category: ErrorCategory,
        description: impl Into<String>,
        solutions: Vec<String>,
    ) -> Self {
        Self {
            category,
            description: description.into(),
            solutions,
            matched_errors: Vec::new(),
        }
    }

    /// Add a matched error message
    pub fn with_error(mut self, error: impl Into<String>) -> Self {
        self.matched_errors.push(error.into());
        self
    }

    /// Print the diagnostic in a user-friendly format
    pub fn print(&self) {
        use console::style;

        eprintln!("\n{}", style("=".repeat(80)).dim());
        eprintln!("{} Build Failure Diagnostics", style("🔍").cyan());
        eprintln!("{}", style("=".repeat(80)).dim());

        eprintln!("\n{} {}", style("Category:").bold(), self.category.as_str());
        eprintln!("{} {}", style("Issue:").bold(), self.description);

        if !self.matched_errors.is_empty() {
            eprintln!("\n{}", style("Matched Errors:").bold());
            for (i, error) in self.matched_errors.iter().enumerate().take(3) {
                eprintln!("  {}. {}", i + 1, style(error).dim());
            }
            if self.matched_errors.len() > 3 {
                eprintln!("  ... and {} more", self.matched_errors.len() - 3);
            }
        }

        eprintln!("\n{}", style("Suggested Solutions:").yellow().bold());
        for (i, solution) in self.solutions.iter().enumerate() {
            eprintln!("  {}. {}", i + 1, solution);
        }

        eprintln!();
    }
}

impl ErrorCategory {
    fn as_str(&self) -> &'static str {
        match self {
            ErrorCategory::MissingDependency => "Missing Dependency",
            ErrorCategory::CompilerError => "Compiler Error",
            ErrorCategory::LinkerError => "Linker Error",
            ErrorCategory::CMakeError => "CMake Configuration Error",
            ErrorCategory::AndroidNdkError => "Android NDK Error",
            ErrorCategory::XcodeError => "Xcode/Apple Toolchain Error",
            ErrorCategory::PermissionError => "Permission Error",
            ErrorCategory::DiskSpaceError => "Disk Space Error",
            ErrorCategory::Unknown => "Unknown Error",
        }
    }
}

/// Analyze build output and provide diagnostics
pub fn analyze_build_failure(
    output: &str,
    platform: &str,
    _project_root: &Path,
) -> Option<Diagnostic> {
    // Try each pattern matcher in order of specificity
    if let Some(diag) = check_missing_dependency(output) {
        return Some(diag);
    }

    if let Some(diag) = check_cmake_errors(output) {
        return Some(diag);
    }

    if let Some(diag) = check_android_ndk_errors(output, platform) {
        return Some(diag);
    }

    if let Some(diag) = check_xcode_errors(output, platform) {
        return Some(diag);
    }

    if let Some(diag) = check_linker_errors(output) {
        return Some(diag);
    }

    if let Some(diag) = check_compiler_errors(output) {
        return Some(diag);
    }

    if let Some(diag) = check_permission_errors(output) {
        return Some(diag);
    }

    if let Some(diag) = check_disk_space_errors(output) {
        return Some(diag);
    }

    None
}

/// Check for missing dependency errors
fn check_missing_dependency(output: &str) -> Option<Diagnostic> {
    let patterns = [
        (r"fatal error: (.+\.h[pp]*): No such file or directory", "C++ header"),
        (r"Could not find package '(.+)'", "CMake package"),
        (r"Package '(.+)' not found", "pkg-config package"),
        (r"library not found for -l(\w+)", "library"),
    ];

    for (pattern, dep_type) in &patterns {
        if let Ok(re) = Regex::new(pattern) {
            if let Some(cap) = re.captures(output) {
                let dep_name = cap.get(1).map_or("unknown", |m| m.as_str());

                let diag = Diagnostic::new(
                    ErrorCategory::MissingDependency,
                    format!("Missing {} dependency: {}", dep_type, dep_name),
                    vec![
                        format!("Install the {} package/library", dep_name),
                        format!("Add {} to your CCGO.toml dependencies", dep_name),
                        "Run: ccgo install to install dependencies".to_string(),
                        "Check if the dependency path is correct in CMakeLists.txt".to_string(),
                    ],
                ).with_error(cap.get(0).map_or("", |m| m.as_str()));

                return Some(diag);
            }
        }
    }

    None
}

/// Check for CMake configuration errors
fn check_cmake_errors(output: &str) -> Option<Diagnostic> {
    if output.contains("CMake Error") || output.contains("CMake configuration failed") {
        let solutions = if output.contains("Could not find") {
            vec![
                "Install missing CMake dependencies".to_string(),
                "Check your system package manager (apt, brew, etc.)".to_string(),
                "Verify CMake package paths in CMakeLists.txt".to_string(),
            ]
        } else if output.contains("No CMAKE_") || output.contains("CMAKE_.*_COMPILER") {
            vec![
                "Install a C++ compiler (g++, clang, or MSVC)".to_string(),
                "Set CMAKE_CXX_COMPILER environment variable".to_string(),
                "On macOS: install Xcode command line tools with 'xcode-select --install'".to_string(),
                "On Linux: install build-essential with 'sudo apt install build-essential'".to_string(),
            ]
        } else if output.contains("version") {
            vec![
                "Upgrade CMake to a newer version".to_string(),
                "Check minimum CMake version in CMakeLists.txt".to_string(),
                "Install CMake: brew install cmake (macOS) or sudo apt install cmake (Linux)".to_string(),
            ]
        } else {
            vec![
                "Check CMakeLists.txt for syntax errors".to_string(),
                "Verify all CMake variables are set correctly".to_string(),
                "Clean build directory and try again: ccgo clean -y".to_string(),
            ]
        };

        return Some(Diagnostic::new(
            ErrorCategory::CMakeError,
            "CMake configuration failed",
            solutions,
        ));
    }

    None
}

/// Check for Android NDK errors
fn check_android_ndk_errors(output: &str, platform: &str) -> Option<Diagnostic> {
    if !platform.contains("android") && !platform.contains("Android") {
        return None;
    }

    if output.contains("ANDROID_NDK") || output.contains("ndk") && output.contains("not found") {
        return Some(Diagnostic::new(
            ErrorCategory::AndroidNdkError,
            "Android NDK not found or not configured",
            vec![
                "Install Android NDK via Android Studio SDK Manager".to_string(),
                "Set ANDROID_NDK environment variable to your NDK path".to_string(),
                "Example: export ANDROID_NDK=/path/to/android-sdk/ndk/25.1.8937393".to_string(),
                "Or set ANDROID_HOME if using SDK default location".to_string(),
            ],
        ));
    }

    if output.contains("unsupported NDK version") || output.contains("NDK version") {
        return Some(Diagnostic::new(
            ErrorCategory::AndroidNdkError,
            "Incompatible NDK version",
            vec![
                "Update Android NDK to a compatible version (25.x or higher recommended)".to_string(),
                "Check project's minSdk requirements in CCGO.toml".to_string(),
                "Install via Android Studio: Tools → SDK Manager → SDK Tools → NDK".to_string(),
            ],
        ));
    }

    None
}

/// Check for Xcode/Apple toolchain errors
fn check_xcode_errors(output: &str, platform: &str) -> Option<Diagnostic> {
    let is_apple = platform.contains("ios") || platform.contains("macos") ||
                   platform.contains("tvos") || platform.contains("watchos") ||
                   platform.contains("apple");

    if !is_apple {
        return None;
    }

    if output.contains("xcode-select") || output.contains("xcrun") && output.contains("error") {
        return Some(Diagnostic::new(
            ErrorCategory::XcodeError,
            "Xcode command line tools not found",
            vec![
                "Install Xcode from the App Store".to_string(),
                "Install command line tools: sudo xcode-select --install".to_string(),
                "Accept Xcode license: sudo xcodebuild -license accept".to_string(),
                "Set Xcode path: sudo xcode-select -s /Applications/Xcode.app".to_string(),
            ],
        ));
    }

    if output.contains("code signing") || output.contains("DEVELOPMENT_TEAM") {
        return Some(Diagnostic::new(
            ErrorCategory::XcodeError,
            "Code signing configuration required",
            vec![
                "Set DEVELOPMENT_TEAM in Xcode project settings".to_string(),
                "Or disable code signing for development builds".to_string(),
                "For frameworks, code signing is optional unless running on device".to_string(),
            ],
        ));
    }

    if output.contains("deployment target") {
        return Some(Diagnostic::new(
            ErrorCategory::XcodeError,
            "Deployment target version mismatch",
            vec![
                "Update minimum deployment target in CCGO.toml".to_string(),
                "Ensure all dependencies support your minimum version".to_string(),
                "Check platform-specific configuration: [platforms.ios] or [platforms.macos]".to_string(),
            ],
        ));
    }

    None
}

/// Check for linker errors
fn check_linker_errors(output: &str) -> Option<Diagnostic> {
    if output.contains("undefined reference") || output.contains("unresolved external symbol") {
        return Some(Diagnostic::new(
            ErrorCategory::LinkerError,
            "Undefined symbols (linker error)",
            vec![
                "Missing library or object file during linking".to_string(),
                "Add missing libraries to target_link_libraries in CMakeLists.txt".to_string(),
                "Check if all source files are included in the build".to_string(),
                "Verify function/symbol declarations match implementations".to_string(),
            ],
        ));
    }

    if output.contains("duplicate symbol") {
        return Some(Diagnostic::new(
            ErrorCategory::LinkerError,
            "Duplicate symbols (linker error)",
            vec![
                "Multiple definitions of the same symbol".to_string(),
                "Remove duplicate source files from CMakeLists.txt".to_string(),
                "Use inline or static functions to avoid multiple definitions".to_string(),
                "Check for header-only libraries included multiple times".to_string(),
            ],
        ));
    }

    if output.contains("cannot find -l") {
        return Some(Diagnostic::new(
            ErrorCategory::LinkerError,
            "Library not found during linking",
            vec![
                "Install the required system library".to_string(),
                "Add library path to CMAKE_LIBRARY_PATH or LDFLAGS".to_string(),
                "Check that the library name in CMakeLists.txt is correct".to_string(),
            ],
        ));
    }

    None
}

/// Check for compiler errors
fn check_compiler_errors(output: &str) -> Option<Diagnostic> {
    if output.contains("error:") && (output.contains(".cpp:") || output.contains(".cc:") || output.contains(".h:")) {
        // Generic compiler error
        if output.contains("C++") && output.contains("standard") {
            return Some(Diagnostic::new(
                ErrorCategory::CompilerError,
                "C++ standard version incompatibility",
                vec![
                    "Update C++ standard in CMakeLists.txt: set(CMAKE_CXX_STANDARD 17)".to_string(),
                    "Ensure all dependencies support the same C++ standard".to_string(),
                    "Common standards: C++11, C++14, C++17, C++20".to_string(),
                ],
            ));
        }

        return Some(Diagnostic::new(
            ErrorCategory::CompilerError,
            "Compilation failed",
            vec![
                "Fix syntax errors in source code".to_string(),
                "Check compiler warnings for hints".to_string(),
                "Ensure all headers are included correctly".to_string(),
                "Verify C++ standard compatibility".to_string(),
            ],
        ));
    }

    None
}

/// Check for permission errors
fn check_permission_errors(output: &str) -> Option<Diagnostic> {
    if output.contains("Permission denied") || output.contains("EACCES") {
        return Some(Diagnostic::new(
            ErrorCategory::PermissionError,
            "Permission denied",
            vec![
                "Check file/directory permissions".to_string(),
                "Run with appropriate user permissions (may need sudo)".to_string(),
                "Ensure build directory is writable".to_string(),
                "On macOS: check Gatekeeper and Security settings".to_string(),
            ],
        ));
    }

    None
}

/// Check for disk space errors
fn check_disk_space_errors(output: &str) -> Option<Diagnostic> {
    if output.contains("No space left on device") || output.contains("ENOSPC") {
        return Some(Diagnostic::new(
            ErrorCategory::DiskSpaceError,
            "Insufficient disk space",
            vec![
                "Free up disk space on your system".to_string(),
                "Clean build artifacts: ccgo clean -y".to_string(),
                "Remove unused Docker images: docker system prune -a".to_string(),
                "Check disk usage: df -h (Linux/macOS) or dir (Windows)".to_string(),
            ],
        ));
    }

    None
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_missing_header() {
        let output = "fatal error: fmt/core.h: No such file or directory";
        let diag = analyze_build_failure(output, "linux", Path::new("."));
        assert!(diag.is_some());
        let diag = diag.unwrap();
        assert_eq!(diag.category, ErrorCategory::MissingDependency);
        assert!(diag.description.contains("fmt/core.h"));
    }

    #[test]
    fn test_cmake_error() {
        let output = "CMake Error: Could not find package FooBar";
        let diag = analyze_build_failure(output, "linux", Path::new("."));
        assert!(diag.is_some());
        assert_eq!(diag.unwrap().category, ErrorCategory::CMakeError);
    }

    #[test]
    fn test_android_ndk_error() {
        let output = "Error: ANDROID_NDK environment variable not set";
        let diag = analyze_build_failure(output, "android", Path::new("."));
        assert!(diag.is_some());
        assert_eq!(diag.unwrap().category, ErrorCategory::AndroidNdkError);
    }

    #[test]
    fn test_xcode_error() {
        let output = "error: xcode-select: command not found";
        let diag = analyze_build_failure(output, "ios", Path::new("."));
        assert!(diag.is_some());
        assert_eq!(diag.unwrap().category, ErrorCategory::XcodeError);
    }
}