cargo-bless 0.3.1

Modernize your Rust dependencies with blessed.rs + live intel
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
//! Fix layer — applies auto-fixable suggestions by editing Cargo.toml
//! using `toml_edit` to preserve comments and formatting.
//!
//! Safety guardrails:
//! - `.bak` backup before any writes  
//! - `--dry-run` previews the diff without touching files
//! - Only direct dependency edits (never transitive)
//! - Only auto-fixable suggestion types (StdReplacement, Unmaintained, FeatureOptimization)

use std::fs;
use std::path::Path;
use std::process::{Command, Output};

use anyhow::{Context, Result};
use colored::*;
use toml_edit::{DocumentMut, Item, Value};

use crate::suggestions::{Suggestion, SuggestionKind};

/// Result summary of a fix operation.
pub struct FixResult {
    pub applied: Vec<String>,
    pub skipped: Vec<String>,
}

/// Apply auto-fixable suggestions to the Cargo.toml at `manifest_path`.
///
/// - Only processes suggestions where `is_auto_fixable()` is true.
/// - Creates a `.bak` backup before any edits.
/// - Uses `toml_edit` to preserve comments and formatting.
/// - If `dry_run` is true, prints the diff but writes nothing.
pub fn apply(suggestions: &[Suggestion], manifest_path: &Path, dry_run: bool) -> Result<FixResult> {
    let fixable: Vec<&Suggestion> = suggestions.iter().filter(|s| s.is_auto_fixable()).collect();

    if fixable.is_empty() {
        println!(
            "{}",
            "ℹ️  No auto-fixable suggestions found. Manual changes recommended above.".dimmed()
        );
        return Ok(FixResult {
            applied: vec![],
            skipped: suggestions.iter().map(|s| s.current.clone()).collect(),
        });
    }

    eprintln!(
        "{}",
        "ℹ️  Autofix: edits Cargo.toml dependency lines only — never Rust source.".dimmed()
    );

    let original = fs::read_to_string(manifest_path)
        .with_context(|| format!("failed to read {}", manifest_path.display()))?;

    let mut doc: DocumentMut = original
        .parse()
        .with_context(|| format!("failed to parse {} as TOML", manifest_path.display()))?;

    let mut applied = Vec::new();
    let mut skipped = Vec::new();

    for suggestion in &fixable {
        match apply_single(&mut doc, suggestion) {
            Ok(desc) => applied.push(desc),
            Err(e) => {
                skipped.push(format!("{}: {}", suggestion.current, e));
            }
        }
    }

    // Also note non-fixable suggestions as skipped
    for suggestion in suggestions {
        if !suggestion.is_auto_fixable() {
            skipped.push(format!(
                "{} (requires source code changes)",
                suggestion.current
            ));
        }
    }

    let edited = doc.to_string();

    if dry_run {
        println!(
            "🔍 {}",
            "Dry-run: the following changes would be made:".bold()
        );
        println!();
        print_diff(&original, &edited);

        if !applied.is_empty() {
            println!();
            println!("{}", "Changes that would be applied:".bold());
            for desc in &applied {
                println!("  {} {}", "".green(), desc);
            }
        }

        if !skipped.is_empty() {
            println!();
            println!("{}", "Skipped (manual action needed):".dimmed());
            for desc in &skipped {
                println!("  {} {}", "".dimmed(), desc.dimmed());
            }
        }
    } else {
        // Create backup
        let backup_path = manifest_path.with_extension("toml.bak");
        fs::copy(manifest_path, &backup_path)
            .with_context(|| format!("failed to create backup at {}", backup_path.display()))?;
        println!(
            "📋 Backup saved to {}",
            backup_path.display().to_string().dimmed()
        );

        // Write edited TOML
        fs::write(manifest_path, &edited)
            .with_context(|| format!("failed to write {}", manifest_path.display()))?;

        run_cargo_validation(
            "cargo update",
            "📦 Running cargo update...",
            "✅ cargo update completed successfully.",
            &["update", "--manifest-path"],
            manifest_path,
        );

        run_cargo_validation(
            "cargo check",
            "🔍 Running cargo check...",
            "✅ cargo check passed — project still compiles.",
            &["check", "--manifest-path"],
            manifest_path,
        );

        println!();
        if !applied.is_empty() {
            println!("{}", "Applied fixes:".bold().green());
            for desc in &applied {
                println!("  {} {}", "".green(), desc);
            }
        }

        if !skipped.is_empty() {
            println!();
            println!("{}", "Skipped (manual action needed):".dimmed());
            for desc in &skipped {
                println!("  {} {}", "".dimmed(), desc.dimmed());
            }
        }
    }

    Ok(FixResult { applied, skipped })
}

fn run_cargo_validation(
    command_name: &str,
    start_message: &str,
    success_message: &str,
    args: &[&str],
    manifest_path: &Path,
) {
    println!("{}", start_message.dimmed());
    let output = Command::new("cargo").args(args).arg(manifest_path).output();

    match output {
        Ok(output) if output.status.success() => {
            println!("{}", success_message.green());
        }
        Ok(output) => {
            println!(
                "{}",
                format!(
                    "⚠️  {command_name} exited with {}. Run `{command_name} --manifest-path {}` for details.",
                    output.status,
                    manifest_path.display()
                )
                .yellow()
            );
            if let Some(summary) = validation_summary(&output) {
                println!("   {}", summary.dimmed());
            }
        }
        Err(err) => {
            println!(
                "{}",
                format!("⚠️  Failed to run {command_name}: {err}").yellow()
            );
        }
    }
}

fn validation_summary(output: &Output) -> Option<String> {
    let stderr = String::from_utf8_lossy(&output.stderr);
    stderr
        .lines()
        .chain(String::from_utf8_lossy(&output.stdout).lines())
        .map(str::trim)
        .find(|line| !line.is_empty())
        .map(str::to_string)
}

/// Apply a single suggestion to the TOML document.
/// Returns a description of what was done on success.
fn apply_single(doc: &mut DocumentMut, suggestion: &Suggestion) -> Result<String> {
    match suggestion.kind {
        SuggestionKind::StdReplacement => {
            apply_remove(doc, &suggestion.current, &suggestion.recommended)
        }
        SuggestionKind::Unmaintained => {
            apply_rename(doc, &suggestion.current, &suggestion.recommended)
        }
        SuggestionKind::FeatureOptimization => {
            apply_feature_opt(doc, &suggestion.current, &suggestion.recommended)
        }
        _ => anyhow::bail!("not auto-fixable"),
    }
}

/// Remove a dependency (StdReplacement: crate replaced by std).
/// Searches [dependencies], [dev-dependencies], and [build-dependencies].
fn apply_remove(doc: &mut DocumentMut, crate_name: &str, replacement: &str) -> Result<String> {
    for section in ["dependencies", "dev-dependencies", "build-dependencies"] {
        if let Some(deps) = doc.get_mut(section).and_then(|d| d.as_table_like_mut()) {
            if deps.remove(crate_name).is_some() {
                return Ok(format!(
                    "Removed `{}` from [{}] (use {} instead)",
                    crate_name, section, replacement
                ));
            }
        }
    }
    anyhow::bail!("`{}` not found in any dependency section", crate_name)
}

/// Rename a dependency (Unmaintained: swap to maintained fork).
/// Searches [dependencies], [dev-dependencies], and [build-dependencies].
fn apply_rename(doc: &mut DocumentMut, old_name: &str, new_name: &str) -> Result<String> {
    for section in ["dependencies", "dev-dependencies", "build-dependencies"] {
        if let Some(deps) = doc.get_mut(section).and_then(|d| d.as_table_like_mut()) {
            if let Some(old_item) = deps.remove(old_name) {
                deps.insert(new_name, old_item);
                return Ok(format!(
                    "Renamed `{}` → `{}` in [{}]",
                    old_name, new_name, section
                ));
            }
        }
    }
    anyhow::bail!("`{}` not found in any dependency section", old_name)
}

/// Feature optimization: remove extra dep, add feature to the main dep.
/// Searches [dependencies], [dev-dependencies], and [build-dependencies].
/// Pattern format: "main_crate+extra_crate" → "main_crate with \"feature\" feature"
fn apply_feature_opt(doc: &mut DocumentMut, pattern: &str, recommended: &str) -> Result<String> {
    let parts: Vec<&str> = pattern.split('+').collect();
    if parts.len() != 2 {
        anyhow::bail!("expected pattern format 'crate1+crate2', got '{}'", pattern);
    }

    let main_crate = parts[0].trim();
    let extra_crate = parts[1].trim();

    // Parse the feature name from recommended text (e.g. 'reqwest with "json" feature')
    let feature_name = extract_feature_name(recommended)
        .ok_or_else(|| anyhow::anyhow!("could not parse feature name from '{}'", recommended))?;

    let sections = ["dependencies", "dev-dependencies", "build-dependencies"];

    // Find the extra crate in any section and remove it
    let mut extra_removed_section = None;
    for section in &sections {
        if let Some(deps) = doc.get_mut(section).and_then(|d| d.as_table_like_mut()) {
            if deps.remove(extra_crate).is_some() {
                extra_removed_section = Some(*section);
                break;
            }
        }
    }

    if extra_removed_section.is_none() {
        anyhow::bail!("`{}` not found in any dependency section", extra_crate);
    }

    // Find the main crate in any section and add the feature
    for section in &sections {
        if let Some(deps) = doc.get_mut(section).and_then(|d| d.as_table_like_mut()) {
            if deps.get(main_crate).is_some() {
                add_feature_to_dep(deps, main_crate, &feature_name)?;
                return Ok(format!(
                    "Removed `{}` from [{}], enabled `{}` feature on `{}` in [{}]",
                    extra_crate,
                    extra_removed_section.unwrap(),
                    feature_name,
                    main_crate,
                    section
                ));
            }
        }
    }

    anyhow::bail!("`{}` not found in any dependency section", main_crate)
}

/// Extract feature name from a recommendation string like 'reqwest with "json" feature'.
fn extract_feature_name(recommended: &str) -> Option<String> {
    // Look for text in quotes
    let start = recommended.find('"')? + 1;
    let end = recommended[start..].find('"')? + start;
    Some(recommended[start..end].to_string())
}

/// Add a feature to an existing dependency entry.
fn add_feature_to_dep(
    deps: &mut dyn toml_edit::TableLike,
    crate_name: &str,
    feature: &str,
) -> Result<()> {
    let entry = deps
        .get_mut(crate_name)
        .ok_or_else(|| anyhow::anyhow!("`{}` not found in [dependencies]", crate_name))?;

    match entry {
        Item::Value(Value::String(version_str)) => {
            // Simple string version like: reqwest = "0.12"
            // Convert to table form: reqwest = { version = "0.12", features = ["json"] }
            let version = version_str.value().clone();
            let mut table = toml_edit::InlineTable::new();
            table.insert("version", Value::from(version));
            let mut features = toml_edit::Array::new();
            features.push(feature);
            table.insert("features", Value::Array(features));
            *entry = Item::Value(Value::InlineTable(table));
        }
        Item::Value(Value::InlineTable(table)) => {
            // Already an inline table like: reqwest = { version = "0.12", features = [...] }
            if let Some(Value::Array(arr)) = table.get_mut("features") {
                // Check if feature already exists
                let has_feature = arr.iter().any(|v| v.as_str() == Some(feature));
                if !has_feature {
                    arr.push(feature);
                }
            } else {
                let mut features = toml_edit::Array::new();
                features.push(feature);
                table.insert("features", Value::Array(features));
            }
        }
        Item::Table(table) => {
            // Full table form
            if let Some(features_item) = table.get_mut("features") {
                if let Item::Value(Value::Array(arr)) = features_item {
                    let has_feature = arr.iter().any(|v| v.as_str() == Some(feature));
                    if !has_feature {
                        arr.push(feature);
                    }
                }
            } else {
                let mut features = toml_edit::Array::new();
                features.push(feature);
                table.insert("features", toml_edit::value(Value::Array(features)));
            }
        }
        _ => {
            anyhow::bail!("unexpected dependency format for `{}`", crate_name);
        }
    }

    Ok(())
}

/// Print a simple line-by-line diff between old and new content.
fn print_diff(old: &str, new: &str) {
    let old_lines: Vec<&str> = old.lines().collect();
    let new_lines: Vec<&str> = new.lines().collect();

    // Simple diff: show removed and added lines
    let mut shown_header = false;

    for line in &old_lines {
        if !new_lines.contains(line) {
            if !shown_header {
                println!("{}", "--- Cargo.toml (original)".dimmed());
                println!("{}", "+++ Cargo.toml (modified)".dimmed());
                println!();
                shown_header = true;
            }
            println!("{}", format!("- {}", line).red());
        }
    }

    for line in &new_lines {
        if !old_lines.contains(line) {
            if !shown_header {
                println!("{}", "--- Cargo.toml (original)".dimmed());
                println!("{}", "+++ Cargo.toml (modified)".dimmed());
                println!();
                shown_header = true;
            }
            println!("{}", format!("+ {}", line).green());
        }
    }

    if !shown_header {
        println!("{}", "  (no changes)".dimmed());
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::suggestions::{
        AutofixSafety, Confidence, EvidenceSource, Impact, MigrationRisk, SuggestionKind,
    };
    use tempfile::TempDir;

    fn make_suggestion(kind: SuggestionKind, current: &str, recommended: &str) -> Suggestion {
        Suggestion {
            kind: kind.clone(),
            current: current.into(),
            recommended: recommended.into(),
            reason: "test reason".into(),
            source: "test".into(),
            impact: match kind {
                SuggestionKind::Unmaintained | SuggestionKind::StdReplacement => Impact::High,
                SuggestionKind::ModernAlternative | SuggestionKind::ComboWin => Impact::Medium,
                SuggestionKind::FeatureOptimization => Impact::Low,
            },
            confidence: Confidence::High,
            migration_risk: MigrationRisk::Low,
            autofix_safety: match kind {
                SuggestionKind::ModernAlternative | SuggestionKind::ComboWin => {
                    AutofixSafety::ManualOnly
                }
                _ => AutofixSafety::CargoTomlOnly,
            },
            evidence_source: EvidenceSource::Heuristic,
            package: None,
        }
    }

    #[test]
    fn test_remove_dep() {
        let toml = r#"
[package]
name = "test-project"
version = "0.1.0"

[dependencies]
lazy_static = "1.5"
serde = "1.0"
"#;
        let mut doc: DocumentMut = toml.parse().unwrap();
        let result = apply_remove(&mut doc, "lazy_static", "std::sync::LazyLock").unwrap();

        assert!(result.contains("Removed `lazy_static`"));
        let edited = doc.to_string();
        assert!(!edited.contains("lazy_static"));
        assert!(edited.contains("serde")); // other deps untouched
    }

    #[test]
    fn test_rename_dep() {
        let toml = r#"
[package]
name = "test-project"
version = "0.1.0"

[dependencies]
memmap = "0.7"
serde = "1.0"
"#;
        let mut doc: DocumentMut = toml.parse().unwrap();
        let result = apply_rename(&mut doc, "memmap", "memmap2").unwrap();

        assert!(result.contains("Renamed `memmap` → `memmap2`"));
        let edited = doc.to_string();
        assert!(!edited.contains("memmap ="));
        assert!(edited.contains("memmap2"));
        assert!(edited.contains("serde")); // other deps untouched
    }

    #[test]
    fn test_feature_opt_simple_version() {
        let toml = r#"
[package]
name = "test-project"
version = "0.1.0"

[dependencies]
reqwest = "0.12"
serde_json = "1.0"
"#;
        let mut doc: DocumentMut = toml.parse().unwrap();
        let result = apply_feature_opt(
            &mut doc,
            "reqwest+serde_json",
            r#"reqwest with "json" feature"#,
        )
        .unwrap();

        assert!(result.contains("Removed `serde_json`"));
        assert!(result.contains("enabled `json` feature on `reqwest`"));
        let edited = doc.to_string();
        assert!(!edited.contains("serde_json"));
        assert!(edited.contains("json"));
        assert!(edited.contains("reqwest"));
    }

    #[test]
    fn test_feature_opt_inline_table() {
        let toml = r#"
[package]
name = "test-project"
version = "0.1.0"

[dependencies]
reqwest = { version = "0.12", features = ["blocking"] }
serde_json = "1.0"
"#;
        let mut doc: DocumentMut = toml.parse().unwrap();
        let result = apply_feature_opt(
            &mut doc,
            "reqwest+serde_json",
            r#"reqwest with "json" feature"#,
        )
        .unwrap();

        assert!(result.contains("Removed `serde_json`"));
        let edited = doc.to_string();
        assert!(!edited.contains("serde_json"));
        // Should have both blocking and json features
        assert!(edited.contains("blocking"));
        assert!(edited.contains("json"));
    }

    #[test]
    fn test_extract_feature_name() {
        assert_eq!(
            extract_feature_name(r#"reqwest with "json" feature"#),
            Some("json".into())
        );
        assert_eq!(
            extract_feature_name(r#"tokio with "full" feature"#),
            Some("full".into())
        );
        assert_eq!(extract_feature_name("no quotes here"), None);
    }

    #[test]
    fn test_remove_nonexistent_dep() {
        let toml = r#"
[package]
name = "test-project"

[dependencies]
serde = "1.0"
"#;
        let mut doc: DocumentMut = toml.parse().unwrap();
        let result = apply_remove(&mut doc, "nonexistent", "something");
        assert!(result.is_err());
    }

    #[test]
    fn test_dry_run_does_not_write() {
        let tmp = TempDir::new().unwrap();
        let manifest = tmp.path().join("Cargo.toml");
        let toml_content = r#"
[package]
name = "test-project"
version = "0.1.0"

[dependencies]
lazy_static = "1.5"
"#;
        fs::write(&manifest, toml_content).unwrap();

        let suggestions = vec![make_suggestion(
            SuggestionKind::StdReplacement,
            "lazy_static",
            "std::sync::LazyLock",
        )];

        let result = apply(&suggestions, &manifest, true).unwrap();
        assert_eq!(result.applied.len(), 1);

        // File should be unchanged
        let after = fs::read_to_string(&manifest).unwrap();
        assert_eq!(after, toml_content);

        // No backup should exist
        assert!(!tmp.path().join("Cargo.toml.bak").exists());
    }

    #[test]
    fn test_full_apply_creates_backup() {
        let tmp = TempDir::new().unwrap();
        let manifest = tmp.path().join("Cargo.toml");
        let toml_content = r#"[package]
name = "test-project"
version = "0.1.0"

[dependencies]
lazy_static = "1.5"
serde = "1.0"
"#;
        fs::write(&manifest, toml_content).unwrap();

        let suggestions = vec![make_suggestion(
            SuggestionKind::StdReplacement,
            "lazy_static",
            "std::sync::LazyLock",
        )];

        let result = apply(&suggestions, &manifest, false).unwrap();
        assert_eq!(result.applied.len(), 1);

        // Backup should exist with original content
        let backup = tmp.path().join("Cargo.toml.bak");
        assert!(backup.exists());
        let backup_content = fs::read_to_string(&backup).unwrap();
        assert_eq!(backup_content, toml_content);

        // File should be modified
        let after = fs::read_to_string(&manifest).unwrap();
        assert!(!after.contains("lazy_static"));
        assert!(after.contains("serde")); // untouched
    }

    #[test]
    fn test_no_fixable_suggestions() {
        let tmp = TempDir::new().unwrap();
        let manifest = tmp.path().join("Cargo.toml");
        fs::write(&manifest, "[package]\nname = \"test\"\n[dependencies]\n").unwrap();

        let suggestions = vec![make_suggestion(
            SuggestionKind::ModernAlternative,
            "structopt",
            "clap v4",
        )];

        let result = apply(&suggestions, &manifest, true).unwrap();
        assert!(result.applied.is_empty());
        assert_eq!(result.skipped.len(), 1);
    }

    #[test]
    fn test_remove_from_dev_dependencies() {
        let toml = r#"
[package]
name = "test-project"
version = "0.1.0"

[dependencies]
serde = "1.0"

[dev-dependencies]
lazy_static = "1.5"
"#;
        let mut doc: DocumentMut = toml.parse().unwrap();
        let result = apply_remove(&mut doc, "lazy_static", "std::sync::LazyLock").unwrap();

        assert!(result.contains("Removed `lazy_static`"));
        assert!(result.contains("[dev-dependencies]"));
        let edited = doc.to_string();
        assert!(!edited.contains("lazy_static"));
        assert!(edited.contains("serde"));
    }

    #[test]
    fn test_remove_from_build_dependencies() {
        let toml = r#"
[package]
name = "test-project"
version = "0.1.0"

[dependencies]
serde = "1.0"

[build-dependencies]
lazy_static = "1.5"
"#;
        let mut doc: DocumentMut = toml.parse().unwrap();
        let result = apply_remove(&mut doc, "lazy_static", "std::sync::LazyLock").unwrap();

        assert!(result.contains("[build-dependencies]"));
        let edited = doc.to_string();
        assert!(!edited.contains("lazy_static"));
    }

    #[test]
    fn test_rename_from_dev_dependencies() {
        let toml = r#"
[package]
name = "test-project"
version = "0.1.0"

[dev-dependencies]
memmap = "0.7"
"#;
        let mut doc: DocumentMut = toml.parse().unwrap();
        let result = apply_rename(&mut doc, "memmap", "memmap2").unwrap();

        assert!(result.contains("Renamed `memmap` → `memmap2`"));
        assert!(result.contains("[dev-dependencies]"));
        let edited = doc.to_string();
        assert!(!edited.contains("memmap ="));
        assert!(edited.contains("memmap2"));
    }

    #[test]
    fn test_feature_opt_across_sections() {
        let toml = r#"
[package]
name = "test-project"
version = "0.1.0"

[dependencies]
reqwest = "0.12"

[dev-dependencies]
serde_json = "1.0"
"#;
        let mut doc: DocumentMut = toml.parse().unwrap();
        let result = apply_feature_opt(
            &mut doc,
            "reqwest+serde_json",
            r#"reqwest with "json" feature"#,
        )
        .unwrap();

        assert!(result.contains("Removed `serde_json`"));
        assert!(result.contains("[dev-dependencies]"));
        assert!(result.contains("enabled `json` feature on `reqwest` in [dependencies]"));
        let edited = doc.to_string();
        assert!(!edited.contains("serde_json"));
        assert!(edited.contains("json"));
    }
}