ccgo 3.4.2

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
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
//! Linux platform builder
//!
//! Builds static and shared libraries for Linux using CMake with GCC or Clang.

use std::path::PathBuf;
use std::time::Instant;

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

use crate::build::archive::{
    get_unified_include_path, ArchiveBuilder, ARCHIVE_DIR_OBJ, ARCHIVE_DIR_SHARED,
    ARCHIVE_DIR_STATIC,
};
use crate::build::cmake::{BuildType, CMakeConfig};
#[cfg(target_os = "linux")]
use crate::build::toolchains::detect_default_compiler;
use crate::build::{BuildContext, BuildResult, PlatformBuilder};
use crate::commands::build::LinkType;

/// Linux platform builder
pub struct LinuxBuilder;

impl LinuxBuilder {
    pub fn new() -> Self {
        Self
    }

    /// Merge all module static libraries into a single library
    /// This is essential for KMP cinterop which expects a single complete library
    fn merge_module_static_libs(
        &self,
        build_dir: &PathBuf,
        lib_name: &str,
        verbose: bool,
    ) -> Result<()> {
        use crate::build::toolchains::linux::LinuxToolchain;

        // Find the output directory where CMake puts libraries
        let out_dir = build_dir.join("out");
        if verbose {
            eprintln!("    [merge] Checking out directory: {}", out_dir.display());
        }
        if !out_dir.exists() {
            if verbose {
                eprintln!("    [merge] Out directory does not exist, skipping merge");
            }
            return Ok(());
        }

        // Check if the main library already exists (CMake may have already merged it)
        let main_lib_name = format!("lib{}.a", lib_name);
        let main_lib_path = out_dir.join(&main_lib_name);

        if main_lib_path.exists() {
            // Check if it's a non-empty file (CMake already created the merged library)
            if let Ok(metadata) = std::fs::metadata(&main_lib_path) {
                if metadata.len() > 0 {
                    if verbose {
                        eprintln!("    [merge] Main library {} already exists, skipping merge", main_lib_name);
                    }
                    // Clean up module libraries (keep output directory clean)
                    for entry in std::fs::read_dir(&out_dir)? {
                        let entry = entry?;
                        let path = entry.path();
                        if path.is_file() && path != main_lib_path {
                            if let Some(ext) = path.extension() {
                                if ext == "a" {
                                    let _ = std::fs::remove_file(&path);
                                }
                            }
                        }
                    }
                    return Ok(());
                }
            }
        }

        // Find all .a files (module libraries)
        let mut module_libs: Vec<PathBuf> = Vec::new();
        for entry in std::fs::read_dir(&out_dir)? {
            let entry = entry?;
            let path = entry.path();
            if path.is_file() {
                if let Some(ext) = path.extension() {
                    if ext == "a" {
                        module_libs.push(path);
                    }
                }
            }
        }

        if verbose {
            eprintln!("    [merge] Found {} .a files:", module_libs.len());
            for lib in &module_libs {
                eprintln!("      - {}", lib.file_name().unwrap().to_string_lossy());
            }
        }

        if module_libs.is_empty() {
            if verbose {
                eprintln!("    [merge] No libraries found, skipping merge");
            }
            return Ok(());
        }

        // Check if we only have the main library (already merged or single module)
        if module_libs.len() == 1 && module_libs[0].file_name().map_or(false, |n| n == main_lib_name.as_str()) {
            if verbose {
                eprintln!("    [merge] Only main library exists, skipping merge");
            }
            return Ok(());
        }

        // Filter out the main library if it exists (we'll recreate it)
        module_libs.retain(|p| p != &main_lib_path);

        if verbose {
            eprintln!("    [merge] Module libraries to merge: {}", module_libs.len());
            for lib in &module_libs {
                eprintln!("      - {}", lib.file_name().unwrap().to_string_lossy());
            }
        }

        if module_libs.is_empty() {
            if verbose {
                eprintln!("    [merge] No module libraries after filtering, skipping merge");
            }
            return Ok(());
        }

        eprintln!(
            "    Merging {} module libraries into {}",
            module_libs.len(),
            main_lib_name
        );

        // Merge all module libraries into the main library
        let toolchain = LinuxToolchain::detect()?;
        toolchain.merge_static_libs(&module_libs, &main_lib_path)?;

        // Clean up module libraries after merge
        eprintln!("    Cleaning up {} module libraries...", module_libs.len());
        for lib in &module_libs {
            if lib != &main_lib_path {
                match std::fs::remove_file(lib) {
                    Ok(_) => {
                        if verbose {
                            eprintln!("      ✓ Removed: {}", lib.file_name().unwrap().to_string_lossy());
                        }
                    }
                    Err(e) => {
                        eprintln!("      âš  Failed to remove {}: {}", lib.file_name().unwrap().to_string_lossy(), e);
                    }
                }
            }
        }

        Ok(())
    }

    /// Merge third-party static libs (e.g. libzstd.a) from cmake build root into the main lib
    fn merge_third_party_static_libs(
        &self,
        build_dir: &PathBuf,
        lib_name: &str,
        verbose: bool,
    ) -> Result<()> {
        use crate::build::toolchains::linux::LinuxToolchain;

        let out_dir = build_dir.join("out");
        let main_lib_path = out_dir.join(format!("lib{}.a", lib_name));
        if !main_lib_path.exists() {
            return Ok(());
        }

        let placeholder_name = format!("lib{}.a", lib_name);
        let mut third_party_libs: Vec<PathBuf> = Vec::new();
        for entry in std::fs::read_dir(build_dir)? {
            let entry = entry?;
            let path = entry.path();
            if path.is_file() {
                if let Some(ext) = path.extension() {
                    if ext == "a" {
                        let fname = path.file_name().unwrap_or_default().to_str().unwrap_or_default();
                        if fname != placeholder_name {
                            third_party_libs.push(path);
                        }
                    }
                }
            }
        }

        if third_party_libs.is_empty() {
            return Ok(());
        }

        if verbose {
            eprintln!("    Merging {} third-party libs into {}", third_party_libs.len(), placeholder_name);
        }

        let toolchain = LinuxToolchain::detect()?;
        let mut all_libs = vec![main_lib_path.clone()];
        all_libs.extend(third_party_libs);
        toolchain.merge_static_libs(&all_libs, &main_lib_path)?;

        Ok(())
    }

    /// Build a specific link type (static or shared)
    /// Returns the build directory where output is located
    fn build_link_type(&self, ctx: &BuildContext, link_type: &str) -> Result<PathBuf> {
        let build_dir = ctx.cmake_build_dir.join(link_type);
        let install_dir = build_dir.join("install");

        let build_shared = link_type == "shared";

        // Configure and build with CMake
        let mut cmake = CMakeConfig::new(ctx.project_root.clone(), build_dir.clone())
            .build_type(if ctx.options.release {
                BuildType::Release
            } else {
                BuildType::Debug
            })
            .install_prefix(install_dir.clone())
            .variable("CCGO_BUILD_STATIC", if build_shared { "OFF" } else { "ON" })
            .variable("CCGO_BUILD_SHARED", if build_shared { "ON" } else { "OFF" })
            .variable("CCGO_BUILD_SHARED_LIBS", if build_shared { "ON" } else { "OFF" })
            .variable("CCGO_LIB_NAME", ctx.lib_name())
            .jobs(ctx.jobs())
            .verbose(ctx.options.verbose);

        // Add CCGO_CMAKE_DIR if available
        if let Some(cmake_dir) = ctx.ccgo_cmake_dir() {
            cmake = cmake.variable("CCGO_CMAKE_DIR", cmake_dir.display().to_string());
        }

        // Add CCGO configuration variables
        cmake = cmake.variable(
            "CCGO_CONFIG_PRESET_VISIBILITY",
            ctx.symbol_visibility().to_string(),
        );

        // Add submodule dependencies for shared library linking
        if let Some(deps_map) = ctx.deps_map() {
            cmake = cmake.variable("CCGO_CONFIG_DEPS_MAP", deps_map);
        }

        // Add feature definitions for conditional compilation
        if let Ok(feature_defines) = ctx.cmake_feature_defines() {
            if !feature_defines.is_empty() {
                cmake = cmake.feature_definitions(&feature_defines);
                if ctx.options.verbose {
                    eprintln!("    Enabled features: {}", feature_defines.replace(';', ", "));
                }
            }
        }

        // Add compiler cache if available
        if let Some(cache) = ctx.compiler_cache() {
            cmake = cmake.compiler_cache(cache);
        }

        cmake.configure_build_install()?;

        // For static builds, merge all module libraries into a single library
        // This is essential for KMP cinterop which expects a single complete library
        if !build_shared {
            self.merge_module_static_libs(&build_dir, ctx.lib_name(), ctx.options.verbose)?;
            self.merge_third_party_static_libs(&build_dir, ctx.lib_name(), ctx.options.verbose)?;
        }

        // Return build_dir since CCGO cmake installs to build_dir/out/
        Ok(build_dir)
    }

    /// Generate IDE project files for Linux
    pub fn generate_ide_project(&self, ctx: &BuildContext) -> Result<BuildResult> {
        use std::process::Command;

        let build_dir = ctx.cmake_build_dir.join("ide_project");

        // Clean build directory
        if build_dir.exists() {
            std::fs::remove_dir_all(&build_dir)
                .with_context(|| format!("Failed to clean {}", build_dir.display()))?;
        }

        // Create build directory
        std::fs::create_dir_all(&build_dir)
            .with_context(|| format!("Failed to create {}", build_dir.display()))?;

        eprintln!(
            "Generating IDE project for Linux in {}...",
            build_dir.display()
        );

        // Configure with CMake using CodeLite generator
        // Also generate compile_commands.json for IDEs like VS Code, CLion
        let mut cmake_cmd = Command::new("cmake");
        cmake_cmd
            .arg("-S")
            .arg(&ctx.project_root)
            .arg("-B")
            .arg(&build_dir)
            .arg("-G")
            .arg("CodeLite - Unix Makefiles")
            .arg("-DCMAKE_EXPORT_COMPILE_COMMANDS=ON");

        // Add CCGO_CMAKE_DIR if available
        if let Some(cmake_dir) = ctx.ccgo_cmake_dir() {
            cmake_cmd.arg(format!("-DCCGO_CMAKE_DIR={}", cmake_dir.display()));
        }

        // Add lib name
        cmake_cmd.arg(format!("-DCCGO_LIB_NAME={}", ctx.lib_name()));

        if ctx.options.verbose {
            eprintln!("CMake configure: {:?}", cmake_cmd);
        }

        let status = cmake_cmd.status().context("Failed to run CMake configure")?;
        if !status.success() {
            bail!("CMake configure failed");
        }

        // Find and report project file
        let workspace_file = build_dir.join(format!("{}.workspace", ctx.lib_name()));
        let compile_commands = build_dir.join("compile_commands.json");

        if workspace_file.exists() {
            eprintln!(
                "\n✓ CodeLite workspace generated: {}",
                workspace_file.display()
            );
        }

        if compile_commands.exists() {
            eprintln!(
                "✓ compile_commands.json generated: {}",
                compile_commands.display()
            );
            eprintln!("   (Use with VS Code C/C++ extension, CLion, or other LSP-compatible editors)");

            // Optionally symlink compile_commands.json to project root for VS Code
            let root_compile_commands = ctx.project_root.join("compile_commands.json");
            if !root_compile_commands.exists() {
                #[cfg(unix)]
                {
                    let _ = std::os::unix::fs::symlink(&compile_commands, &root_compile_commands);
                    eprintln!("   Symlinked to project root for VS Code");
                }
            }
        }

        if !workspace_file.exists() && !compile_commands.exists() {
            eprintln!(
                "\n✓ IDE project files generated in: {}",
                build_dir.display()
            );
        }

        // Return a placeholder result for IDE generation
        Ok(BuildResult {
            sdk_archive: build_dir,
            symbols_archive: None,
            aar_archive: None,
            duration_secs: 0.0,
            architectures: vec![],
        })
    }

    /// Find library directory in build output
    /// Prioritizes out/ directory where CCGO cmake puts the merged library
    fn find_lib_dir(&self, build_dir: &PathBuf) -> Option<PathBuf> {
        // CCGO cmake puts the combined/merged library in out/
        // e.g., static/out/libccgonow.a or shared/out/libccgonow.so
        // This is the preferred location as it contains only the final merged library
        let possible_dirs = vec![
            build_dir.join("out"),           // Merged library (priority)
            build_dir.join("install/lib"),   // Fallback: CMake install location
            build_dir.join("lib"),
        ];

        for dir in possible_dirs {
            if dir.exists() {
                return Some(dir);
            }
        }
        None
    }
}

impl PlatformBuilder for LinuxBuilder {
    fn platform_name(&self) -> &str {
        "linux"
    }

    fn default_architectures(&self) -> Vec<String> {
        vec!["x86_64".to_string()]
    }

    fn validate_prerequisites(&self, _ctx: &BuildContext) -> Result<()> {
        // Check if we're on Linux
        #[cfg(not(target_os = "linux"))]
        {
            bail!(
                "Linux builds can only be run on Linux systems.\n\
                 Current OS: {}\n\n\
                 To build for Linux from your current OS, use Docker:\n  \
                 ccgo build linux --docker",
                std::env::consts::OS
            );
        }

        #[cfg(target_os = "linux")]
        {
            // Check for CMake
            if !crate::build::cmake::is_cmake_available() {
                bail!("CMake is required for Linux builds. Please install CMake.");
            }

            // Check for C++ compiler
            let compiler = detect_default_compiler()
                .context("No C/C++ compiler found. Please install GCC or Clang.")?;

            if _ctx.options.verbose {
                eprintln!(
                    "Using {} compiler: {} ({})",
                    compiler.compiler_type,
                    compiler.cxx.display(),
                    compiler.version
                );
            }

            Ok(())
        }
    }

    fn build(&self, ctx: &BuildContext) -> Result<BuildResult> {
        // Check for IDE project generation mode
        if ctx.options.ide_project {
            return self.generate_ide_project(ctx);
        }

        let start = Instant::now();

        // Validate prerequisites first
        self.validate_prerequisites(ctx)?;

        if ctx.options.verbose {
            eprintln!("Building {} for Linux...", ctx.lib_name());
        }

        // Create output directory
        std::fs::create_dir_all(&ctx.output_dir)?;

        // Create archive builder
        let archive = ArchiveBuilder::new(
            ctx.lib_name(),
            ctx.version(),
            ctx.publish_suffix(),
            ctx.options.release,
            "linux",
            ctx.output_dir.clone(),
        )?;

        let mut built_link_types = Vec::new();

        // Build static libraries
        if matches!(ctx.options.link_type, LinkType::Static | LinkType::Both) {
            if ctx.options.verbose {
                eprintln!("Building static library...");
            }
            let build_dir = self.build_link_type(ctx, "static")?;

            // Add static library to archive: lib/linux/static/
            // find_lib_dir prioritizes out/ which contains only the merged library
            if let Some(lib_dir) = self.find_lib_dir(&build_dir) {
                let archive_path = format!("lib/{}/{}", self.platform_name(), ARCHIVE_DIR_STATIC);
                archive.add_directory_filtered(&lib_dir, &archive_path, &["a"])?;
            }
            built_link_types.push("static");
        }

        // Build shared libraries
        if matches!(ctx.options.link_type, LinkType::Shared | LinkType::Both) {
            if ctx.options.verbose {
                eprintln!("Building shared library...");
            }
            let build_dir = self.build_link_type(ctx, "shared")?;

            // Add shared library to archive: lib/linux/shared/
            // find_lib_dir prioritizes out/ which contains only the merged library
            if let Some(lib_dir) = self.find_lib_dir(&build_dir) {
                let archive_path = format!("lib/{}/{}", self.platform_name(), ARCHIVE_DIR_SHARED);
                archive.add_directory_filtered(&lib_dir, &archive_path, &["so", "a"])?;
            }
            built_link_types.push("shared");
        }

        // Add include files from project's include directory (matching pyccgo behavior)
        let include_source = ctx.include_source_dir();
        if include_source.exists() {
            let include_path = get_unified_include_path(ctx.lib_name(), &include_source);
            archive.add_directory(&include_source, &include_path)?;
            if ctx.options.verbose {
                eprintln!("Added include files from {} to {}", include_source.display(), include_path);
            }
        }

        // Create the SDK archive
        let link_type_str = ctx.options.link_type.to_string();
        let sdk_archive = archive.create_sdk_archive(&["x86_64".to_string()], &link_type_str)?;

        // Create symbols archive with unstripped binaries
        // Structure: obj/linux/x86_64/*.so (for shared libs)
        let mut symbols_archive_result = None;
        if ctx.options.link_type != LinkType::Static {
            // For shared builds, collect unstripped .so files
            let symbols_temp = std::env::temp_dir().join(format!("ccgo-symbols-{}", ctx.lib_name()));
            std::fs::create_dir_all(&symbols_temp)?;

            // Create obj/linux/x86_64/ structure
            let obj_arch_dir = symbols_temp
                .join(ARCHIVE_DIR_OBJ)
                .join(self.platform_name())
                .join("x86_64");
            std::fs::create_dir_all(&obj_arch_dir)?;

            // Find and copy unstripped .so files from build directory
            let shared_build_dir = ctx.cmake_build_dir.join("shared");
            if let Some(lib_dir) = self.find_lib_dir(&shared_build_dir) {
                for entry in std::fs::read_dir(&lib_dir)? {
                    let entry = entry?;
                    let path = entry.path();
                    if path.extension().map_or(false, |ext| ext == "so") {
                        let file_name = path.file_name().unwrap();
                        std::fs::copy(&path, obj_arch_dir.join(file_name))?;
                    }
                }

                // Only create symbols archive if we found .so files
                if obj_arch_dir.read_dir()?.next().is_some() {
                    let symbols_archive_path = archive.create_symbols_archive(&symbols_temp)?;
                    symbols_archive_result = Some(symbols_archive_path);
                }
            }

            // Clean up temp directory
            if symbols_temp.exists() {
                std::fs::remove_dir_all(&symbols_temp)?;
            }
        }

        let duration = start.elapsed();

        if ctx.options.verbose {
            eprintln!(
                "Linux build completed in {:.2}s: {}",
                duration.as_secs_f64(),
                sdk_archive.display()
            );
            if let Some(ref sym) = symbols_archive_result {
                eprintln!("  Symbols archive: {}", sym.display());
            }
        }

        Ok(BuildResult {
            sdk_archive,
            symbols_archive: symbols_archive_result,
            aar_archive: None,
            duration_secs: duration.as_secs_f64(),
            architectures: vec!["x86_64".to_string()],
        })
    }

    fn clean(&self, ctx: &BuildContext) -> Result<()> {
        // Clean new directory structure: cmake_build/{release|debug}/linux
        for subdir in &["release", "debug"] {
            let build_dir = ctx.project_root.join("cmake_build").join(subdir).join("linux");
            if build_dir.exists() {
                std::fs::remove_dir_all(&build_dir)
                    .with_context(|| format!("Failed to clean {}", build_dir.display()))?;
            }
        }

        // Clean old structure for backwards compatibility: cmake_build/Linux, cmake_build/linux
        for old_dir in &[
            ctx.project_root.join("cmake_build/Linux"),
            ctx.project_root.join("cmake_build/linux"),
        ] {
            if old_dir.exists() {
                std::fs::remove_dir_all(old_dir)
                    .with_context(|| format!("Failed to clean {}", old_dir.display()))?;
            }
        }

        // Clean target directories
        for old_dir in &[
            ctx.project_root.join("target/release/linux"),
            ctx.project_root.join("target/debug/linux"),
            ctx.project_root.join("target/release/Linux"),
            ctx.project_root.join("target/debug/Linux"),
            ctx.project_root.join("target/linux"),
            ctx.project_root.join("target/Linux"),
        ] {
            if old_dir.exists() {
                std::fs::remove_dir_all(old_dir)
                    .with_context(|| format!("Failed to clean {}", old_dir.display()))?;
            }
        }

        Ok(())
    }
}

impl Default for LinuxBuilder {
    fn default() -> Self {
        Self::new()
    }
}