ccgo 3.4.3

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
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
//! Vendor command implementation
//!
//! Copies all dependencies to a local vendor/ directory for offline builds.
//! This ensures reproducible builds without network access.

use std::fs;
use std::io::Read;
use std::path::{Path, PathBuf};

use anyhow::{bail, Context, Result};
use clap::Args;
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use walkdir::WalkDir;

use crate::config::CcgoConfig;
use crate::lockfile::{LockedPackage, Lockfile, LOCKFILE_NAME};

/// Default vendor directory name
pub const VENDOR_DIR: &str = "vendor";

/// Vendor metadata filename
pub const VENDOR_TOML: &str = ".vendor.toml";

/// Directories to exclude when vendoring
const EXCLUDE_DIRS: &[&str] = &[
    ".git",
    ".svn",
    ".hg",
    "target",
    "build",
    "cmake_build",
    ".ccgo",
    "node_modules",
    "__pycache__",
    ".cache",
    "vendor",
    "bin",
];

/// Vendor all dependencies to project local directory
#[derive(Args, Debug)]
pub struct VendorCommand {
    /// Don't delete unused dependencies from vendor/
    #[arg(long)]
    pub no_delete: bool,

    /// Sync vendor/ with lockfile, re-vendoring changed dependencies
    #[arg(long)]
    pub sync: bool,

    /// Only verify vendor/ integrity without modifying
    #[arg(long)]
    pub verify: bool,

    /// Custom vendor directory path
    #[arg(long, default_value = VENDOR_DIR)]
    pub path: String,

    /// Remove .git directories from vendored dependencies
    #[arg(long, default_value = "true")]
    pub strip_git: bool,
}

/// Vendor metadata file structure
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct VendorConfig {
    /// Vendor config version
    pub version: u32,

    /// Metadata
    #[serde(default)]
    pub metadata: VendorMetadata,

    /// Vendored packages
    #[serde(default, rename = "package")]
    pub packages: Vec<VendoredPackage>,
}

/// Vendor metadata
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct VendorMetadata {
    /// When vendor was last run
    #[serde(skip_serializing_if = "Option::is_none")]
    pub generated_at: Option<String>,

    /// CCGO version
    #[serde(skip_serializing_if = "Option::is_none")]
    pub ccgo_version: Option<String>,

    /// Source lockfile hash for change detection
    #[serde(skip_serializing_if = "Option::is_none")]
    pub lockfile_hash: Option<String>,
}

/// A vendored package entry
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct VendoredPackage {
    /// Package name
    pub name: String,

    /// Package version
    pub version: String,

    /// Original source
    pub source: String,

    /// When this package was vendored
    #[serde(skip_serializing_if = "Option::is_none")]
    pub vendored_at: Option<String>,

    /// Checksum of vendored content
    #[serde(skip_serializing_if = "Option::is_none")]
    pub checksum: Option<String>,
}

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

impl VendorConfig {
    /// Create new vendor config
    pub fn new() -> Self {
        Self {
            version: 1,
            metadata: VendorMetadata {
                generated_at: Some(chrono::Local::now().to_rfc3339()),
                ccgo_version: Some(env!("CARGO_PKG_VERSION").to_string()),
                lockfile_hash: None,
            },
            packages: Vec::new(),
        }
    }

    /// Load vendor config from path
    pub fn load(vendor_dir: &Path) -> Result<Option<Self>> {
        let config_path = vendor_dir.join(VENDOR_TOML);
        if !config_path.exists() {
            return Ok(None);
        }

        let content = fs::read_to_string(&config_path)
            .with_context(|| format!("Failed to read {}", config_path.display()))?;

        let config: Self = toml::from_str(&content)
            .with_context(|| format!("Failed to parse {}", config_path.display()))?;

        Ok(Some(config))
    }

    /// Save vendor config
    pub fn save(&self, vendor_dir: &Path) -> Result<()> {
        let config_path = vendor_dir.join(VENDOR_TOML);

        let mut content = String::new();
        content.push_str("# Auto-generated by ccgo vendor\n");
        content.push_str("# Do not edit manually\n\n");
        content.push_str(&format!("version = {}\n\n", self.version));

        content.push_str("[metadata]\n");
        if let Some(ref generated_at) = self.metadata.generated_at {
            content.push_str(&format!("generated_at = \"{}\"\n", generated_at));
        }
        if let Some(ref ccgo_version) = self.metadata.ccgo_version {
            content.push_str(&format!("ccgo_version = \"{}\"\n", ccgo_version));
        }
        if let Some(ref lockfile_hash) = self.metadata.lockfile_hash {
            content.push_str(&format!("lockfile_hash = \"{}\"\n", lockfile_hash));
        }
        content.push('\n');

        for pkg in &self.packages {
            content.push_str("[[package]]\n");
            content.push_str(&format!("name = \"{}\"\n", pkg.name));
            content.push_str(&format!("version = \"{}\"\n", pkg.version));
            content.push_str(&format!("source = \"{}\"\n", pkg.source));
            if let Some(ref vendored_at) = pkg.vendored_at {
                content.push_str(&format!("vendored_at = \"{}\"\n", vendored_at));
            }
            if let Some(ref checksum) = pkg.checksum {
                content.push_str(&format!("checksum = \"{}\"\n", checksum));
            }
            content.push('\n');
        }

        fs::write(&config_path, content)
            .with_context(|| format!("Failed to write {}", config_path.display()))?;

        Ok(())
    }

    /// Get a vendored package by name
    pub fn get_package(&self, name: &str) -> Option<&VendoredPackage> {
        self.packages.iter().find(|p| p.name == name)
    }

    /// Add or update a package
    pub fn upsert_package(&mut self, pkg: VendoredPackage) {
        if let Some(existing) = self.packages.iter_mut().find(|p| p.name == pkg.name) {
            *existing = pkg;
        } else {
            self.packages.push(pkg);
        }
        self.packages.sort_by(|a, b| a.name.cmp(&b.name));
    }
}

impl VendorCommand {
    /// Execute the vendor command
    pub fn execute(self, verbose: bool) -> Result<()> {
        println!("{}", "=".repeat(80));
        println!("CCGO Vendor - Vendor Dependencies for Offline Builds");
        println!("{}", "=".repeat(80));

        let project_dir = std::env::current_dir().context("Failed to get current directory")?;
        let vendor_dir = project_dir.join(&self.path);

        println!("\nProject directory: {}", project_dir.display());
        println!("Vendor directory: {}", vendor_dir.display());

        // Load CCGO.toml
        let config = CcgoConfig::load().context("Failed to load CCGO.toml")?;

        // Load lockfile (required for vendor)
        let lockfile = Lockfile::load(&project_dir)?.ok_or_else(|| {
            anyhow::anyhow!(
                "No {} found. Run 'ccgo fetch' first to generate a lockfile.",
                LOCKFILE_NAME
            )
        })?;

        let dependencies = &config.dependencies;
        if dependencies.is_empty() {
            println!("\n   ℹ️  No dependencies to vendor");
            return Ok(());
        }

        // Load existing vendor config
        let existing_vendor_config = VendorConfig::load(&vendor_dir)?;

        // Verify mode
        if self.verify {
            return self.verify_vendor(&vendor_dir, &lockfile, existing_vendor_config.as_ref());
        }

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

        println!("\n📦 Vendoring {} dependencies...", lockfile.packages.len());

        let ccgo_home = Self::get_ccgo_home();
        let mut vendor_config = VendorConfig::new();
        let mut vendored_count = 0;
        let mut skipped_count = 0;
        let mut failed_count = 0;

        // Track which packages we're vendoring (for cleanup)
        let mut vendored_names: Vec<String> = Vec::new();

        for locked_pkg in &lockfile.packages {
            vendored_names.push(locked_pkg.name.clone());

            // Check if already vendored and up-to-date
            if !self.sync {
                if let Some(ref existing) = existing_vendor_config {
                    if let Some(existing_pkg) = existing.get_package(&locked_pkg.name) {
                        if existing_pkg.source == locked_pkg.source {
                            if verbose {
                                println!("   ⏭️  {} already vendored", locked_pkg.name);
                            }
                            vendor_config.upsert_package(existing_pkg.clone());
                            skipped_count += 1;
                            continue;
                        }
                    }
                }
            }

            match self.vendor_package(locked_pkg, &project_dir, &vendor_dir, &ccgo_home, verbose) {
                Ok(vendored_pkg) => {
                    println!("   ✓ Vendored {}", locked_pkg.name);
                    vendor_config.upsert_package(vendored_pkg);
                    vendored_count += 1;
                }
                Err(e) => {
                    eprintln!("   ✗ Failed to vendor {}: {}", locked_pkg.name, e);
                    failed_count += 1;
                }
            }
        }

        // Clean up unused dependencies
        if !self.no_delete {
            self.cleanup_unused(&vendor_dir, &vendored_names, verbose)?;
        }

        // Save vendor config
        vendor_config.metadata.generated_at = Some(chrono::Local::now().to_rfc3339());
        vendor_config.save(&vendor_dir)?;

        // Summary
        println!("\n{}", "=".repeat(80));
        println!("Vendor Summary");
        println!("{}", "=".repeat(80));
        println!("\n✓ Vendored: {}", vendored_count);
        if skipped_count > 0 {
            println!("⏭️  Skipped (already vendored): {}", skipped_count);
        }
        if failed_count > 0 {
            println!("✗ Failed: {}", failed_count);
        }
        println!("\n📁 Vendor directory: {}", vendor_dir.display());

        // Usage hint
        println!("\n💡 To use vendored dependencies:");
        println!("   - Dependencies are now in {}/", self.path);
        println!("   - Commit vendor/ to version control for offline builds");

        if failed_count > 0 {
            bail!("{} package(s) failed to vendor", failed_count);
        }

        Ok(())
    }

    /// Vendor a single package
    fn vendor_package(
        &self,
        locked_pkg: &LockedPackage,
        project_dir: &Path,
        vendor_dir: &Path,
        ccgo_home: &Path,
        verbose: bool,
    ) -> Result<VendoredPackage> {
        let target_dir = vendor_dir.join(&locked_pkg.name);

        // Remove existing if present
        if target_dir.exists() {
            fs::remove_dir_all(&target_dir).with_context(|| {
                format!(
                    "Failed to remove existing vendor dir: {}",
                    target_dir.display()
                )
            })?;
        }

        // Determine source and copy
        let (source_type, source_path) = locked_pkg.parse_source();

        match source_type {
            crate::lockfile::SourceType::Git => {
                self.vendor_from_git(locked_pkg, &target_dir, ccgo_home, verbose)?;
            }
            crate::lockfile::SourceType::Path => {
                self.vendor_from_path(&source_path, &target_dir, project_dir, verbose)?;
            }
            _ => {
                bail!("Unsupported source type for vendoring: {:?}", source_type);
            }
        }

        // Strip .git directory if requested
        if self.strip_git {
            let git_dir = target_dir.join(".git");
            if git_dir.exists() {
                if verbose {
                    println!("      Removing .git directory");
                }
                fs::remove_dir_all(&git_dir).ok();
            }
        }

        // Calculate checksum of vendored content
        let checksum = Self::calculate_directory_checksum(&target_dir)?;

        Ok(VendoredPackage {
            name: locked_pkg.name.clone(),
            version: locked_pkg.version.clone(),
            source: locked_pkg.source.clone(),
            vendored_at: Some(chrono::Local::now().to_rfc3339()),
            checksum: Some(checksum),
        })
    }

    /// Vendor from git cache
    fn vendor_from_git(
        &self,
        locked_pkg: &LockedPackage,
        target_dir: &Path,
        ccgo_home: &Path,
        verbose: bool,
    ) -> Result<()> {
        // Parse git URL from source
        let (_, git_url) = locked_pkg.parse_source();

        // Find in registry cache
        let hash_input = format!("{}:{}", locked_pkg.name, git_url);
        let hash = format!("{:x}", md5::compute(hash_input.as_bytes()));
        let registry_name = format!("{}-{}", locked_pkg.name, &hash[..16]);
        let registry_path = ccgo_home.join("registry").join(&registry_name);

        if !registry_path.exists() {
            // Need to clone first
            if verbose {
                println!("      Cloning {} (not in cache)", git_url);
            }

            let registry_dir = ccgo_home.join("registry");
            fs::create_dir_all(&registry_dir)?;

            let mut cmd = std::process::Command::new("git");
            cmd.args(["clone", &git_url, registry_path.to_string_lossy().as_ref()]);

            let output = cmd.output().context("Failed to execute git clone")?;
            if !output.status.success() {
                bail!(
                    "Git clone failed: {}",
                    String::from_utf8_lossy(&output.stderr)
                );
            }

            // Checkout specific revision if available
            if let Some(ref git_info) = locked_pkg.git {
                let checkout = std::process::Command::new("git")
                    .args(["checkout", &git_info.revision])
                    .current_dir(&registry_path)
                    .output()
                    .context("Failed to checkout revision")?;
                if !checkout.status.success() {
                    bail!(
                        "Git checkout failed: {}",
                        String::from_utf8_lossy(&checkout.stderr)
                    );
                }
            }
        }

        // Copy from cache to vendor
        if verbose {
            println!("      Copying from cache: {}", registry_path.display());
        }
        Self::copy_dir_recursive(&registry_path, target_dir)?;

        Ok(())
    }

    /// Vendor from local path
    fn vendor_from_path(
        &self,
        path: &str,
        target_dir: &Path,
        project_dir: &Path,
        verbose: bool,
    ) -> Result<()> {
        let source_path = if Path::new(path).is_absolute() {
            PathBuf::from(path)
        } else {
            project_dir.join(path)
        };

        if !source_path.exists() {
            bail!("Source path does not exist: {}", source_path.display());
        }

        if verbose {
            println!("      Copying from: {}", source_path.display());
        }

        Self::copy_dir_recursive(&source_path, target_dir)?;

        Ok(())
    }

    /// Recursively copy directory, excluding build artifacts
    fn copy_dir_recursive(src: &Path, dst: &Path) -> Result<()> {
        fs::create_dir_all(dst)?;

        for entry in fs::read_dir(src)? {
            let entry = entry?;
            let src_path = entry.path();
            let dst_path = dst.join(entry.file_name());
            let name = entry.file_name().to_string_lossy().to_string();

            // Skip excluded directories
            if src_path.is_dir() && Self::should_exclude(&name) {
                continue;
            }

            if src_path.is_dir() {
                Self::copy_dir_recursive(&src_path, &dst_path)?;
            } else {
                fs::copy(&src_path, &dst_path)?;
            }
        }

        Ok(())
    }

    /// Check if a directory should be excluded from vendoring
    fn should_exclude(name: &str) -> bool {
        EXCLUDE_DIRS.contains(&name) || name.starts_with('.')
    }

    /// Calculate SHA-256 checksum of a directory
    fn calculate_directory_checksum(dir: &Path) -> Result<String> {
        let mut hasher = Sha256::new();
        let mut files: Vec<PathBuf> = Vec::new();

        // Collect all files (sorted for deterministic hashing)
        for entry in WalkDir::new(dir)
            .follow_links(false)
            .into_iter()
            .filter_entry(|e| {
                let name = e.file_name().to_string_lossy();
                !Self::should_exclude(&name)
            })
            .filter_map(|e| e.ok())
        {
            if entry.file_type().is_file() {
                files.push(entry.path().to_path_buf());
            }
        }

        // Sort files for deterministic order
        files.sort();

        // Hash each file's relative path and content
        for file_path in files {
            // Hash relative path
            let relative_path = file_path.strip_prefix(dir).unwrap_or(&file_path);
            hasher.update(relative_path.to_string_lossy().as_bytes());

            // Hash file content
            let mut file = fs::File::open(&file_path)
                .with_context(|| format!("Failed to open file: {}", file_path.display()))?;
            let mut buffer = Vec::new();
            file.read_to_end(&mut buffer)
                .with_context(|| format!("Failed to read file: {}", file_path.display()))?;
            hasher.update(&buffer);
        }

        let result = hasher.finalize();
        Ok(format!("sha256:{:x}", result))
    }

    /// Clean up unused vendored dependencies
    fn cleanup_unused(&self, vendor_dir: &Path, keep: &[String], verbose: bool) -> Result<()> {
        if !vendor_dir.exists() {
            return Ok(());
        }

        for entry in fs::read_dir(vendor_dir)? {
            let entry = entry?;
            let path = entry.path();

            if !path.is_dir() {
                continue;
            }

            let name = entry.file_name().to_string_lossy().to_string();

            // Skip hidden directories and vendor config
            if name.starts_with('.') {
                continue;
            }

            if !keep.contains(&name) {
                if verbose {
                    println!("   🗑️  Removing unused: {}", name);
                }
                fs::remove_dir_all(&path)
                    .with_context(|| format!("Failed to remove {}", path.display()))?;
            }
        }

        Ok(())
    }

    /// Verify vendor directory integrity
    fn verify_vendor(
        &self,
        vendor_dir: &Path,
        lockfile: &Lockfile,
        vendor_config: Option<&VendorConfig>,
    ) -> Result<()> {
        println!("\n🔍 Verifying vendor directory...");

        let vendor_config = vendor_config
            .ok_or_else(|| anyhow::anyhow!("No {} found in vendor directory", VENDOR_TOML))?;

        let mut missing = Vec::new();
        let mut outdated = Vec::new();
        let mut corrupted = Vec::new();

        for locked_pkg in &lockfile.packages {
            let pkg_dir = vendor_dir.join(&locked_pkg.name);

            if !pkg_dir.exists() {
                missing.push(locked_pkg.name.clone());
                continue;
            }

            if let Some(vendored) = vendor_config.get_package(&locked_pkg.name) {
                // Check source match
                if vendored.source != locked_pkg.source {
                    outdated.push(locked_pkg.name.clone());
                    continue;
                }

                // Verify checksum if available
                if let Some(ref expected_checksum) = vendored.checksum {
                    match Self::calculate_directory_checksum(&pkg_dir) {
                        Ok(actual_checksum) => {
                            if &actual_checksum != expected_checksum {
                                corrupted.push(locked_pkg.name.clone());
                            }
                        }
                        Err(_) => {
                            corrupted.push(locked_pkg.name.clone());
                        }
                    }
                }
            } else {
                // In vendor dir but not in config
                missing.push(locked_pkg.name.clone());
            }
        }

        if missing.is_empty() && outdated.is_empty() && corrupted.is_empty() {
            println!("\n✓ Vendor directory is up-to-date");
            println!("  {} packages verified", lockfile.packages.len());
            Ok(())
        } else {
            println!("\n⚠️  Vendor directory needs update:");
            if !missing.is_empty() {
                println!("   Missing: {}", missing.join(", "));
            }
            if !outdated.is_empty() {
                println!("   Outdated: {}", outdated.join(", "));
            }
            if !corrupted.is_empty() {
                println!("   Corrupted: {}", corrupted.join(", "));
            }
            println!("\n   Run 'ccgo vendor --sync' to fix");
            bail!("Vendor verification failed");
        }
    }

    /// Get CCGO home directory
    fn get_ccgo_home() -> PathBuf {
        directories::BaseDirs::new()
            .map(|dirs| dirs.home_dir().to_path_buf())
            .unwrap_or_else(|| PathBuf::from("."))
            .join(".ccgo")
    }
}