Skip to main content

rustbridge_bundle/
builder.rs

1//! Bundle creation utilities.
2//!
3//! The [`BundleBuilder`] provides a fluent API for creating `.rbp` bundle archives.
4
5use crate::{BundleError, BundleResult, MANIFEST_FILE, Manifest, Platform};
6use minisign::SecretKey;
7use sha2::{Digest, Sha256};
8use std::fs::{self, File};
9use std::io::Write;
10use std::path::Path;
11use zip::ZipWriter;
12use zip::write::SimpleFileOptions;
13
14/// Builder for creating plugin bundles.
15///
16/// # Example
17///
18/// ```no_run
19/// use rustbridge_bundle::{BundleBuilder, Manifest, Platform};
20///
21/// let manifest = Manifest::new("my-plugin", "1.0.0");
22/// let builder = BundleBuilder::new(manifest)
23///     .add_library(Platform::LinuxX86_64, "target/release/libmyplugin.so")?
24///     .add_schema_file("schema/messages.h", "include/messages.h")?;
25///
26/// builder.write("my-plugin-1.0.0.rbp")?;
27/// # Ok::<(), rustbridge_bundle::BundleError>(())
28/// ```
29#[derive(Debug)]
30pub struct BundleBuilder {
31    manifest: Manifest,
32    files: Vec<BundleFile>,
33    signing_key: Option<(String, SecretKey)>, // (public_key_base64, secret_key)
34}
35
36/// A file to include in the bundle.
37#[derive(Debug)]
38struct BundleFile {
39    /// Path within the bundle archive.
40    archive_path: String,
41    /// File contents.
42    contents: Vec<u8>,
43}
44
45impl BundleBuilder {
46    /// Create a new bundle builder with the given manifest.
47    #[must_use]
48    pub fn new(manifest: Manifest) -> Self {
49        Self {
50            manifest,
51            files: Vec::new(),
52            signing_key: None,
53        }
54    }
55
56    /// Set the signing key for bundle signing.
57    ///
58    /// The secret key will be used to sign all library files and the manifest.
59    /// The corresponding public key will be embedded in the manifest.
60    ///
61    /// # Arguments
62    /// * `public_key_base64` - The public key in base64 format (from the .pub file)
63    /// * `secret_key` - The secret key for signing
64    pub fn with_signing_key(mut self, public_key_base64: String, secret_key: SecretKey) -> Self {
65        self.manifest.set_public_key(public_key_base64.clone());
66        self.signing_key = Some((public_key_base64, secret_key));
67        self
68    }
69
70    /// Add a platform-specific library to the bundle as the release variant.
71    ///
72    /// This reads the library file, computes its SHA256 checksum,
73    /// and updates the manifest with the platform information.
74    ///
75    /// This is a convenience method that adds the library as the `release` variant.
76    /// For other variants, use `add_library_variant` instead.
77    pub fn add_library<P: AsRef<Path>>(
78        self,
79        platform: Platform,
80        library_path: P,
81    ) -> BundleResult<Self> {
82        self.add_library_variant(platform, "release", library_path)
83    }
84
85    /// Add a variant-specific library to the bundle.
86    ///
87    /// This reads the library file, computes its SHA256 checksum,
88    /// and updates the manifest with the platform and variant information.
89    ///
90    /// # Arguments
91    /// * `platform` - Target platform
92    /// * `variant` - Variant name (e.g., "release", "debug")
93    /// * `library_path` - Path to the library file
94    pub fn add_library_variant<P: AsRef<Path>>(
95        mut self,
96        platform: Platform,
97        variant: &str,
98        library_path: P,
99    ) -> BundleResult<Self> {
100        let library_path = library_path.as_ref();
101
102        // Read the library file
103        let contents = fs::read(library_path).map_err(|e| {
104            BundleError::LibraryNotFound(format!("{}: {}", library_path.display(), e))
105        })?;
106
107        // Compute SHA256 checksum
108        let checksum = compute_sha256(&contents);
109
110        // Determine the archive path (now includes variant)
111        let file_name = library_path
112            .file_name()
113            .ok_or_else(|| {
114                BundleError::InvalidManifest(format!(
115                    "Invalid library path: {}",
116                    library_path.display()
117                ))
118            })?
119            .to_string_lossy();
120        let archive_path = format!("lib/{}/{}/{}", platform.as_str(), variant, file_name);
121
122        // Update manifest
123        self.manifest
124            .add_platform_variant(platform, variant, &archive_path, &checksum, None);
125
126        // Add to files list
127        self.files.push(BundleFile {
128            archive_path,
129            contents,
130        });
131
132        Ok(self)
133    }
134
135    /// Add a variant-specific library with build metadata.
136    ///
137    /// Similar to `add_library_variant` but also attaches build metadata
138    /// to the variant (e.g., compiler flags, features, etc.).
139    pub fn add_library_variant_with_build<P: AsRef<Path>>(
140        mut self,
141        platform: Platform,
142        variant: &str,
143        library_path: P,
144        build: serde_json::Value,
145    ) -> BundleResult<Self> {
146        let library_path = library_path.as_ref();
147
148        // Read the library file
149        let contents = fs::read(library_path).map_err(|e| {
150            BundleError::LibraryNotFound(format!("{}: {}", library_path.display(), e))
151        })?;
152
153        // Compute SHA256 checksum
154        let checksum = compute_sha256(&contents);
155
156        // Determine the archive path
157        let file_name = library_path
158            .file_name()
159            .ok_or_else(|| {
160                BundleError::InvalidManifest(format!(
161                    "Invalid library path: {}",
162                    library_path.display()
163                ))
164            })?
165            .to_string_lossy();
166        let archive_path = format!("lib/{}/{}/{}", platform.as_str(), variant, file_name);
167
168        // Update manifest with build metadata
169        self.manifest.add_platform_variant(
170            platform,
171            variant,
172            &archive_path,
173            &checksum,
174            Some(build),
175        );
176
177        // Add to files list
178        self.files.push(BundleFile {
179            archive_path,
180            contents,
181        });
182
183        Ok(self)
184    }
185
186    /// Add a schema file to the bundle.
187    ///
188    /// Schema files are stored in the `schema/` directory within the bundle.
189    ///
190    /// The schema format is automatically detected from the file extension:
191    /// - `.h` -> "c-header"
192    /// - `.json` -> "json-schema"
193    /// - Others -> "unknown"
194    pub fn add_schema_file<P: AsRef<Path>>(
195        mut self,
196        source_path: P,
197        archive_name: &str,
198    ) -> BundleResult<Self> {
199        let source_path = source_path.as_ref();
200
201        let contents = fs::read(source_path).map_err(|e| {
202            BundleError::Io(std::io::Error::new(
203                e.kind(),
204                format!(
205                    "Failed to read schema file {}: {}",
206                    source_path.display(),
207                    e
208                ),
209            ))
210        })?;
211
212        // Compute checksum
213        let checksum = compute_sha256(&contents);
214
215        // Detect format from extension
216        let format = detect_schema_format(archive_name);
217
218        let archive_path = format!("schema/{archive_name}");
219
220        // Add to manifest
221        self.manifest.add_schema(
222            archive_name.to_string(),
223            archive_path.clone(),
224            format,
225            checksum,
226            None, // No description by default
227        );
228
229        self.files.push(BundleFile {
230            archive_path,
231            contents,
232        });
233
234        Ok(self)
235    }
236
237    /// Add a documentation file to the bundle.
238    ///
239    /// Documentation files are stored in the `docs/` directory within the bundle.
240    pub fn add_doc_file<P: AsRef<Path>>(
241        mut self,
242        source_path: P,
243        archive_name: &str,
244    ) -> BundleResult<Self> {
245        let source_path = source_path.as_ref();
246
247        let contents = fs::read(source_path).map_err(|e| {
248            BundleError::Io(std::io::Error::new(
249                e.kind(),
250                format!("Failed to read doc file {}: {}", source_path.display(), e),
251            ))
252        })?;
253
254        let archive_path = format!("docs/{archive_name}");
255
256        self.files.push(BundleFile {
257            archive_path,
258            contents,
259        });
260
261        Ok(self)
262    }
263
264    /// Add raw bytes as a file in the bundle.
265    pub fn add_bytes(mut self, archive_path: &str, contents: Vec<u8>) -> Self {
266        self.files.push(BundleFile {
267            archive_path: archive_path.to_string(),
268            contents,
269        });
270        self
271    }
272
273    /// Set the build information for the bundle.
274    pub fn with_build_info(mut self, build_info: crate::BuildInfo) -> Self {
275        self.manifest.set_build_info(build_info);
276        self
277    }
278
279    /// Set the SBOM paths.
280    pub fn with_sbom(mut self, sbom: crate::Sbom) -> Self {
281        self.manifest.set_sbom(sbom);
282        self
283    }
284
285    /// Add a notices file to the bundle.
286    ///
287    /// The file will be stored in the `docs/` directory.
288    pub fn add_notices_file<P: AsRef<Path>>(mut self, source_path: P) -> BundleResult<Self> {
289        let source_path = source_path.as_ref();
290
291        let contents = fs::read(source_path).map_err(|e| {
292            BundleError::Io(std::io::Error::new(
293                e.kind(),
294                format!(
295                    "Failed to read notices file {}: {}",
296                    source_path.display(),
297                    e
298                ),
299            ))
300        })?;
301
302        let archive_path = "docs/NOTICES.txt".to_string();
303        self.manifest.set_notices(archive_path.clone());
304
305        self.files.push(BundleFile {
306            archive_path,
307            contents,
308        });
309
310        Ok(self)
311    }
312
313    /// Add the plugin's license file to the bundle.
314    ///
315    /// The file will be stored in the `legal/` directory as `LICENSE`.
316    /// This is for the plugin's own license, not third-party notices.
317    pub fn add_license_file<P: AsRef<Path>>(mut self, source_path: P) -> BundleResult<Self> {
318        let source_path = source_path.as_ref();
319
320        let contents = fs::read(source_path).map_err(|e| {
321            BundleError::Io(std::io::Error::new(
322                e.kind(),
323                format!(
324                    "Failed to read license file {}: {}",
325                    source_path.display(),
326                    e
327                ),
328            ))
329        })?;
330
331        let archive_path = "legal/LICENSE".to_string();
332        self.manifest.set_license_file(archive_path.clone());
333
334        self.files.push(BundleFile {
335            archive_path,
336            contents,
337        });
338
339        Ok(self)
340    }
341
342    /// Add an SBOM file to the bundle.
343    ///
344    /// The file will be stored in the `sbom/` directory.
345    pub fn add_sbom_file<P: AsRef<Path>>(
346        mut self,
347        source_path: P,
348        archive_name: &str,
349    ) -> BundleResult<Self> {
350        let source_path = source_path.as_ref();
351
352        let contents = fs::read(source_path).map_err(|e| {
353            BundleError::Io(std::io::Error::new(
354                e.kind(),
355                format!("Failed to read SBOM file {}: {}", source_path.display(), e),
356            ))
357        })?;
358
359        let archive_path = format!("sbom/{archive_name}");
360
361        self.files.push(BundleFile {
362            archive_path,
363            contents,
364        });
365
366        Ok(self)
367    }
368
369    /// Write the bundle to a file.
370    pub fn write<P: AsRef<Path>>(self, output_path: P) -> BundleResult<()> {
371        let output_path = output_path.as_ref();
372
373        // Validate the manifest
374        self.manifest.validate()?;
375
376        // Create the ZIP file
377        let file = File::create(output_path)?;
378        let mut zip = ZipWriter::new(file);
379        let options =
380            SimpleFileOptions::default().compression_method(zip::CompressionMethod::Deflated);
381
382        // Write manifest.json
383        let manifest_json = self.manifest.to_json()?;
384        zip.start_file(MANIFEST_FILE, options)?;
385        zip.write_all(manifest_json.as_bytes())?;
386
387        // Sign and write manifest.json.minisig if signing is enabled
388        if let Some((ref _public_key, ref secret_key)) = self.signing_key {
389            let signature = sign_data(secret_key, manifest_json.as_bytes())?;
390            zip.start_file(format!("{MANIFEST_FILE}.minisig"), options)?;
391            zip.write_all(signature.as_bytes())?;
392        }
393
394        // Write all other files
395        for bundle_file in &self.files {
396            zip.start_file(&bundle_file.archive_path, options)?;
397            zip.write_all(&bundle_file.contents)?;
398
399            // Sign library files if signing is enabled
400            if let Some((ref _public_key, ref secret_key)) = self.signing_key {
401                // Only sign library files (in lib/ directory)
402                if bundle_file.archive_path.starts_with("lib/") {
403                    let signature = sign_data(secret_key, &bundle_file.contents)?;
404                    let sig_path = format!("{}.minisig", bundle_file.archive_path);
405                    zip.start_file(&sig_path, options)?;
406                    zip.write_all(signature.as_bytes())?;
407                }
408            }
409        }
410
411        zip.finish()?;
412
413        Ok(())
414    }
415
416    /// Get the current manifest (for inspection).
417    #[must_use]
418    pub fn manifest(&self) -> &Manifest {
419        &self.manifest
420    }
421
422    /// Get a mutable reference to the manifest (for modification).
423    pub fn manifest_mut(&mut self) -> &mut Manifest {
424        &mut self.manifest
425    }
426}
427
428/// Compute SHA256 hash of data and return as hex string.
429pub fn compute_sha256(data: &[u8]) -> String {
430    let mut hasher = Sha256::new();
431    hasher.update(data);
432    let result = hasher.finalize();
433    hex::encode(result)
434}
435
436/// Verify SHA256 checksum of data.
437pub fn verify_sha256(data: &[u8], expected: &str) -> bool {
438    let actual = compute_sha256(data);
439
440    // Handle both "sha256:xxx" and raw "xxx" formats
441    let expected_hex = expected.strip_prefix("sha256:").unwrap_or(expected);
442
443    actual == expected_hex
444}
445
446/// Detect schema format from file extension.
447fn detect_schema_format(filename: &str) -> String {
448    if filename.ends_with(".h") || filename.ends_with(".hpp") {
449        "c-header".to_string()
450    } else if filename.ends_with(".json") {
451        "json-schema".to_string()
452    } else {
453        "unknown".to_string()
454    }
455}
456
457/// Sign data using a minisign secret key.
458///
459/// Returns the signature in minisign format (base64-encoded).
460fn sign_data(secret_key: &SecretKey, data: &[u8]) -> BundleResult<String> {
461    let signature_box = minisign::sign(
462        None, // No public key needed for signing
463        secret_key, data, None, // No trusted comment
464        None, // No untrusted comment
465    )
466    .map_err(|e| BundleError::Io(std::io::Error::other(format!("Failed to sign data: {e}"))))?;
467
468    Ok(signature_box.to_string())
469}
470
471#[cfg(test)]
472mod tests {
473    #![allow(non_snake_case)]
474
475    use super::*;
476    use tempfile::TempDir;
477
478    #[test]
479    fn compute_sha256___returns_consistent_hash() {
480        let data = b"hello world";
481        let hash1 = compute_sha256(data);
482        let hash2 = compute_sha256(data);
483
484        assert_eq!(hash1, hash2);
485        assert_eq!(hash1.len(), 64); // SHA256 is 32 bytes = 64 hex chars
486    }
487
488    #[test]
489    fn compute_sha256___different_data___different_hash() {
490        let hash1 = compute_sha256(b"hello");
491        let hash2 = compute_sha256(b"world");
492
493        assert_ne!(hash1, hash2);
494    }
495
496    #[test]
497    fn compute_sha256___empty_data___returns_valid_hash() {
498        let hash = compute_sha256(b"");
499
500        assert_eq!(hash.len(), 64);
501        // Known SHA256 of empty string
502        assert_eq!(
503            hash,
504            "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
505        );
506    }
507
508    #[test]
509    fn verify_sha256___accepts_valid_checksum() {
510        let data = b"hello world";
511        let checksum = compute_sha256(data);
512
513        assert!(verify_sha256(data, &checksum));
514        assert!(verify_sha256(data, &format!("sha256:{checksum}")));
515    }
516
517    #[test]
518    fn verify_sha256___rejects_invalid_checksum() {
519        let data = b"hello world";
520
521        assert!(!verify_sha256(data, "invalid"));
522        assert!(!verify_sha256(data, "sha256:invalid"));
523    }
524
525    #[test]
526    fn verify_sha256___case_sensitive___rejects_uppercase() {
527        let data = b"hello world";
528        let checksum = compute_sha256(data).to_uppercase();
529
530        assert!(!verify_sha256(data, &checksum));
531    }
532
533    #[test]
534    fn BundleBuilder___add_bytes___adds_file() {
535        let manifest = Manifest::new("test", "1.0.0");
536        let builder = BundleBuilder::new(manifest).add_bytes("test.txt", b"hello".to_vec());
537
538        assert_eq!(builder.files.len(), 1);
539        assert_eq!(builder.files[0].archive_path, "test.txt");
540        assert_eq!(builder.files[0].contents, b"hello");
541    }
542
543    #[test]
544    fn BundleBuilder___add_bytes___multiple_files() {
545        let manifest = Manifest::new("test", "1.0.0");
546        let builder = BundleBuilder::new(manifest)
547            .add_bytes("file1.txt", b"content1".to_vec())
548            .add_bytes("file2.txt", b"content2".to_vec())
549            .add_bytes("dir/file3.txt", b"content3".to_vec());
550
551        assert_eq!(builder.files.len(), 3);
552    }
553
554    #[test]
555    fn BundleBuilder___add_library___nonexistent_file___returns_error() {
556        let manifest = Manifest::new("test", "1.0.0");
557        let result = BundleBuilder::new(manifest)
558            .add_library(Platform::LinuxX86_64, "/nonexistent/path/libtest.so");
559
560        assert!(result.is_err());
561        let err = result.unwrap_err();
562        assert!(matches!(err, BundleError::LibraryNotFound(_)));
563        assert!(err.to_string().contains("/nonexistent/path/libtest.so"));
564    }
565
566    #[test]
567    fn BundleBuilder___add_library___valid_file___computes_checksum() {
568        let temp_dir = TempDir::new().unwrap();
569        let lib_path = temp_dir.path().join("libtest.so");
570        fs::write(&lib_path, b"fake library").unwrap();
571
572        let manifest = Manifest::new("test", "1.0.0");
573        let builder = BundleBuilder::new(manifest)
574            .add_library(Platform::LinuxX86_64, &lib_path)
575            .unwrap();
576
577        let platform_info = builder
578            .manifest
579            .get_platform(Platform::LinuxX86_64)
580            .unwrap();
581        let release = platform_info.release().unwrap();
582        assert!(release.checksum.starts_with("sha256:"));
583        assert_eq!(release.library, "lib/linux-x86_64/release/libtest.so");
584    }
585
586    #[test]
587    fn BundleBuilder___add_library_variant___adds_multiple_variants() {
588        let temp_dir = TempDir::new().unwrap();
589        let release_lib = temp_dir.path().join("libtest_release.so");
590        let debug_lib = temp_dir.path().join("libtest_debug.so");
591        fs::write(&release_lib, b"release library").unwrap();
592        fs::write(&debug_lib, b"debug library").unwrap();
593
594        let manifest = Manifest::new("test", "1.0.0");
595        let builder = BundleBuilder::new(manifest)
596            .add_library_variant(Platform::LinuxX86_64, "release", &release_lib)
597            .unwrap()
598            .add_library_variant(Platform::LinuxX86_64, "debug", &debug_lib)
599            .unwrap();
600
601        let platform_info = builder
602            .manifest
603            .get_platform(Platform::LinuxX86_64)
604            .unwrap();
605
606        assert!(platform_info.has_variant("release"));
607        assert!(platform_info.has_variant("debug"));
608
609        let release = platform_info.variant("release").unwrap();
610        let debug = platform_info.variant("debug").unwrap();
611
612        assert_eq!(
613            release.library,
614            "lib/linux-x86_64/release/libtest_release.so"
615        );
616        assert_eq!(debug.library, "lib/linux-x86_64/debug/libtest_debug.so");
617    }
618
619    #[test]
620    fn BundleBuilder___add_library___multiple_platforms() {
621        let temp_dir = TempDir::new().unwrap();
622
623        let linux_lib = temp_dir.path().join("libtest.so");
624        let macos_lib = temp_dir.path().join("libtest.dylib");
625        fs::write(&linux_lib, b"linux lib").unwrap();
626        fs::write(&macos_lib, b"macos lib").unwrap();
627
628        let manifest = Manifest::new("test", "1.0.0");
629        let builder = BundleBuilder::new(manifest)
630            .add_library(Platform::LinuxX86_64, &linux_lib)
631            .unwrap()
632            .add_library(Platform::DarwinAarch64, &macos_lib)
633            .unwrap();
634
635        assert!(builder.manifest.supports_platform(Platform::LinuxX86_64));
636        assert!(builder.manifest.supports_platform(Platform::DarwinAarch64));
637        assert!(!builder.manifest.supports_platform(Platform::WindowsX86_64));
638    }
639
640    #[test]
641    fn BundleBuilder___add_schema_file___nonexistent___returns_error() {
642        let manifest = Manifest::new("test", "1.0.0");
643        let result =
644            BundleBuilder::new(manifest).add_schema_file("/nonexistent/schema.h", "schema.h");
645
646        assert!(result.is_err());
647    }
648
649    #[test]
650    fn BundleBuilder___add_schema_file___detects_c_header_format() {
651        let temp_dir = TempDir::new().unwrap();
652        let schema_path = temp_dir.path().join("messages.h");
653        fs::write(&schema_path, b"#include <stdint.h>").unwrap();
654
655        let manifest = Manifest::new("test", "1.0.0");
656        let builder = BundleBuilder::new(manifest)
657            .add_schema_file(&schema_path, "messages.h")
658            .unwrap();
659
660        let schema_info = builder.manifest.schemas.get("messages.h").unwrap();
661        assert_eq!(schema_info.format, "c-header");
662    }
663
664    #[test]
665    fn BundleBuilder___add_schema_file___detects_json_schema_format() {
666        let temp_dir = TempDir::new().unwrap();
667        let schema_path = temp_dir.path().join("schema.json");
668        fs::write(&schema_path, b"{}").unwrap();
669
670        let manifest = Manifest::new("test", "1.0.0");
671        let builder = BundleBuilder::new(manifest)
672            .add_schema_file(&schema_path, "schema.json")
673            .unwrap();
674
675        let schema_info = builder.manifest.schemas.get("schema.json").unwrap();
676        assert_eq!(schema_info.format, "json-schema");
677    }
678
679    #[test]
680    fn BundleBuilder___add_schema_file___unknown_format() {
681        let temp_dir = TempDir::new().unwrap();
682        let schema_path = temp_dir.path().join("schema.xyz");
683        fs::write(&schema_path, b"content").unwrap();
684
685        let manifest = Manifest::new("test", "1.0.0");
686        let builder = BundleBuilder::new(manifest)
687            .add_schema_file(&schema_path, "schema.xyz")
688            .unwrap();
689
690        let schema_info = builder.manifest.schemas.get("schema.xyz").unwrap();
691        assert_eq!(schema_info.format, "unknown");
692    }
693
694    #[test]
695    fn BundleBuilder___write___invalid_manifest___returns_error() {
696        let temp_dir = TempDir::new().unwrap();
697        let output_path = temp_dir.path().join("test.rbp");
698
699        // Manifest without any platforms is invalid
700        let manifest = Manifest::new("test", "1.0.0");
701        let result = BundleBuilder::new(manifest).write(&output_path);
702
703        assert!(result.is_err());
704        let err = result.unwrap_err();
705        assert!(matches!(err, BundleError::InvalidManifest(_)));
706    }
707
708    #[test]
709    fn BundleBuilder___write___creates_valid_bundle() {
710        let temp_dir = TempDir::new().unwrap();
711        let lib_path = temp_dir.path().join("libtest.so");
712        let output_path = temp_dir.path().join("test.rbp");
713        fs::write(&lib_path, b"fake library").unwrap();
714
715        let manifest = Manifest::new("test", "1.0.0");
716        BundleBuilder::new(manifest)
717            .add_library(Platform::LinuxX86_64, &lib_path)
718            .unwrap()
719            .write(&output_path)
720            .unwrap();
721
722        assert!(output_path.exists());
723
724        // Verify it's a valid ZIP
725        let file = File::open(&output_path).unwrap();
726        let archive = zip::ZipArchive::new(file).unwrap();
727        assert!(archive.len() >= 2); // manifest + library
728    }
729
730    #[test]
731    fn BundleBuilder___manifest_mut___allows_modification() {
732        let manifest = Manifest::new("test", "1.0.0");
733        let mut builder = BundleBuilder::new(manifest);
734
735        builder.manifest_mut().plugin.description = Some("Modified".to_string());
736
737        assert_eq!(
738            builder.manifest().plugin.description,
739            Some("Modified".to_string())
740        );
741    }
742
743    #[test]
744    fn detect_schema_format___hpp_extension___returns_c_header() {
745        assert_eq!(detect_schema_format("types.hpp"), "c-header");
746    }
747
748    #[test]
749    fn BundleBuilder___add_license_file___adds_file_to_legal_dir() {
750        let temp_dir = TempDir::new().unwrap();
751        let license_path = temp_dir.path().join("LICENSE");
752        fs::write(&license_path, b"MIT License\n\nCopyright...").unwrap();
753
754        let manifest = Manifest::new("test", "1.0.0");
755        let builder = BundleBuilder::new(manifest)
756            .add_license_file(&license_path)
757            .unwrap();
758
759        // Check file was added
760        assert_eq!(builder.files.len(), 1);
761        assert_eq!(builder.files[0].archive_path, "legal/LICENSE");
762
763        // Check manifest was updated
764        assert_eq!(builder.manifest.get_license_file(), Some("legal/LICENSE"));
765    }
766
767    #[test]
768    fn BundleBuilder___add_license_file___nonexistent___returns_error() {
769        let manifest = Manifest::new("test", "1.0.0");
770        let result = BundleBuilder::new(manifest).add_license_file("/nonexistent/LICENSE");
771
772        assert!(result.is_err());
773    }
774}