rustbridge-cli 1.0.1

Build tool and code generator for rustbridge
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
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
//! Pack command - auto-detect plugin project and create a bundle.
//!
//! Reads name/version from `Cargo.toml`, detects the platform, finds built libraries,
//! and delegates to `bundle::create()`.

use anyhow::{Context, Result};
use rustbridge_bundle::Platform;
use serde::Deserialize;
use std::path::{Path, PathBuf};
use std::time::SystemTime;
use yansi::{Condition, Paint, Style};

/// Yellow bold style for warnings, active only when stderr is a terminal.
static WARN: Style = Style::new()
    .yellow()
    .bold()
    .whenever(Condition::STDERR_IS_TTY);

/// Minimal Cargo.toml representation for plugin detection.
#[derive(Deserialize)]
struct CargoToml {
    package: Option<PackageInfo>,
    lib: Option<LibInfo>,
}

#[derive(Deserialize)]
struct PackageInfo {
    name: Option<String>,
    version: Option<toml::Value>,
    metadata: Option<PackageMetadata>,
}

#[derive(Deserialize)]
struct PackageMetadata {
    rustbridge: Option<RustbridgeMetadata>,
}

#[derive(Deserialize, Default)]
struct RustbridgeMetadata {
    #[serde(rename = "schema-source")]
    schema_source: Option<String>,
    #[serde(rename = "header-source")]
    header_source: Option<String>,
}

#[derive(Deserialize)]
struct LibInfo {
    name: Option<String>,
    #[serde(rename = "crate-type")]
    crate_type: Option<Vec<String>>,
}

/// Minimal workspace Cargo.toml representation for version resolution.
#[derive(Deserialize)]
struct WorkspaceCargoToml {
    workspace: Option<WorkspaceInfo>,
}

#[derive(Deserialize)]
struct WorkspaceInfo {
    package: Option<WorkspacePackageInfo>,
}

#[derive(Deserialize)]
struct WorkspacePackageInfo {
    version: Option<String>,
}

/// Detected plugin project metadata.
#[derive(Debug)]
pub struct PluginProject {
    /// Package name from Cargo.toml
    pub name: String,
    /// Resolved version string
    pub version: String,
    /// Library base name (underscored, used for filename generation)
    pub lib_name: String,
    /// Schema source from `[package.metadata.rustbridge]` (e.g. `"src/lib.rs:schema.json"`)
    pub schema_source: Option<String>,
    /// Header source from `[package.metadata.rustbridge]` (e.g. `"src/lib.rs:messages.h"`)
    pub header_source: Option<String>,
}

impl PluginProject {
    /// Detect plugin project from a directory containing Cargo.toml.
    pub fn detect(project_dir: &Path) -> Result<Self> {
        let cargo_toml_path = project_dir.join("Cargo.toml");
        if !cargo_toml_path.exists() {
            anyhow::bail!(
                "No Cargo.toml found in {}. Run this command from a plugin project directory.",
                project_dir.display()
            );
        }

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

        let cargo_toml: CargoToml =
            toml::from_str(&contents).context("Failed to parse Cargo.toml")?;

        // Validate crate-type includes cdylib
        let lib_info = cargo_toml.lib.as_ref();
        let has_cdylib = lib_info
            .and_then(|l| l.crate_type.as_ref())
            .is_some_and(|types| types.iter().any(|t| t == "cdylib"));

        if !has_cdylib {
            anyhow::bail!(
                "Expected [lib] crate-type to include \"cdylib\" in {}. \
                 This command only works with plugin projects.",
                cargo_toml_path.display()
            );
        }

        // Extract package name
        let package = cargo_toml
            .package
            .as_ref()
            .ok_or_else(|| anyhow::anyhow!("Missing [package] section in Cargo.toml"))?;

        let name = package
            .name
            .clone()
            .ok_or_else(|| anyhow::anyhow!("Missing package.name in Cargo.toml"))?;

        // Resolve version
        let version = resolve_version(package, project_dir)?;

        // Determine library base name: [lib] name or derive from package name
        let lib_name = lib_info
            .and_then(|l| l.name.clone())
            .unwrap_or_else(|| name.replace('-', "_"));

        // Extract [package.metadata.rustbridge] fields
        let rb_meta = package
            .metadata
            .as_ref()
            .and_then(|m| m.rustbridge.as_ref());
        let schema_source = rb_meta.and_then(|r| r.schema_source.clone());
        let header_source = rb_meta.and_then(|r| r.header_source.clone());

        Ok(Self {
            name,
            version,
            lib_name,
            schema_source,
            header_source,
        })
    }
}

/// Resolve version from package info, following workspace inheritance.
fn resolve_version(package: &PackageInfo, project_dir: &Path) -> Result<String> {
    let version_value = package
        .version
        .as_ref()
        .ok_or_else(|| anyhow::anyhow!("Missing package.version in Cargo.toml"))?;

    match version_value {
        toml::Value::String(v) => Ok(v.clone()),
        toml::Value::Table(t) => {
            if t.get("workspace").and_then(|v| v.as_bool()) == Some(true) {
                find_workspace_version(project_dir)
            } else {
                anyhow::bail!("Unsupported package.version format in Cargo.toml")
            }
        }
        _ => anyhow::bail!("Unsupported package.version format in Cargo.toml"),
    }
}

/// Walk up parent directories to find the workspace root Cargo.toml and read its version.
fn find_workspace_version(start_dir: &Path) -> Result<String> {
    let mut dir = start_dir.to_path_buf();

    loop {
        // Check parent directory
        if !dir.pop() {
            anyhow::bail!(
                "Could not find workspace root with [workspace.package] version. \
                 Searched from {}",
                start_dir.display()
            );
        }

        let candidate = dir.join("Cargo.toml");
        if !candidate.exists() {
            continue;
        }

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

        let workspace_toml: WorkspaceCargoToml = match toml::from_str(&contents) {
            Ok(parsed) => parsed,
            Err(_) => continue,
        };

        if let Some(workspace) = workspace_toml.workspace
            && let Some(pkg) = workspace.package
            && let Some(version) = pkg.version
        {
            return Ok(version);
        }
    }
}

/// Return the default signing key path (`~/.rustbridge/signing.key`).
fn default_signing_key_path() -> Result<PathBuf> {
    let home = std::env::var("HOME")
        .or_else(|_| std::env::var("USERPROFILE"))
        .context("Could not determine home directory")?;
    Ok(PathBuf::from(home).join(".rustbridge").join("signing.key"))
}

/// Derive the output bundle path.
fn derive_pack_output(project_dir: &Path, name: &str, version: &str, dev: bool) -> PathBuf {
    let suffix = if dev { "-dev" } else { "" };
    project_dir
        .join("target")
        .join("bundle")
        .join(format!("{name}-{version}{suffix}.rbp"))
}

/// Find the cargo target directory by walking up to the workspace root.
///
/// Cargo puts build artifacts in the workspace root's `target/` directory,
/// not in the member crate's directory.
fn find_target_dir(project_dir: &Path) -> PathBuf {
    // Check if there's a workspace root above us
    let mut dir = project_dir.to_path_buf();
    loop {
        if !dir.pop() {
            // No workspace root found, use project_dir
            return project_dir.join("target");
        }

        let candidate = dir.join("Cargo.toml");
        if !candidate.exists() {
            continue;
        }

        // Check if it has a [workspace] section
        if let Ok(contents) = std::fs::read_to_string(&candidate)
            && let Ok(parsed) = toml::from_str::<WorkspaceCargoToml>(&contents)
            && parsed.workspace.is_some()
        {
            return dir.join("target");
        }
    }
}

/// Format a `SystemTime` as `YYYY-MM-DD HH:MM:SS UTC`.
fn format_system_time(time: SystemTime) -> String {
    let duration = time
        .duration_since(SystemTime::UNIX_EPOCH)
        .unwrap_or_default();
    let secs = duration.as_secs();

    // Convert epoch seconds to calendar date/time (UTC)
    let days = secs / 86400;
    let time_of_day = secs % 86400;
    let hours = time_of_day / 3600;
    let minutes = (time_of_day % 3600) / 60;
    let seconds = time_of_day % 60;

    // Days since 1970-01-01 to (year, month, day) using a standard algorithm
    let (year, month, day) = {
        // Algorithm from Howard Hinnant's date library (public domain)
        let z = days as i64 + 719468;
        let era = if z >= 0 { z } else { z - 146096 } / 146097;
        let doe = (z - era * 146097) as u64;
        let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365;
        let y = yoe as i64 + era * 400;
        let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
        let mp = (5 * doy + 2) / 153;
        let d = doy - (153 * mp + 2) / 5 + 1;
        let m = if mp < 10 { mp + 3 } else { mp - 9 };
        let y = if m <= 2 { y + 1 } else { y };
        (y, m as u32, d as u32)
    };

    format!("{year:04}-{month:02}-{day:02} {hours:02}:{minutes:02}:{seconds:02} UTC")
}

/// Check if a library file is older than source files, warning if stale.
///
/// Compares the modification time of `lib_path` against `Cargo.toml` and
/// all `.rs` files under `src/`. Prints a warning to stderr if any source
/// file is newer than the library.
fn check_library_staleness(project_dir: &Path, lib_path: &Path, variant_label: &str) {
    let lib_mtime = match lib_path.metadata().and_then(|m| m.modified()) {
        Ok(t) => t,
        Err(_) => return,
    };

    let mut newest_source: Option<(PathBuf, SystemTime)> = None;

    let mut consider = |path: PathBuf| {
        if let Ok(meta) = path.metadata()
            && let Ok(mtime) = meta.modified()
            && newest_source.as_ref().is_none_or(|(_, prev)| mtime > *prev)
        {
            newest_source = Some((path, mtime));
        }
    };

    // Check Cargo.toml
    let cargo_toml = project_dir.join("Cargo.toml");
    if cargo_toml.exists() {
        consider(cargo_toml);
    }

    // Check build.rs
    let build_rs = project_dir.join("build.rs");
    if build_rs.exists() {
        consider(build_rs);
    }

    // Check all .rs files under src/
    let src_dir = project_dir.join("src");
    if src_dir.is_dir() {
        for entry in walkdir::WalkDir::new(&src_dir)
            .into_iter()
            .filter_map(|e| e.ok())
        {
            let path = entry.into_path();
            if path.extension().is_some_and(|ext| ext == "rs") {
                consider(path);
            }
        }
    }

    if let Some((newest_path, newest_mtime)) = newest_source
        && newest_mtime > lib_mtime
    {
        let lib_display = lib_path.display();
        let src_display = newest_path
            .strip_prefix(project_dir)
            .unwrap_or(&newest_path)
            .display();
        let lib_time_str = format_system_time(lib_mtime);
        let newest_time_str = format_system_time(newest_mtime);

        let build_hint = if variant_label == "Release" {
            "cargo build --release"
        } else {
            "cargo build"
        };

        let header = format!("Warning: {variant_label} library appears out of date.");
        eprintln!();
        eprintln!("{}", header.paint(WARN));
        eprintln!("  Library:       {lib_display}  ({lib_time_str})");
        eprintln!("  Newest source: {src_display}  ({newest_time_str})");
        eprintln!("  Run: {build_hint}");
        eprintln!();
    }
}

/// Run the pack command.
#[allow(clippy::too_many_arguments)]
pub fn run_pack(
    dev: bool,
    sign_key: Option<String>,
    no_sign: bool,
    schema_source: Option<String>,
    header_source: Option<String>,
) -> Result<()> {
    // Validate flag combinations
    if sign_key.is_some() && no_sign {
        anyhow::bail!("Conflicting flags: --sign-key and --no-sign cannot be used together");
    }

    let cwd = std::env::current_dir().context("Failed to get current directory")?;
    let project = PluginProject::detect(&cwd)?;

    // Merge CLI flags with Cargo.toml metadata (CLI wins)
    let effective_schema = schema_source.or_else(|| {
        if let Some(ref s) = project.schema_source {
            println!("  Schema source (from Cargo.toml): {s}");
        }
        project.schema_source.clone()
    });
    let effective_header = header_source.or_else(|| {
        if let Some(ref h) = project.header_source {
            println!("  Header source (from Cargo.toml): {h}");
        }
        project.header_source.clone()
    });

    let platform = Platform::current().ok_or_else(|| {
        anyhow::anyhow!(
            "Unsupported platform: {}-{}",
            std::env::consts::OS,
            std::env::consts::ARCH
        )
    })?;
    let platform_str = platform.to_string();

    println!("Packing plugin: {} v{}", project.name, project.version);
    println!("  Platform: {platform_str}");
    println!(
        "  Library name: {}",
        platform.library_name(&project.lib_name)
    );

    let target_dir = find_target_dir(&cwd);
    let lib_filename = platform.library_name(&project.lib_name);

    // Build library list
    let mut libraries: Vec<(String, String, String)> = Vec::new();

    // Always include release library
    let release_lib = target_dir.join("release").join(&lib_filename);
    if !release_lib.exists() {
        anyhow::bail!(
            "Release library not found: {}\n\
             Run: cargo build --release",
            release_lib.display()
        );
    }
    check_library_staleness(&cwd, &release_lib, "Release");
    libraries.push((
        platform_str.clone(),
        "release".to_string(),
        release_lib.to_string_lossy().to_string(),
    ));
    println!("  Release library: {}", release_lib.display());

    // Include debug library if dev mode
    if dev {
        let debug_lib = target_dir.join("debug").join(&lib_filename);
        if !debug_lib.exists() {
            anyhow::bail!(
                "Debug library not found: {}\n\
                 Run: cargo build",
                debug_lib.display()
            );
        }
        check_library_staleness(&cwd, &debug_lib, "Debug");
        libraries.push((
            platform_str,
            "debug".to_string(),
            debug_lib.to_string_lossy().to_string(),
        ));
        println!("  Debug library: {}", debug_lib.display());
    }

    // Find SBOM files
    let mut sbom_files: Vec<(String, String)> = Vec::new();
    for sbom_name in &["sbom.cdx.json", "sbom.spdx.json"] {
        let sbom_path = cwd.join(sbom_name);
        if sbom_path.exists() {
            println!("  SBOM: {sbom_name}");
            sbom_files.push((
                sbom_path.to_string_lossy().to_string(),
                (*sbom_name).to_string(),
            ));
        }
    }

    // Find LICENSE file
    let license_path = find_license_file(&cwd);
    if let Some(ref lp) = license_path {
        println!("  License: {}", lp.display());
    }

    // Resolve signing key for release mode
    let resolved_sign_key = if dev || no_sign {
        None
    } else {
        match sign_key {
            Some(path) => Some(path),
            None => {
                let default_key = default_signing_key_path()?;
                if default_key.exists() {
                    println!("  Signing with: {}", default_key.display());
                    Some(default_key.to_string_lossy().to_string())
                } else {
                    eprintln!(
                        "{} No signing key found at {}. Bundle will not be signed. \
                         Use 'rustbridge keygen' to generate a key.",
                        "Warning:".paint(WARN),
                        default_key.display()
                    );
                    None
                }
            }
        }
    };

    // Create output directory
    let output = derive_pack_output(&cwd, &project.name, &project.version, dev);
    if let Some(parent) = output.parent() {
        std::fs::create_dir_all(parent)
            .with_context(|| format!("Failed to create directory: {}", parent.display()))?;
    }

    println!("  Output: {}", output.display());

    // Delegate to bundle::create
    crate::bundle::create(
        &project.name,
        &project.version,
        &libraries,
        Some(output.to_string_lossy().to_string()),
        &[], // schema_files (handled via generate flags)
        resolved_sign_key,
        effective_header, // generate_header
        effective_schema, // generate_schema
        None,             // notices
        license_path.map(|p| p.to_string_lossy().to_string()),
        false, // no_metadata
        &sbom_files,
        &[], // custom_metadata
    )?;

    Ok(())
}

/// Find a LICENSE file in the project directory.
fn find_license_file(project_dir: &Path) -> Option<PathBuf> {
    for name in &[
        "LICENSE",
        "LICENSE.md",
        "LICENSE.txt",
        "LICENSE-MIT",
        "LICENSE-APACHE",
    ] {
        let path = project_dir.join(name);
        if path.exists() {
            return Some(path);
        }
    }
    None
}

#[cfg(test)]
mod tests {
    #![allow(non_snake_case)]

    use super::*;
    use std::fs;
    use tempfile::TempDir;

    fn write_cargo_toml(dir: &Path, content: &str) {
        fs::write(dir.join("Cargo.toml"), content).unwrap();
    }

    #[test]
    fn detect___standalone_project___extracts_name_and_version() {
        let temp = TempDir::new().unwrap();
        write_cargo_toml(
            temp.path(),
            r#"
[package]
name = "my-plugin"
version = "2.1.0"

[lib]
crate-type = ["cdylib"]
"#,
        );

        let project = PluginProject::detect(temp.path()).unwrap();

        assert_eq!(project.name, "my-plugin");
        assert_eq!(project.version, "2.1.0");
    }

    #[test]
    fn detect___custom_lib_name___uses_lib_name() {
        let temp = TempDir::new().unwrap();
        write_cargo_toml(
            temp.path(),
            r#"
[package]
name = "my-plugin"
version = "1.0.0"

[lib]
name = "custom_name"
crate-type = ["cdylib"]
"#,
        );

        let project = PluginProject::detect(temp.path()).unwrap();

        assert_eq!(project.lib_name, "custom_name");
    }

    #[test]
    fn detect___workspace_version___resolves_from_workspace_root() {
        let temp = TempDir::new().unwrap();

        // Create workspace root
        write_cargo_toml(
            temp.path(),
            r#"
[workspace]
members = ["crates/my-plugin"]

[workspace.package]
version = "3.0.0"
"#,
        );

        // Create member directory
        let member_dir = temp.path().join("crates").join("my-plugin");
        fs::create_dir_all(&member_dir).unwrap();
        write_cargo_toml(
            &member_dir,
            r#"
[package]
name = "my-plugin"
version.workspace = true

[lib]
crate-type = ["cdylib"]
"#,
        );

        let project = PluginProject::detect(&member_dir).unwrap();

        assert_eq!(project.version, "3.0.0");
    }

    #[test]
    fn detect___no_cargo_toml___returns_error() {
        let temp = TempDir::new().unwrap();

        let result = PluginProject::detect(temp.path());

        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(err.contains("No Cargo.toml"), "Error was: {err}");
    }

    #[test]
    fn detect___no_cdylib_crate_type___returns_error() {
        let temp = TempDir::new().unwrap();
        write_cargo_toml(
            temp.path(),
            r#"
[package]
name = "my-lib"
version = "1.0.0"

[lib]
crate-type = ["rlib"]
"#,
        );

        let result = PluginProject::detect(temp.path());

        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(err.contains("cdylib"), "Error was: {err}");
    }

    #[test]
    fn detect___hyphenated_name___converts_to_underscores() {
        let temp = TempDir::new().unwrap();
        write_cargo_toml(
            temp.path(),
            r#"
[package]
name = "my-cool-plugin"
version = "1.0.0"

[lib]
crate-type = ["cdylib"]
"#,
        );

        let project = PluginProject::detect(temp.path()).unwrap();

        assert_eq!(project.lib_name, "my_cool_plugin");
    }

    #[test]
    fn output_path___release_mode___no_dev_suffix() {
        let dir = Path::new("/project");

        let path = derive_pack_output(dir, "my-plugin", "1.0.0", false);

        assert_eq!(
            path,
            PathBuf::from("/project/target/bundle/my-plugin-1.0.0.rbp")
        );
    }

    #[test]
    fn output_path___dev_mode___has_dev_suffix() {
        let dir = Path::new("/project");

        let path = derive_pack_output(dir, "my-plugin", "1.0.0", true);

        assert_eq!(
            path,
            PathBuf::from("/project/target/bundle/my-plugin-1.0.0-dev.rbp")
        );
    }

    #[test]
    fn detect___metadata_schema_source___extracts_value() {
        let temp = TempDir::new().unwrap();
        write_cargo_toml(
            temp.path(),
            r#"
[package]
name = "my-plugin"
version = "1.0.0"

[package.metadata.rustbridge]
schema-source = "src/lib.rs:schema.json"

[lib]
crate-type = ["cdylib"]
"#,
        );

        let project = PluginProject::detect(temp.path()).unwrap();

        assert_eq!(
            project.schema_source.as_deref(),
            Some("src/lib.rs:schema.json")
        );
    }

    #[test]
    fn detect___metadata_header_source___extracts_value() {
        let temp = TempDir::new().unwrap();
        write_cargo_toml(
            temp.path(),
            r#"
[package]
name = "my-plugin"
version = "1.0.0"

[package.metadata.rustbridge]
header-source = "src/binary_messages.rs:messages.h"

[lib]
crate-type = ["cdylib"]
"#,
        );

        let project = PluginProject::detect(temp.path()).unwrap();

        assert_eq!(
            project.header_source.as_deref(),
            Some("src/binary_messages.rs:messages.h")
        );
    }

    #[test]
    fn detect___no_metadata___fields_are_none() {
        let temp = TempDir::new().unwrap();
        write_cargo_toml(
            temp.path(),
            r#"
[package]
name = "my-plugin"
version = "1.0.0"

[lib]
crate-type = ["cdylib"]
"#,
        );

        let project = PluginProject::detect(temp.path()).unwrap();

        assert!(project.schema_source.is_none());
        assert!(project.header_source.is_none());
    }

    #[test]
    fn staleness___library_older_than_source___prints_warning() {
        use filetime::FileTime;

        let temp = TempDir::new().unwrap();

        // Create project structure
        fs::write(temp.path().join("Cargo.toml"), "[package]\nname = \"x\"\n").unwrap();
        let src_dir = temp.path().join("src");
        fs::create_dir_all(&src_dir).unwrap();
        fs::write(src_dir.join("lib.rs"), "// source").unwrap();

        // Create a fake library file
        let lib_path = temp.path().join("libx.so");
        fs::write(&lib_path, "fake lib").unwrap();

        // Set lib to be old (year 2020), source to be new (year 2025)
        let old_time = FileTime::from_unix_time(1_577_836_800, 0); // 2020-01-01
        let new_time = FileTime::from_unix_time(1_737_849_600, 0); // 2025-01-26

        filetime::set_file_mtime(&lib_path, old_time).unwrap();
        filetime::set_file_mtime(src_dir.join("lib.rs"), new_time).unwrap();

        // The function prints to stderr via eprintln!, so we verify
        // the staleness condition is detected by checking timestamps directly
        let lib_mtime = fs::metadata(&lib_path).unwrap().modified().unwrap();
        let src_mtime = fs::metadata(src_dir.join("lib.rs"))
            .unwrap()
            .modified()
            .unwrap();

        assert!(src_mtime > lib_mtime, "Source should be newer than library");

        // Call the function (warning goes to stderr; no panic = success)
        check_library_staleness(temp.path(), &lib_path, "Release");
    }

    #[test]
    fn staleness___library_newer_than_source___no_warning() {
        use filetime::FileTime;

        let temp = TempDir::new().unwrap();

        // Create project structure
        fs::write(temp.path().join("Cargo.toml"), "[package]\nname = \"x\"\n").unwrap();
        let src_dir = temp.path().join("src");
        fs::create_dir_all(&src_dir).unwrap();
        fs::write(src_dir.join("lib.rs"), "// source").unwrap();

        // Create a fake library file
        let lib_path = temp.path().join("libx.so");
        fs::write(&lib_path, "fake lib").unwrap();

        // Set source to be old, lib to be new
        let old_time = FileTime::from_unix_time(1_577_836_800, 0); // 2020-01-01
        let new_time = FileTime::from_unix_time(1_737_849_600, 0); // 2025-01-26

        filetime::set_file_mtime(src_dir.join("lib.rs"), old_time).unwrap();
        filetime::set_file_mtime(temp.path().join("Cargo.toml"), old_time).unwrap();
        filetime::set_file_mtime(&lib_path, new_time).unwrap();

        // Verify the condition: lib should be newer than all sources
        let lib_mtime = fs::metadata(&lib_path).unwrap().modified().unwrap();
        let src_mtime = fs::metadata(src_dir.join("lib.rs"))
            .unwrap()
            .modified()
            .unwrap();

        assert!(lib_mtime > src_mtime, "Library should be newer than source");

        // Call the function (no warning expected; no panic = success)
        check_library_staleness(temp.path(), &lib_path, "Release");
    }

    #[test]
    fn staleness___no_src_directory___no_warning() {
        use filetime::FileTime;

        let temp = TempDir::new().unwrap();

        // Create project with Cargo.toml but no src/ directory
        fs::write(temp.path().join("Cargo.toml"), "[package]\nname = \"x\"\n").unwrap();

        let lib_path = temp.path().join("libx.so");
        fs::write(&lib_path, "fake lib").unwrap();

        // Set lib to be old so Cargo.toml alone could trigger a warning,
        // but the point is the function should not panic without src/
        let old_time = FileTime::from_unix_time(1_577_836_800, 0);
        filetime::set_file_mtime(&lib_path, old_time).unwrap();

        // Call the function (should not panic even without src/ directory)
        check_library_staleness(temp.path(), &lib_path, "Release");
    }
}