cargo-cross 1.5.0

A cargo subcommand for cross-compilation, no need docker!
Documentation
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
//! Platform-specific cross-compilation setup modules

pub mod android;
pub mod darwin;
pub mod freebsd;
pub mod ios;
pub mod linux;
pub mod netbsd;
pub mod windows;

use crate::cli::Args;
use crate::config::{Arch, HostPlatform, Libc, Os, TargetConfig};
use crate::env::{CMakeToolchain, CrossEnv};
use crate::error::{CrossError, Result};
use path_slash::PathExt as _;
use std::collections::HashMap;
use std::fs;
use std::path::{Path, PathBuf};
use tokio::process::Command;

/// Convert a path to CMake-compatible format (forward slashes)
///
/// `CMake` interprets backslashes as escape sequences (e.g., `\U` in `\Users`),
/// so all paths must use forward slashes. Uses the `path-slash` crate which
/// properly handles:
/// - Windows drive letters (C:\ -> C:/)
/// - UNC paths (\\server\share -> //server/share)
/// - Already forward-slashed paths (no-op)
#[must_use]
pub fn to_cmake_path(path: &Path) -> String {
    path.to_slash_lossy().into_owned()
}

/// Mark that this target should use a generated generic CMake toolchain file.
pub fn setup_generic_cmake_toolchain(env: &mut CrossEnv) {
    env.set_generic_cmake_toolchain();
}

/// Return the target-specific CMake toolchain environment variable name.
#[must_use]
pub fn cmake_toolchain_env_key(target: &str) -> String {
    format!("CMAKE_TOOLCHAIN_FILE_{}", target.replace('-', "_"))
}

/// Check if a CMake toolchain file has already been configured externally.
#[must_use]
pub fn has_preconfigured_cmake_toolchain(env: &HashMap<String, String>, target: &str) -> bool {
    let target_lower = target.replace('-', "_");
    let target_hyphen = format!("CMAKE_TOOLCHAIN_FILE_{target}");
    let target_underscore = format!("CMAKE_TOOLCHAIN_FILE_{target_lower}");
    let vars = [
        target_hyphen.as_str(),
        target_underscore.as_str(),
        "TARGET_CMAKE_TOOLCHAIN_FILE",
        "CMAKE_TOOLCHAIN_FILE",
    ];

    vars.iter().any(|key| {
        env.get(*key).is_some_and(|value| !value.is_empty())
            || std::env::var_os(key).is_some_and(|value| !value.is_empty())
    })
}

/// Resolve a path relative to the current working directory.
pub fn resolve_path_from_current_dir(path: &Path) -> Result<PathBuf> {
    if path.is_absolute() {
        return Ok(path.to_path_buf());
    }

    let base = std::env::current_dir().map_err(|source| CrossError::IoError {
        message: "Failed to determine current working directory".to_string(),
        source,
    })?;

    Ok(base.join(path))
}

/// Generate or select the appropriate CMake toolchain file path for this target.
pub fn prepare_cmake_toolchain_file(
    args: &Args,
    target_config: &TargetConfig,
    cross_env: &CrossEnv,
) -> Result<Option<PathBuf>> {
    match cross_env.cmake_toolchain.as_ref() {
        Some(CMakeToolchain::Custom(path)) => Ok(Some(path.clone())),
        Some(CMakeToolchain::Generic) => {
            let path = write_generic_cmake_toolchain_file(args, target_config, cross_env)?;
            Ok(Some(path))
        }
        None => Ok(None),
    }
}

fn write_generic_cmake_toolchain_file(
    args: &Args,
    target_config: &TargetConfig,
    cross_env: &CrossEnv,
) -> Result<PathBuf> {
    let output_dir = resolve_path_from_current_dir(&args.cross_compiler_dir)?.join("cmake");
    fs::create_dir_all(&output_dir).map_err(|source| CrossError::IoError {
        message: format!(
            "Failed to create CMake toolchain directory at {}",
            output_dir.display()
        ),
        source,
    })?;

    let path = output_dir.join(format!("{}.cmake", target_config.target));
    let content = render_cmake_toolchain_file(target_config, cross_env);
    fs::write(&path, content).map_err(|source| CrossError::IoError {
        message: format!("Failed to write CMake toolchain file at {}", path.display()),
        source,
    })?;

    Ok(path)
}

/// Render a generic CMake toolchain file that matches `cmake-rs` defaults and adds
/// any toolchain information cargo-cross has already discovered.
#[must_use]
pub fn render_cmake_toolchain_file(target_config: &TargetConfig, cross_env: &CrossEnv) -> String {
    let mut lines = vec![format!(
        "# Auto-generated by cargo-cross for {}",
        target_config.target
    )];

    let (system_name, system_processor) = cmake_system_name_and_processor(target_config);
    push_cmake_set(&mut lines, "CMAKE_SYSTEM_NAME", system_name);
    push_cmake_set(&mut lines, "CMAKE_SYSTEM_PROCESSOR", system_processor);

    if let Some(osx_arch) = cmake_osx_architecture(target_config) {
        push_cmake_set(&mut lines, "CMAKE_OSX_ARCHITECTURES", osx_arch);
    }

    let c_compiler = cross_env
        .cc
        .as_deref()
        .map(|tool| resolve_tool_path(tool, &cross_env.path));
    let cxx_compiler = cross_env
        .cxx
        .as_deref()
        .map(|tool| resolve_tool_path(tool, &cross_env.path));
    let ar = cross_env
        .ar
        .as_deref()
        .map(|tool| resolve_tool_path(tool, &cross_env.path));
    let linker = cross_env
        .linker
        .as_deref()
        .map(|tool| resolve_tool_path(tool, &cross_env.path));

    if let Some(path) = c_compiler.as_deref() {
        push_cmake_set_path(&mut lines, "CMAKE_C_COMPILER", path);
    }
    if let Some(path) = cxx_compiler.as_deref() {
        push_cmake_set_path(&mut lines, "CMAKE_CXX_COMPILER", path);
    }
    if let Some(path) = ar.as_deref() {
        push_cmake_set_path(&mut lines, "CMAKE_AR", path);
    }
    if let Some(path) = linker.as_deref() {
        push_cmake_set_path(&mut lines, "CMAKE_LINKER", path);
    }

    if let Some(root) = cross_env
        .sysroot
        .as_deref()
        .or(cross_env.sdkroot.as_deref())
    {
        push_cmake_set_path(&mut lines, "CMAKE_SYSROOT", root);
    }

    if let Some(sdkroot) = cross_env.sdkroot.as_deref() {
        push_cmake_set_path(&mut lines, "CMAKE_OSX_SYSROOT", sdkroot);
    }

    let mut content = lines.join("\n");
    content.push('\n');
    content
}

fn cmake_system_name_and_processor(target_config: &TargetConfig) -> (&'static str, &'static str) {
    let os = rust_cfg_target_os(target_config);
    let arch = rust_cfg_target_arch(target_config);

    match (os, arch) {
        ("android", "arm") => ("Android", "armv7-a"),
        ("android", "x86") => ("Android", "i686"),
        ("android", arch) => ("Android", arch),
        ("dragonfly", arch) => ("DragonFly", arch),
        ("macos", "aarch64") => ("Darwin", "arm64"),
        ("macos", arch) => ("Darwin", arch),
        ("freebsd", "x86_64") => ("FreeBSD", "amd64"),
        ("freebsd", arch) => ("FreeBSD", arch),
        ("fuchsia", arch) => ("Fuchsia", arch),
        ("haiku", arch) => ("Haiku", arch),
        ("ios", "aarch64") => ("iOS", "arm64"),
        ("ios", arch) => ("iOS", arch),
        ("linux", arch) => {
            let name = "Linux";
            match arch {
                "powerpc" => (name, "ppc"),
                "powerpc64" => (name, "ppc64"),
                "powerpc64le" => (name, "ppc64le"),
                _ => (name, arch),
            }
        }
        ("netbsd", arch) => ("NetBSD", arch),
        ("openbsd", "x86_64") => ("OpenBSD", "amd64"),
        ("openbsd", arch) => ("OpenBSD", arch),
        ("solaris", arch) => ("SunOS", arch),
        ("tvos", "aarch64") => ("tvOS", "arm64"),
        ("tvos", arch) => ("tvOS", arch),
        ("visionos", "aarch64") => ("visionOS", "arm64"),
        ("visionos", arch) => ("visionOS", arch),
        ("watchos", "aarch64") => ("watchOS", "arm64"),
        ("watchos", arch) => ("watchOS", arch),
        ("windows", "x86_64") => ("Windows", "AMD64"),
        ("windows", "x86") => ("Windows", "X86"),
        ("windows", "aarch64") => ("Windows", "ARM64"),
        ("none", arch) => ("Generic", arch),
        (os, arch) => (os, arch),
    }
}

fn rust_cfg_target_os(target_config: &TargetConfig) -> &'static str {
    match target_config.os {
        Os::Linux => "linux",
        Os::Windows => "windows",
        Os::FreeBsd => "freebsd",
        Os::NetBsd => "netbsd",
        Os::Darwin => "macos",
        Os::Ios | Os::IosSim => "ios",
        Os::Android => "android",
    }
}

fn rust_cfg_target_arch(target_config: &TargetConfig) -> &'static str {
    match target_config.arch {
        Arch::Aarch64 | Arch::Aarch64Be | Arch::Arm64e => "aarch64",
        Arch::Armv5 | Arch::Armv6 | Arch::Armv7 => "arm",
        Arch::I586 | Arch::I686 => "x86",
        Arch::Mips | Arch::Mipsel => "mips",
        Arch::Mipsisa32r6 | Arch::Mipsisa32r6el => "mips32r6",
        Arch::Mipsisa64r6 | Arch::Mipsisa64r6el => "mips64r6",
        Arch::Mips64 | Arch::Mips64el => "mips64",
        Arch::Powerpc64 => "powerpc64",
        Arch::Powerpc64le => "powerpc64le",
        Arch::X86_64 | Arch::X86_64h => "x86_64",
        _ => target_config.arch.as_str(),
    }
}

fn cmake_osx_architecture(target_config: &TargetConfig) -> Option<&'static str> {
    match (target_config.os, target_config.arch) {
        (Os::Darwin, Arch::Aarch64) => Some("arm64"),
        (Os::Darwin, Arch::X86_64 | Arch::X86_64h) => Some("x86_64"),
        _ => None,
    }
}

fn push_cmake_set(lines: &mut Vec<String>, key: &str, value: &str) {
    lines.push(format!("set({key} \"{}\")", escape_cmake_value(value)));
}

fn push_cmake_set_path(lines: &mut Vec<String>, key: &str, value: &Path) {
    push_cmake_set(lines, key, &to_cmake_path(value));
}

fn escape_cmake_value(value: &str) -> String {
    value.replace('"', "\\\"")
}

fn resolve_tool_path(tool: &str, extra_path: &[PathBuf]) -> PathBuf {
    let tool_path = Path::new(tool);
    if tool_path.is_absolute() || tool_path.parent().is_some() {
        return tool_path.to_path_buf();
    }

    let path_dirs = std::env::var_os("PATH")
        .map(|paths| std::env::split_paths(&paths).collect::<Vec<_>>())
        .unwrap_or_default();

    extra_path
        .iter()
        .map(|dir| dir.join(tool))
        .chain(path_dirs.into_iter().map(|dir| dir.join(tool)))
        .find(|candidate| candidate.exists())
        .unwrap_or_else(|| tool_path.to_path_buf())
}

/// Setup cross-compilation environment for a target
pub async fn setup_cross_env(
    target_config: &TargetConfig,
    args: &Args,
    host: &HostPlatform,
) -> Result<CrossEnv> {
    // Skip toolchain setup if user wants to skip it
    if args.no_toolchain_setup {
        return Ok(CrossEnv::new());
    }

    match target_config.os {
        Os::Linux => linux::setup(target_config, args, host).await,
        Os::Windows => windows::setup(target_config, args, host).await,
        Os::FreeBsd => freebsd::setup(target_config, args, host).await,
        Os::NetBsd => netbsd::setup(target_config, args, host).await,
        Os::Darwin => darwin::setup(target_config, args, host).await,
        Os::Ios | Os::IosSim => ios::setup(target_config, args, host).await,
        Os::Android => android::setup(target_config, args, host).await,
    }
}

/// Get the binary prefix for a Linux target
#[must_use]
pub fn get_linux_bin_prefix(arch: Arch, libc: Libc, abi: Option<crate::config::Abi>) -> String {
    let arch_str = arch.as_str();

    // Special handling for gnu abi variants (gnusf, gnuspe, gnuabiv2, gnuabiv2hf)
    // These use combined libc+abi strings instead of separate libc and abi
    if let Some(abi_val) = abi {
        if abi_val.is_gnu_abi_variant() && libc == crate::config::Libc::Gnu {
            return format!("{arch_str}-linux-gnu{}", abi_val.as_str());
        }
    }

    let libc_str = libc.as_str();
    let abi_str = abi.map_or("", |a| a.as_str());

    format!("{arch_str}-linux-{libc_str}{abi_str}")
}

/// Get the cross-compiler folder name for a Linux target
#[must_use]
pub fn get_linux_folder_name(
    arch: Arch,
    libc: Libc,
    abi: Option<crate::config::Abi>,
    glibc_version: &str,
    default_glibc_version: &str,
) -> String {
    let arch_str = arch.as_str();

    // Special handling for gnu abi variants (gnusf, gnuspe, gnuabiv2, gnuabiv2hf)
    if let Some(abi_val) = abi {
        if abi_val.is_gnu_abi_variant() && libc == crate::config::Libc::Gnu {
            let abi_suffix = abi_val.as_str();
            // For gnu libc, folder name includes glibc version suffix (except for default version)
            let folder_suffix = if glibc_version == default_glibc_version {
                format!("gnu{abi_suffix}")
            } else {
                format!("gnu{abi_suffix}-{glibc_version}")
            };
            return format!("{arch_str}-linux-{folder_suffix}-cross");
        }
    }

    let libc_str = libc.as_str();
    let abi_str = abi.map_or("", |a| a.as_str());

    // For gnu libc, folder name includes glibc version suffix (except for default version)
    let folder_suffix = if libc == Libc::Gnu && glibc_version != default_glibc_version {
        format!("{libc_str}{abi_str}-{glibc_version}")
    } else {
        format!("{libc_str}{abi_str}")
    };

    format!("{arch_str}-linux-{folder_suffix}-cross")
}

/// Setup `CMake` generator for cross-compilation
///
/// If `cmake_generator` is specified, uses it directly.
/// On Windows, auto-detects if not specified (VS ignores CC/CXX).
/// On other platforms, only sets if explicitly specified.
pub fn setup_cmake(env: &mut CrossEnv, cmake_generator: Option<&str>, is_windows: bool) {
    // User specified generator - use it on any platform
    if let Some(g) = cmake_generator {
        env.extra_env
            .insert("CMAKE_GENERATOR".to_string(), g.to_string());
        return;
    }

    // On non-Windows, don't override CMake's default
    if !is_windows {
        return;
    }

    // Auto-detect on Windows: Ninja > MinGW Makefiles > Unix Makefiles
    let generator = if which::which("ninja").is_ok() {
        "Ninja"
    } else if which::which("mingw32-make").is_ok() {
        "MinGW Makefiles"
    } else {
        "Unix Makefiles"
    };
    env.extra_env
        .insert("CMAKE_GENERATOR".to_string(), generator.to_string());
}

/// Setup `CROSS_COMPILE` prefix for cc crate and other build systems
///
/// `CROSS_COMPILE` is a common convention used by:
/// - Linux kernel builds
/// - cc crate (Rust)
/// - Many autoconf/automake projects
///   Note: `bin_dir` should already be in PATH, so we use prefix directly.
pub fn setup_cross_compile_prefix(env: &mut CrossEnv, bin_prefix: &str) {
    // CROSS_COMPILE should be the prefix including trailing dash
    // e.g., "armv7-linux-gnueabihf-" so tools become "${CROSS_COMPILE}gcc"
    env.extra_env
        .insert("CROSS_COMPILE".to_string(), format!("{bin_prefix}-"));
}

/// Setup library path for Darwin/iOS linker binaries
///
/// The Darwin/iOS linker binaries from cross-compilation toolchains need to find their
/// shared libraries at runtime. This function adds the compiler's lib directory to
/// the library path (`LD_LIBRARY_PATH` on Linux, `DYLD_LIBRARY_PATH` on macOS).
pub fn setup_darwin_linker_library_path(env: &mut CrossEnv, compiler_dir: &Path) {
    let lib_dir = compiler_dir.join("lib");
    if lib_dir.exists() {
        env.add_library_path(&lib_dir);
    }
}

/// Get Ubuntu version from `lsb_release` (used for Linux cross-compilation downloads)
pub async fn get_ubuntu_version() -> Option<String> {
    let output = Command::new("lsb_release").arg("-rs").output().await.ok()?;

    if output.status.success() {
        let version = String::from_utf8_lossy(&output.stdout).trim().to_string();
        if version.contains('.') {
            return Some(version);
        }
    }
    None
}

/// Find an Apple SDK by version using xcrun and xcode-select
pub async fn find_apple_sdk(sdk_type: AppleSdkType, version: &str) -> Option<PathBuf> {
    let (sdk_name, platform_name) = sdk_type.names(version);

    // Try xcrun first
    if let Some(path) = try_xcrun_sdk(&sdk_name).await {
        return Some(path);
    }

    // Try xcode-select path
    if let Some(path) = try_xcode_select_sdk(platform_name, version).await {
        return Some(path);
    }

    // Search in /Applications/Xcode*.app
    search_xcode_apps_for_sdk(platform_name, version)
}

/// Apple SDK type
#[derive(Debug, Clone, Copy)]
pub enum AppleSdkType {
    MacOS,
    IPhoneOS,
    IPhoneSimulator,
}

impl AppleSdkType {
    /// Get SDK name and platform name for this SDK type
    fn names(&self, version: &str) -> (String, &'static str) {
        match self {
            Self::MacOS => (format!("macosx{version}"), "MacOSX"),
            Self::IPhoneOS => (format!("iphoneos{version}"), "iPhoneOS"),
            Self::IPhoneSimulator => (format!("iphonesimulator{version}"), "iPhoneSimulator"),
        }
    }
}

/// Try to find SDK using xcrun
async fn try_xcrun_sdk(sdk_name: &str) -> Option<PathBuf> {
    let output = Command::new("xcrun")
        .args(["--sdk", sdk_name, "--show-sdk-path"])
        .output()
        .await
        .ok()?;

    if output.status.success() {
        let path = String::from_utf8_lossy(&output.stdout).trim().to_string();
        let path = PathBuf::from(&path);
        if path.exists() {
            return Some(path);
        }
    }
    None
}

/// Try to find SDK using xcode-select path
async fn try_xcode_select_sdk(platform_name: &str, version: &str) -> Option<PathBuf> {
    let output = Command::new("xcode-select").arg("-p").output().await.ok()?;

    if output.status.success() {
        let xcode_path = String::from_utf8_lossy(&output.stdout).trim().to_string();
        let sdk_path = PathBuf::from(&xcode_path)
            .join(format!("Platforms/{platform_name}.platform/Developer/SDKs"))
            .join(format!("{platform_name}{version}.sdk"));
        if sdk_path.exists() {
            return Some(sdk_path);
        }
    }
    None
}

/// Search for SDK in /Applications/Xcode*.app directories
fn search_xcode_apps_for_sdk(platform_name: &str, version: &str) -> Option<PathBuf> {
    let entries = std::fs::read_dir("/Applications").ok()?;

    for entry in entries.filter_map(std::result::Result::ok) {
        let name = entry.file_name();
        let name_str = name.to_string_lossy();
        if name_str.starts_with("Xcode") && name_str.ends_with(".app") {
            let sdk_path = entry
                .path()
                .join(format!(
                    "Contents/Developer/Platforms/{platform_name}.platform/Developer/SDKs"
                ))
                .join(format!("{platform_name}{version}.sdk"));
            if sdk_path.exists() {
                return Some(sdk_path);
            }
        }
    }
    None
}

/// Find a file matching a glob pattern in a directory
///
/// Pattern uses glob syntax where `*` matches any sequence of characters.
/// The pattern must match the entire filename, not just a substring.
pub async fn find_file_by_pattern(dir: &Path, pattern: &str) -> Option<PathBuf> {
    let matcher = globset::Glob::new(pattern).ok()?.compile_matcher();

    let mut entries = tokio::fs::read_dir(dir).await.ok()?;
    while let Ok(Some(entry)) = entries.next_entry().await {
        let name = entry.file_name();
        if matcher.is_match(&*name.to_string_lossy()) {
            return Some(entry.path());
        }
    }

    None
}

/// Check if a filename matches a glob pattern (for testing)
#[cfg(test)]
fn glob_matches(pattern: &str, filename: &str) -> bool {
    globset::Glob::new(pattern)
        .map(|g| g.compile_matcher().is_match(filename))
        .unwrap_or(false)
}

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

    // Tests for CMake path conversion (using path-slash crate)

    #[test]
    fn test_to_cmake_path_unix() {
        // Unix paths should pass through unchanged
        let path = Path::new("/home/user/project");
        assert_eq!(to_cmake_path(path), "/home/user/project");
    }

    #[test]
    fn test_to_cmake_path_relative() {
        // Relative paths should work
        let path = Path::new("src/main.rs");
        assert_eq!(to_cmake_path(path), "src/main.rs");
    }

    #[test]
    fn test_to_cmake_path_with_dots() {
        // Paths with . and .. should be preserved
        let path = Path::new("../project/./src");
        assert_eq!(to_cmake_path(path), "../project/./src");
    }

    // Note: Windows-specific path tests (C:\, UNC paths) would only work correctly
    // when compiled and run on Windows. The path-slash crate handles these cases
    // properly on Windows by converting backslashes to forward slashes.

    #[test]
    fn test_linux_bin_prefix_musl() {
        let prefix = get_linux_bin_prefix(Arch::Aarch64, Libc::Musl, None);
        assert_eq!(prefix, "aarch64-linux-musl");
    }

    #[test]
    fn test_linux_bin_prefix_gnu() {
        let prefix = get_linux_bin_prefix(Arch::X86_64, Libc::Gnu, None);
        assert_eq!(prefix, "x86_64-linux-gnu");
    }

    #[test]
    fn test_linux_bin_prefix_with_abi() {
        let prefix = get_linux_bin_prefix(Arch::Armv7, Libc::Musl, Some(Abi::Eabihf));
        assert_eq!(prefix, "armv7-linux-musleabihf");
    }

    #[test]
    fn test_linux_folder_name_musl() {
        let name = get_linux_folder_name(Arch::Aarch64, Libc::Musl, None, "2.28", "2.28");
        assert_eq!(name, "aarch64-linux-musl-cross");
    }

    #[test]
    fn test_linux_folder_name_gnu_default() {
        let name = get_linux_folder_name(Arch::X86_64, Libc::Gnu, None, "2.28", "2.28");
        assert_eq!(name, "x86_64-linux-gnu-cross");
    }

    #[test]
    fn test_linux_folder_name_gnu_custom_version() {
        let name = get_linux_folder_name(Arch::X86_64, Libc::Gnu, None, "2.31", "2.28");
        assert_eq!(name, "x86_64-linux-gnu-2.31-cross");
    }

    #[test]
    fn test_linux_folder_name_with_abi() {
        let name = get_linux_folder_name(Arch::Armv7, Libc::Gnu, Some(Abi::Eabihf), "2.28", "2.28");
        assert_eq!(name, "armv7-linux-gnueabihf-cross");
    }

    // Tests for glob pattern matching (verifying the fix for -libc++ suffix issue)

    #[test]
    fn test_glob_matches_clang_exact() {
        // Should match the exact clang binary
        assert!(glob_matches(
            "x86_64-apple-darwin*-clang",
            "x86_64-apple-darwin25.2-clang"
        ));
    }

    #[test]
    fn test_glob_does_not_match_clang_plus_plus() {
        // Should NOT match clang++ when looking for clang
        // This was the bug: regex "x86_64-apple-darwin.*-clang" would match
        // "x86_64-apple-darwin25.2-clang++" because "clang" is a substring
        assert!(!glob_matches(
            "x86_64-apple-darwin*-clang",
            "x86_64-apple-darwin25.2-clang++"
        ));
    }

    #[test]
    fn test_glob_does_not_match_clang_with_libc_suffix() {
        // Should NOT match clang++-libc++ when looking for clang
        // This was the exact bug reported: finding "clang++-libc++" instead of "clang"
        assert!(!glob_matches(
            "x86_64-apple-darwin*-clang",
            "x86_64-apple-darwin25.2-clang++-libc++"
        ));
    }

    #[test]
    fn test_glob_matches_clang_plus_plus_exact() {
        // Should match clang++ when pattern is for clang++
        assert!(glob_matches(
            "x86_64-apple-darwin*-clang++",
            "x86_64-apple-darwin25.2-clang++"
        ));
    }

    #[test]
    fn test_glob_does_not_match_clang_plus_plus_with_suffix() {
        // Should NOT match clang++-libc++ when looking for clang++
        assert!(!glob_matches(
            "x86_64-apple-darwin*-clang++",
            "x86_64-apple-darwin25.2-clang++-libc++"
        ));
    }

    #[test]
    fn test_glob_matches_aarch64_darwin_clang() {
        assert!(glob_matches(
            "aarch64-apple-darwin*-clang",
            "aarch64-apple-darwin25.2-clang"
        ));
        assert!(!glob_matches(
            "aarch64-apple-darwin*-clang",
            "aarch64-apple-darwin25.2-clang++"
        ));
    }

    #[test]
    fn test_glob_matches_different_darwin_versions() {
        let pattern = "x86_64-apple-darwin*-clang";
        assert!(glob_matches(pattern, "x86_64-apple-darwin24.0-clang"));
        assert!(glob_matches(pattern, "x86_64-apple-darwin25.2-clang"));
        assert!(glob_matches(pattern, "x86_64-apple-darwin26.0-clang"));
        // Should not match clang++ variants
        assert!(!glob_matches(pattern, "x86_64-apple-darwin24.0-clang++"));
        assert!(!glob_matches(pattern, "x86_64-apple-darwin25.2-clang++"));
    }

    #[test]
    fn test_glob_matches_ios_compiler() {
        // iOS uses darwin11 prefix
        assert!(glob_matches(
            "arm64-apple-darwin*-clang",
            "arm64-apple-darwin11-clang"
        ));
        assert!(!glob_matches(
            "arm64-apple-darwin*-clang",
            "arm64-apple-darwin11-clang++"
        ));
    }

    #[test]
    fn test_x32_folder_names() {
        use crate::config::{Abi, Arch, Libc};

        // Test x32 gnu with glibc version
        let folder = get_linux_folder_name(Arch::X86_64, Libc::Gnu, Some(Abi::X32), "2.17", "");
        assert_eq!(folder, "x86_64-linux-gnux32-2.17-cross");

        // Test x32 gnu with default (empty) version
        let folder = get_linux_folder_name(Arch::X86_64, Libc::Gnu, Some(Abi::X32), "", "");
        assert_eq!(folder, "x86_64-linux-gnux32-cross");
    }

    #[test]
    fn test_x32_bin_prefix() {
        use crate::config::{Abi, Arch, Libc};

        // Test x32 gnu bin prefix
        let bin_prefix = get_linux_bin_prefix(Arch::X86_64, Libc::Gnu, Some(Abi::X32));
        assert_eq!(bin_prefix, "x86_64-linux-gnux32");
    }

    #[test]
    fn test_aarch64_be_targets() {
        use crate::config::{Arch, Libc};

        // Test aarch64_be musl
        let bin_prefix = get_linux_bin_prefix(Arch::Aarch64Be, Libc::Musl, None);
        assert_eq!(bin_prefix, "aarch64_be-linux-musl");

        let folder = get_linux_folder_name(Arch::Aarch64Be, Libc::Musl, None, "", "");
        assert_eq!(folder, "aarch64_be-linux-musl-cross");

        // Test aarch64_be gnu with version
        let bin_prefix = get_linux_bin_prefix(Arch::Aarch64Be, Libc::Gnu, None);
        assert_eq!(bin_prefix, "aarch64_be-linux-gnu");

        let folder = get_linux_folder_name(Arch::Aarch64Be, Libc::Gnu, None, "2.17", "");
        assert_eq!(folder, "aarch64_be-linux-gnu-2.17-cross");
    }
}