cargo-rail 0.28.1

Cargo-native Rust workspace engine for affected CI, Rust source-surface analysis, compiler reuse, dependency coherence, exact-SHA releases, and split/sync
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
//! Heuristically detect Rust target triples in workspace configuration files.

use crate::error::{RailError, RailResult};
use std::collections::HashSet;
use std::ffi::OsStr;
use std::path::{Path, PathBuf};
use std::process::Command;
use std::sync::OnceLock;

/// Return sorted, deduplicated Rust targets found in workspace TOML and GitHub workflows.
///
/// Matches tokens against `rustc --print target-list`; unreadable files are skipped.
pub fn detect_targets(workspace_root: &Path) -> RailResult<Vec<String>> {
    detect_targets_excluding(workspace_root, &[])
}

/// Detect targets excluding specific files
///
/// Same as [`detect_targets`] but skips paths in `exclude`.
/// Useful when a caller needs to avoid circular self-detection.
pub fn detect_targets_excluding(workspace_root: &Path, exclude: &[&Path]) -> RailResult<Vec<String>> {
    let canonical_targets = get_rust_target_list()?;

    let mut config_files = find_toml_files(workspace_root);
    config_files.extend(find_github_workflow_files(workspace_root));

    let mut found = HashSet::new();

    for file_path in config_files {
        if exclude.iter().any(|e| file_path == *e) {
            continue;
        }

        if let Ok(content) = std::fs::read_to_string(&file_path) {
            for target in &canonical_targets {
                if contains_target_match(&content, target) {
                    found.insert(target.clone());
                }
            }
        }
    }

    let mut targets: Vec<_> = found.into_iter().collect();
    targets.sort();

    Ok(targets)
}

/// Validate that the given targets are valid Rust target triples
///
/// Returns an error if any of the targets are not in rustc's canonical target list.
pub fn validate_targets(targets: &[String]) -> RailResult<()> {
    if targets.is_empty() {
        return Ok(());
    }

    let canonical_targets = get_rust_target_list()?;
    let mut invalid = Vec::new();

    for target in targets {
        if !canonical_targets.contains(target) {
            invalid.push(target.clone());
        }
    }

    if !invalid.is_empty() {
        return Err(RailError::with_help(
            format!("invalid target triple(s) in config: {}", invalid.join(", ")),
            "check spelling against `rustc --print target-list`. Common targets:\n  \
         - x86_64-unknown-linux-gnu\n  \
         - aarch64-apple-darwin\n  \
         - x86_64-pc-windows-msvc\n  \
         - wasm32-unknown-unknown"
                .to_string(),
        ));
    }

    Ok(())
}

/// Return the targets supported by `rustc` on `PATH`.
///
/// The first query, including failure, is cached for the process lifetime.
pub fn get_rust_target_list() -> RailResult<Vec<String>> {
    static TARGETS: OnceLock<Option<Vec<String>>> = OnceLock::new();

    let targets = TARGETS.get_or_init(|| {
        let output = Command::new("rustc").args(["--print", "target-list"]).output().ok()?;

        if !output.status.success() {
            return None;
        }

        let targets: Vec<String> = String::from_utf8_lossy(&output.stdout)
            .lines()
            .map(str::trim)
            .filter(|s| !s.is_empty())
            .map(String::from)
            .collect();

        Some(targets)
    });

    targets.clone().ok_or_else(|| {
        RailError::message("Failed to get target list from rustc. Ensure rustc is installed and in PATH.")
    })
}

/// Match complete target tokens so a longer triple cannot match its prefix.
fn contains_target_match(content: &str, target: &str) -> bool {
    let mut start = 0;
    while let Some(pos) = content.get(start..).and_then(|remaining| remaining.find(target)) {
        let absolute_pos = start + pos;
        let end_pos = absolute_pos + target.len();

        let char_before = if absolute_pos > 0 {
            content.get(..absolute_pos).and_then(|prefix| prefix.chars().last())
        } else {
            None
        };

        let char_after = content.get(end_pos..).and_then(|suffix| suffix.chars().next());

        // Dots delimit TOML table components; dotted triples must be quoted.
        let is_target_char = |c: char| c.is_alphanumeric() || c == '-' || c == '_';

        let valid_before = char_before.is_none_or(|c| !is_target_char(c));
        let valid_after = char_after.is_none_or(|c| !is_target_char(c));

        if valid_before && valid_after {
            return true;
        }

        start = absolute_pos + 1;
    }

    false
}

/// Recursively find all .toml files in workspace
///
/// - Searches up to depth 3 (avoids excessive traversal)
/// - Skips: target/, .git/, node_modules/
/// - Returns: absolute paths to .toml files
fn find_toml_files(workspace_root: &Path) -> Vec<PathBuf> {
    let mut toml_files = Vec::new();
    find_toml_files_recursive(workspace_root, 0, 3, &mut toml_files);
    toml_files
}

fn find_toml_files_recursive(dir: &Path, current_depth: usize, max_depth: usize, toml_files: &mut Vec<PathBuf>) {
    if current_depth > max_depth {
        return;
    }

    let Ok(entries) = std::fs::read_dir(dir) else {
        return;
    };

    for entry in entries.flatten() {
        let path = entry.path();

        if let Some(name) = path.file_name().and_then(|n| n.to_str())
            && matches!(name, "target" | ".git" | "node_modules" | ".cargo-rail")
        {
            continue;
        }

        if path.is_file() {
            if path.extension() == Some(OsStr::new("toml")) {
                toml_files.push(path);
            }
        } else if path.is_dir() {
            find_toml_files_recursive(&path, current_depth + 1, max_depth, toml_files);
        }
    }
}

/// Find `.yml` and `.yaml` files directly inside `.github/workflows/`.
fn find_github_workflow_files(workspace_root: &Path) -> Vec<PathBuf> {
    let workflows_dir = workspace_root.join(".github").join("workflows");

    if !workflows_dir.is_dir() {
        return Vec::new();
    }

    let Ok(entries) = std::fs::read_dir(&workflows_dir) else {
        return Vec::new();
    };

    entries
        .flatten()
        .filter_map(|entry| {
            let path = entry.path();
            if path.is_file() {
                let ext = path.extension().and_then(|e| e.to_str());
                if matches!(ext, Some("yml") | Some("yaml")) {
                    return Some(path);
                }
            }
            None
        })
        .collect()
}

/// Return whether `.github/workflows/` contains a `.yml` or `.yaml` file.
///
/// Returns `false` when the directory cannot be read.
pub fn has_github_workflows(workspace_root: &Path) -> bool {
    let workflows_dir = workspace_root.join(".github").join("workflows");
    if !workflows_dir.is_dir() {
        return false;
    }

    if let Ok(entries) = std::fs::read_dir(&workflows_dir) {
        for entry in entries.flatten() {
            let path = entry.path();
            if path.is_file() {
                let ext = path.extension().and_then(|e| e.to_str());
                if matches!(ext, Some("yml") | Some("yaml")) {
                    return true;
                }
            }
        }
    }

    false
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;
    use tempfile::TempDir;

    #[test]
    fn test_validate_targets_valid() {
        let valid_targets = vec![
            "x86_64-unknown-linux-gnu".to_string(),
            "wasm32-unknown-unknown".to_string(),
        ];
        validate_targets(&valid_targets).unwrap();
    }

    #[test]
    fn test_validate_targets_invalid() {
        let invalid_targets = vec!["invalid-target-triple".to_string()];
        let result = validate_targets(&invalid_targets);
        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(err.contains("invalid-target-triple"));
    }

    #[test]
    fn test_validate_targets_mixed() {
        let mixed_targets = vec!["x86_64-unknown-linux-gnu".to_string(), "not-a-real-target".to_string()];
        let result = validate_targets(&mixed_targets);
        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(err.contains("not-a-real-target"));
        // Should NOT mention the valid target
        assert!(!err.contains("x86_64-unknown-linux-gnu"));
    }

    #[test]
    fn test_validate_targets_empty() {
        let empty: Vec<String> = vec![];
        validate_targets(&empty).unwrap();
    }

    #[test]
    fn test_get_rust_target_list() {
        let targets = get_rust_target_list().expect("rustc should be available");

        // Should have many targets (current rustc has ~285)
        assert!(targets.len() > 200, "Expected >200 targets, got {}", targets.len());

        // Should contain common targets
        assert!(targets.contains(&"x86_64-unknown-linux-gnu".to_string()));
        assert!(targets.contains(&"aarch64-apple-darwin".to_string()));
        assert!(targets.contains(&"wasm32-unknown-unknown".to_string()));
    }

    #[test]
    fn test_detect_targets_empty_workspace() {
        let temp = TempDir::new().unwrap();
        let targets = detect_targets(temp.path()).unwrap();
        assert_eq!(targets, Vec::<String>::new());
    }

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

        // Create rust-toolchain.toml with targets
        fs::write(
            temp.path().join("rust-toolchain.toml"),
            r#"
[toolchain]
channel = "stable"
targets = ["x86_64-unknown-linux-gnu", "wasm32-unknown-unknown"]
"#,
        )
        .unwrap();

        let targets = detect_targets(temp.path()).unwrap();
        assert!(targets.contains(&"x86_64-unknown-linux-gnu".to_string()));
        assert!(targets.contains(&"wasm32-unknown-unknown".to_string()));
    }

    #[test]
    fn test_detect_targets_cargo_config() {
        let temp = TempDir::new().unwrap();
        let cargo_dir = temp.path().join(".cargo");
        fs::create_dir(&cargo_dir).unwrap();

        // Create .cargo/config.toml with target sections
        fs::write(
            cargo_dir.join("config.toml"),
            r#"
[target.x86_64-pc-windows-msvc]
linker = "lld-link.exe"

[target.aarch64-apple-darwin]
rustflags = ["-C", "link-arg=-fuse-ld=lld"]
"#,
        )
        .unwrap();

        let targets = detect_targets(temp.path()).unwrap();
        assert!(targets.contains(&"x86_64-pc-windows-msvc".to_string()));
        assert!(targets.contains(&"aarch64-apple-darwin".to_string()));
    }

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

        // Create Cross.toml (used by cross-rs)
        fs::write(
            temp.path().join("Cross.toml"),
            r#"
[target.aarch64-unknown-linux-gnu]
pre-build = ["apt-get update"]

[target.armv7-unknown-linux-gnueabihf]
image = "custom-image"
"#,
        )
        .unwrap();

        let targets = detect_targets(temp.path()).unwrap();
        assert!(targets.contains(&"aarch64-unknown-linux-gnu".to_string()));
        assert!(targets.contains(&"armv7-unknown-linux-gnueabihf".to_string()));
    }

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

        // Create dist-workspace.toml (used by cargo-dist)
        fs::write(
            temp.path().join("dist-workspace.toml"),
            r#"
[dist]
targets = [
  "x86_64-unknown-linux-gnu",
  "aarch64-apple-darwin",
  "x86_64-pc-windows-msvc"
]
"#,
        )
        .unwrap();

        let targets = detect_targets(temp.path()).unwrap();
        assert!(targets.contains(&"x86_64-unknown-linux-gnu".to_string()));
        assert!(targets.contains(&"aarch64-apple-darwin".to_string()));
        assert!(targets.contains(&"x86_64-pc-windows-msvc".to_string()));
    }

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

        // Create multiple files mentioning the same targets
        fs::write(
            temp.path().join("rust-toolchain.toml"),
            r#"
[toolchain]
targets = ["x86_64-unknown-linux-gnu"]
"#,
        )
        .unwrap();

        let cargo_dir = temp.path().join(".cargo");
        fs::create_dir(&cargo_dir).unwrap();
        fs::write(
            cargo_dir.join("config.toml"),
            r#"
[target.x86_64-unknown-linux-gnu]
linker = "clang"
"#,
        )
        .unwrap();

        let targets = detect_targets(temp.path()).unwrap();
        // Should only appear once despite being in 2 files
        assert_eq!(targets.iter().filter(|t| *t == "x86_64-unknown-linux-gnu").count(), 1);
    }

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

        // Create a target directory with a TOML file
        let target_dir = temp.path().join("target");
        fs::create_dir(&target_dir).unwrap();
        fs::write(target_dir.join("should-skip.toml"), "# ignored").unwrap();

        // Create a valid TOML file at root
        fs::write(temp.path().join("valid.toml"), "# found").unwrap();

        let toml_files = find_toml_files(temp.path());

        // Should find valid.toml but not target/should-skip.toml
        assert_eq!(toml_files.len(), 1);
        assert!(toml_files[0].ends_with("valid.toml"));
    }

    // GitHub Workflow YAML Tests

    #[test]
    fn test_find_github_workflow_files_empty() {
        let temp = TempDir::new().unwrap();
        let files = find_github_workflow_files(temp.path());
        assert!(files.is_empty());
    }

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

        // Create .github/workflows directory
        let workflows_dir = temp.path().join(".github").join("workflows");
        fs::create_dir_all(&workflows_dir).unwrap();

        // Create workflow files
        fs::write(workflows_dir.join("ci.yml"), "name: CI").unwrap();
        fs::write(workflows_dir.join("release.yaml"), "name: Release").unwrap();

        let files = find_github_workflow_files(temp.path());
        assert_eq!(files.len(), 2);
    }

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

        // Create .github/workflows directory
        let workflows_dir = temp.path().join(".github").join("workflows");
        fs::create_dir_all(&workflows_dir).unwrap();

        // Create mixed files
        fs::write(workflows_dir.join("ci.yml"), "name: CI").unwrap();
        fs::write(workflows_dir.join("README.md"), "# Workflows").unwrap();
        fs::write(workflows_dir.join("config.json"), "{}").unwrap();

        let files = find_github_workflow_files(temp.path());
        assert_eq!(files.len(), 1);
        assert!(files[0].ends_with("ci.yml"));
    }

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

        // Create .github/workflows/ci.yml with target matrix
        let workflows_dir = temp.path().join(".github").join("workflows");
        fs::create_dir_all(&workflows_dir).unwrap();

        fs::write(
            workflows_dir.join("ci.yml"),
            r#"
name: CI
jobs:
  build:
    strategy:
      matrix:
        target:
          - x86_64-unknown-linux-gnu
          - aarch64-apple-darwin
          - x86_64-pc-windows-msvc
"#,
        )
        .unwrap();

        let targets = detect_targets(temp.path()).unwrap();
        assert!(targets.contains(&"x86_64-unknown-linux-gnu".to_string()));
        assert!(targets.contains(&"aarch64-apple-darwin".to_string()));
        assert!(targets.contains(&"x86_64-pc-windows-msvc".to_string()));
    }

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

        // Create rust-toolchain.toml with one target
        fs::write(
            temp.path().join("rust-toolchain.toml"),
            r#"
[toolchain]
targets = ["wasm32-unknown-unknown"]
"#,
        )
        .unwrap();

        // Create .github/workflows/ci.yml with different targets
        let workflows_dir = temp.path().join(".github").join("workflows");
        fs::create_dir_all(&workflows_dir).unwrap();

        fs::write(
            workflows_dir.join("ci.yml"),
            r#"
name: CI
jobs:
  build:
    strategy:
      matrix:
        target: ["x86_64-unknown-linux-gnu", "aarch64-apple-darwin"]
"#,
        )
        .unwrap();

        let targets = detect_targets(temp.path()).unwrap();

        // Should find targets from both sources
        assert!(targets.contains(&"wasm32-unknown-unknown".to_string()));
        assert!(targets.contains(&"x86_64-unknown-linux-gnu".to_string()));
        assert!(targets.contains(&"aarch64-apple-darwin".to_string()));
        assert_eq!(targets.len(), 3);
    }

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

        // Create .github/workflows with a workflow file
        let workflows_dir = temp.path().join(".github").join("workflows");
        fs::create_dir_all(&workflows_dir).unwrap();
        fs::write(workflows_dir.join("ci.yml"), "name: CI").unwrap();

        assert!(has_github_workflows(temp.path()));
    }

    #[test]
    fn test_has_github_workflows_false_no_dir() {
        let temp = TempDir::new().unwrap();
        assert!(!has_github_workflows(temp.path()));
    }

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

        // Create empty .github/workflows directory
        let workflows_dir = temp.path().join(".github").join("workflows");
        fs::create_dir_all(&workflows_dir).unwrap();

        assert!(!has_github_workflows(temp.path()));
    }

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

        // Create .github/workflows with non-YAML files only
        let workflows_dir = temp.path().join(".github").join("workflows");
        fs::create_dir_all(&workflows_dir).unwrap();
        fs::write(workflows_dir.join("README.md"), "# Workflows").unwrap();

        assert!(!has_github_workflows(temp.path()));
    }

    // Word Boundary Matching Tests

    #[test]
    fn test_contains_target_match_exact() {
        assert!(contains_target_match("thumbv7em-none-eabihf", "thumbv7em-none-eabihf"));
    }

    #[test]
    fn test_contains_target_match_quoted() {
        assert!(contains_target_match(
            r#""thumbv7em-none-eabihf""#,
            "thumbv7em-none-eabihf"
        ));
        assert!(contains_target_match(
            r#"'thumbv7em-none-eabihf'"#,
            "thumbv7em-none-eabihf"
        ));
    }

    #[test]
    fn test_contains_target_match_in_array() {
        let content = r#"targets = ["x86_64-unknown-linux-gnu", "aarch64-apple-darwin"]"#;
        assert!(contains_target_match(content, "x86_64-unknown-linux-gnu"));
        assert!(contains_target_match(content, "aarch64-apple-darwin"));
    }

    #[test]
    fn test_contains_target_match_in_table_key() {
        let content = r#"[target.thumbv7em-none-eabihf]
linker = "arm-none-eabi-gcc""#;
        assert!(contains_target_match(content, "thumbv7em-none-eabihf"));
    }

    #[test]
    fn test_contains_target_match_rejects_substring() {
        // This is the critical test - should NOT match shorter target when only longer exists
        let content = r#"targets = ["thumbv7em-none-eabihf"]"#;

        // Should match the actual target
        assert!(contains_target_match(content, "thumbv7em-none-eabihf"));

        // Should NOT match the shorter substring target
        assert!(
            !contains_target_match(content, "thumbv7em-none-eabi"),
            "Should not match 'thumbv7em-none-eabi' when file only contains 'thumbv7em-none-eabihf'"
        );
    }

    #[test]
    fn test_contains_target_match_rejects_all_substring_cases() {
        // Test several known substring cases from rustc target list
        let test_cases = [
            ("aarch64-apple-ios-sim", "aarch64-apple-ios"),
            ("arm-unknown-linux-gnueabihf", "arm-unknown-linux-gnueabi"),
            ("x86_64-unknown-linux-gnux32", "x86_64-unknown-linux-gnu"),
            ("wasm32-wasip1-threads", "wasm32-wasip1"),
            ("x86_64-pc-windows-gnullvm", "x86_64-pc-windows-gnu"),
        ];

        for (full_target, substring_target) in test_cases {
            let content = format!(r#"targets = ["{}"]"#, full_target);
            assert!(
                contains_target_match(&content, full_target),
                "Should match full target: {}",
                full_target
            );
            assert!(
                !contains_target_match(&content, substring_target),
                "Should NOT match substring '{}' when file only contains '{}'",
                substring_target,
                full_target
            );
        }
    }

    #[test]
    fn test_contains_target_match_allows_both_when_both_present() {
        // When both the short and long target are in the file, both should match
        let content = r#"targets = ["thumbv7em-none-eabi", "thumbv7em-none-eabihf"]"#;

        assert!(contains_target_match(content, "thumbv7em-none-eabi"));
        assert!(contains_target_match(content, "thumbv7em-none-eabihf"));
    }

    #[test]
    fn test_contains_target_match_yaml_format() {
        let content = r#"
matrix:
  target:
    - x86_64-unknown-linux-gnu
    - aarch64-apple-darwin
"#;
        assert!(contains_target_match(content, "x86_64-unknown-linux-gnu"));
        assert!(contains_target_match(content, "aarch64-apple-darwin"));
        // Should not false positive on similar targets
        assert!(!contains_target_match(content, "x86_64-unknown-linux-gnux32"));
    }

    #[test]
    fn test_contains_target_match_with_dots() {
        // Targets like thumbv8m.main-none-eabi have dots in them.
        // In TOML, these MUST be quoted because dots are path separators.
        // So we test the quoted form which is what users would actually write.
        let content = r#"[target."thumbv8m.main-none-eabihf"]"#;
        assert!(contains_target_match(content, "thumbv8m.main-none-eabihf"));
        assert!(!contains_target_match(content, "thumbv8m.main-none-eabi"));

        // Also test in array form
        let content2 = r#"targets = ["thumbv8m.main-none-eabihf"]"#;
        assert!(contains_target_match(content2, "thumbv8m.main-none-eabihf"));
        assert!(!contains_target_match(content2, "thumbv8m.main-none-eabi"));
    }

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

        // Create a file with ONLY the longer target
        fs::write(
            temp.path().join("rust-toolchain.toml"),
            r#"
[toolchain]
channel = "stable"
targets = ["thumbv7em-none-eabihf"]
"#,
        )
        .unwrap();

        let targets = detect_targets(temp.path()).unwrap();

        // Should find the actual target
        assert!(
            targets.contains(&"thumbv7em-none-eabihf".to_string()),
            "Should detect thumbv7em-none-eabihf"
        );

        // Should NOT find the substring target
        assert!(
            !targets.contains(&"thumbv7em-none-eabi".to_string()),
            "Should NOT detect thumbv7em-none-eabi (false positive)"
        );
    }
}