gitversion-rs 0.2.4

Rust port of GitVersion — calculates semantic versions from Git history. Full feature port with a Ratatui TUI.
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
//! File output: AssemblyInfo, project files, Wix.
//!
//! Corresponds to the original `GitVersion.Output/AssemblyInfo/*` and `WixUpdater/*`.

use super::variables::VersionVariables;
use anyhow::{Context, Result};
use quick_xml::events::{BytesText, Event};
use quick_xml::reader::Reader;
use quick_xml::writer::Writer;
use regex::Regex;
use rust_i18n::t;
use std::io::Cursor;
use std::path::{Path, PathBuf};

/// Template header for generated AssemblyInfo files (matches the original).
const ASSEMBLY_HEADER: &str = "\
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by GitVersion.
//
// You can modify this code as we will not overwrite it when re-executing GitVersion
// </auto-generated>
//------------------------------------------------------------------------------
";

/// Recursively find files matching the given predicate under `root`.
fn find_recursive(root: &Path, matches: impl Fn(&Path) -> bool) -> Vec<PathBuf> {
    let mut out = Vec::new();
    let mut stack = vec![root.to_path_buf()];
    while let Some(dir) = stack.pop() {
        let Ok(entries) = std::fs::read_dir(&dir) else {
            continue;
        };
        for entry in entries.flatten() {
            let path = entry.path();
            if path.is_dir() {
                // Skip hidden directories such as .git.
                if path
                    .file_name()
                    .map(|n| n.to_string_lossy().starts_with('.'))
                    .unwrap_or(false)
                {
                    continue;
                }
                stack.push(path);
            } else if matches(&path) {
                out.push(path);
            }
        }
    }
    out.sort();
    out
}

/// Update AssemblyInfo files (creates them when `ensure` is true and they are missing).
///
/// When `files` is empty, searches the working directory recursively for AssemblyInfo.{cs,vb,fs}.
pub fn update_assembly_info(
    vars: &VersionVariables,
    work_dir: &Path,
    files: &[String],
    ensure: bool,
) -> Result<Vec<PathBuf>> {
    let targets: Vec<PathBuf> = if files.is_empty() {
        find_recursive(work_dir, |p| {
            let name = p
                .file_name()
                .map(|n| n.to_string_lossy().to_lowercase())
                .unwrap_or_default();
            matches!(
                name.as_str(),
                "assemblyinfo.cs" | "assemblyinfo.vb" | "assemblyinfo.fs"
            )
        })
    } else {
        files.iter().map(|f| work_dir.join(f)).collect()
    };

    let mut updated = Vec::new();
    for path in targets {
        if path.exists() {
            let content = std::fs::read_to_string(&path)
                .with_context(|| t!("file.read_failed", path = path.display()).to_string())?;
            let new = replace_assembly_attributes(&content, vars);
            std::fs::write(&path, new)?;
            updated.push(path);
        } else if ensure {
            let content = create_assembly_info(&path, vars);
            if let Some(parent) = path.parent() {
                std::fs::create_dir_all(parent).ok();
            }
            std::fs::write(&path, content)?;
            updated.push(path);
        }
    }
    Ok(updated)
}

/// Replace the three assembly attribute values in an existing AssemblyInfo file using regex.
fn replace_assembly_attributes(content: &str, vars: &VersionVariables) -> String {
    let replace_attr = |text: &str, attr: &str, value: &str| -> String {
        // Matches both `AssemblyVersion("...")` and `<Assembly: AssemblyVersion("...")>`.
        let re = Regex::new(&format!(r#"({attr}\s*\(\s*")[^"]*("\s*\))"#)).unwrap();
        re.replace_all(text, format!("${{1}}{value}${{2}}").as_str())
            .into_owned()
    };
    let mut out = content.to_string();
    out = replace_attr(&out, "AssemblyFileVersion", &vars.assembly_sem_file_ver);
    out = replace_attr(
        &out,
        "AssemblyInformationalVersion",
        &vars.informational_version,
    );
    out = replace_attr(&out, "AssemblyVersion", &vars.assembly_sem_ver);
    out
}

/// Generate the content for a new AssemblyInfo file (syntax varies by extension).
fn create_assembly_info(path: &Path, vars: &VersionVariables) -> String {
    let ext = path
        .extension()
        .map(|e| e.to_string_lossy().to_lowercase())
        .unwrap_or_default();
    let (fv, av, iv) = (
        &vars.assembly_sem_file_ver,
        &vars.assembly_sem_ver,
        &vars.informational_version,
    );
    match ext.as_str() {
        "vb" => format!(
            "{ASSEMBLY_HEADER}\nImports System.Reflection\n\n\
             <Assembly: AssemblyFileVersion(\"{fv}\")>\n\
             <Assembly: AssemblyVersion(\"{av}\")>\n\
             <Assembly: AssemblyInformationalVersion(\"{iv}\")>\n"
        ),
        "fs" => format!(
            "{ASSEMBLY_HEADER}\nnamespace AssemblyInfo\n\nopen System.Reflection\n\n\
             [<assembly: AssemblyFileVersion(\"{fv}\")>]\n\
             [<assembly: AssemblyVersion(\"{av}\")>]\n\
             [<assembly: AssemblyInformationalVersion(\"{iv}\")>]\n\
             do ()\n"
        ),
        _ => format!(
            "{ASSEMBLY_HEADER}\nusing System.Reflection;\n\n\
             [assembly: AssemblyFileVersion(\"{fv}\")]\n\
             [assembly: AssemblyVersion(\"{av}\")]\n\
             [assembly: AssemblyInformationalVersion(\"{iv}\")]\n"
        ),
    }
}

/// Update version elements in .csproj / .vbproj / .fsproj files.
pub fn update_project_files(
    vars: &VersionVariables,
    work_dir: &Path,
    files: &[String],
) -> Result<Vec<PathBuf>> {
    let targets: Vec<PathBuf> = if files.is_empty() {
        find_recursive(work_dir, |p| {
            let ext = p
                .extension()
                .map(|e| e.to_string_lossy().to_lowercase())
                .unwrap_or_default();
            matches!(ext.as_str(), "csproj" | "vbproj" | "fsproj")
        })
    } else {
        files.iter().map(|f| work_dir.join(f)).collect()
    };

    let mut updated = Vec::new();
    for path in targets {
        if !path.exists() {
            continue;
        }
        let content = std::fs::read_to_string(&path)
            .with_context(|| t!("file.read_failed", path = path.display()).to_string())?;
        let new = replace_project_elements(&content, vars)
            .with_context(|| t!("file.xml_update_failed", path = path.display()).to_string())?;
        std::fs::write(&path, new)?;
        updated.push(path);
    }
    Ok(updated)
}

/// Target version elements in fixed order (matching the original `ProjectFileUpdater` processing order).
const PROJECT_ELEMENTS: [&str; 4] = [
    "AssemblyVersion",
    "FileVersion",
    "InformationalVersion",
    "Version",
];

/// Update version elements in a project file using real XML parsing.
///
/// Uses quick-xml events rather than regex, so comments, attributes, and indentation are preserved.
/// Like the original `ProjectFileUpdater`, existing elements have their values updated, and
/// missing elements are appended to the first `<PropertyGroup>`.
fn replace_project_elements(content: &str, vars: &VersionVariables) -> Result<String> {
    let value_of = |elem: &str| -> &str {
        match elem {
            "AssemblyVersion" => &vars.assembly_sem_ver,
            "FileVersion" => &vars.assembly_sem_file_ver,
            "InformationalVersion" => &vars.informational_version,
            _ => &vars.sem_ver,
        }
    };

    // 1) Collect all events in owned form.
    let mut reader = Reader::from_str(content);
    reader.config_mut().trim_text(false);
    let mut events: Vec<Event<'static>> = Vec::new();
    loop {
        match reader.read_event() {
            Ok(Event::Eof) => break,
            Ok(ev) => events.push(ev.into_owned()),
            Err(e) => return Err(anyhow::anyhow!("{}", t!("file.xml_parse_error", error = e))),
        }
    }

    let name_of =
        |e: &quick_xml::events::BytesStart| String::from_utf8_lossy(e.name().as_ref()).into_owned();
    let end_name_of =
        |e: &quick_xml::events::BytesEnd| String::from_utf8_lossy(e.name().as_ref()).into_owned();

    // 2) Update text in existing target elements and record which exist plus the first PropertyGroup position.
    let mut existing: std::collections::HashSet<String> = std::collections::HashSet::new();
    let mut current: Option<String> = None;
    let mut replaced = false;
    let mut first_pg_start: Option<usize> = None;
    let mut first_pg_end: Option<usize> = None;
    let mut child_indent: Option<String> = None;
    let mut pg_depth = 0i32;

    for i in 0..events.len() {
        match &events[i] {
            Event::Start(e) => {
                let name = name_of(e);
                if name == "PropertyGroup" {
                    pg_depth += 1;
                    if first_pg_start.is_none() {
                        first_pg_start = Some(i);
                    }
                }
                if PROJECT_ELEMENTS.contains(&name.as_str()) {
                    existing.insert(name.clone());
                    current = Some(name);
                    replaced = false;
                }
            }
            Event::Text(_) => {
                // Capture the indentation of the first child inside the first PropertyGroup.
                if first_pg_start.is_some() && first_pg_end.is_none() && child_indent.is_none() {
                    if let (Event::Text(t), Some(Event::Start(_))) = (&events[i], events.get(i + 1))
                    {
                        let s = String::from_utf8_lossy(t.as_ref()).into_owned();
                        if s.contains('\n') {
                            child_indent = Some(s);
                        }
                    }
                }
                if let Some(name) = current.clone() {
                    if !replaced {
                        events[i] = Event::Text(BytesText::new(value_of(&name)).into_owned());
                        replaced = true;
                    }
                }
            }
            Event::End(e) => {
                let name = end_name_of(e);
                if current.as_deref() == Some(name.as_str()) {
                    current = None;
                }
                if name == "PropertyGroup" {
                    pg_depth -= 1;
                    if first_pg_end.is_none() && first_pg_start.is_some() && pg_depth == 0 {
                        first_pg_end = Some(i);
                    }
                }
            }
            _ => {}
        }
    }

    // 3) Insert missing elements before the closing tag of the first PropertyGroup.
    let missing: Vec<&str> = PROJECT_ELEMENTS
        .iter()
        .filter(|e| !existing.contains(**e))
        .copied()
        .collect();
    if let (Some(end_idx), false) = (first_pg_end, missing.is_empty()) {
        let indent = child_indent.unwrap_or_else(|| "\n    ".into());
        // Insert before the closing-indent text node (immediately before the End event).
        let insert_at = if end_idx > 0 && matches!(&events[end_idx - 1], Event::Text(_)) {
            end_idx - 1
        } else {
            end_idx
        };
        let mut new_events: Vec<Event<'static>> = Vec::new();
        for elem in &missing {
            new_events.push(Event::Text(BytesText::new(&indent).into_owned()));
            new_events.push(Event::Start(
                quick_xml::events::BytesStart::new(*elem).into_owned(),
            ));
            new_events.push(Event::Text(BytesText::new(value_of(elem)).into_owned()));
            new_events.push(Event::End(
                quick_xml::events::BytesEnd::new(*elem).into_owned(),
            ));
        }
        events.splice(insert_at..insert_at, new_events);
    }

    // 4) Re-serialise.
    let mut writer = Writer::new(Cursor::new(Vec::new()));
    for ev in events {
        writer.write_event(ev)?;
    }
    Ok(String::from_utf8(writer.into_inner().into_inner())?)
}

/// Update the version field in package manifests for various languages.
///
/// Uses a format-preserving parser for each format (not regex):
/// - `package.json` (Node.js): serde_json (preserves key order)
/// - `Cargo.toml` (Rust), `pyproject.toml` (Python): toml_edit (preserves comments and formatting)
///
/// When `files` is empty, searches the working directory recursively for known manifests.
pub fn update_package_files(
    vars: &VersionVariables,
    work_dir: &Path,
    files: &[String],
) -> Result<Vec<PathBuf>> {
    let targets: Vec<PathBuf> = if files.is_empty() {
        find_recursive(work_dir, |p| {
            let name = p
                .file_name()
                .map(|n| n.to_string_lossy().to_lowercase())
                .unwrap_or_default();
            // Exclude manifests inside node_modules / vendor directories.
            let in_vendor = p.components().any(|c| {
                let s = c.as_os_str().to_string_lossy();
                s == "node_modules" || s == "vendor" || s == "target"
            });
            !in_vendor
                && matches!(
                    name.as_str(),
                    "package.json" | "cargo.toml" | "pyproject.toml"
                )
        })
    } else {
        files.iter().map(|f| work_dir.join(f)).collect()
    };

    let mut updated = Vec::new();
    for path in targets {
        if !path.exists() {
            continue;
        }
        let name = path
            .file_name()
            .map(|n| n.to_string_lossy().to_lowercase())
            .unwrap_or_default();
        let content = std::fs::read_to_string(&path)
            .with_context(|| t!("file.read_failed", path = path.display()).to_string())?;
        // Package manifests use SemVer without build metadata.
        let version = &vars.sem_ver;
        let new = match name.as_str() {
            "package.json" => update_package_json(&content, version)?,
            "cargo.toml" => update_cargo_toml(&content, version)?,
            "pyproject.toml" => update_pyproject_toml(&content, version)?,
            _ => continue,
        };
        if let Some(new) = new {
            std::fs::write(&path, new)?;
            updated.push(path);
        }
    }
    Ok(updated)
}

/// Update the top-level `"version"` field in package.json (key order preserved, 2-space indent).
fn update_package_json(content: &str, version: &str) -> Result<Option<String>> {
    let mut value: serde_json::Value =
        serde_json::from_str(content).with_context(|| t!("file.json_parse_failed").to_string())?;
    let serde_json::Value::Object(map) = &mut value else {
        return Ok(None);
    };
    if !map.contains_key("version") {
        return Ok(None);
    }
    map.insert(
        "version".into(),
        serde_json::Value::String(version.to_string()),
    );
    let mut out = serde_json::to_string_pretty(&value)?;
    out.push('\n'); // npm convention: trailing newline.
    Ok(Some(out))
}

/// Sync the `version` of internal path dependencies in a dependency table to `version`.
///
/// An entry is treated as an internal (sibling) crate when it is a table with both a
/// `path` and a string `version` — exactly the form crates.io validates on publish, e.g.
/// `dep = { path = "crates/dep", version = "0.0.1" }`. External deps (no `path`) and
/// inherited deps (`dep.workspace = true`, no string `version`) are left untouched.
/// The value's surrounding formatting is preserved. Returns true if anything changed.
fn sync_path_dep_versions(deps: &mut dyn toml_edit::TableLike, version: &str) -> bool {
    let mut changed = false;
    for (_key, item) in deps.iter_mut() {
        let Some(dep) = item.as_table_like_mut() else {
            continue;
        };
        if dep.get("path").is_none() {
            continue;
        }
        if let Some(val) = dep.get_mut("version").and_then(|i| i.as_value_mut()) {
            if val.is_str() {
                let decor = val.decor().clone();
                *val = toml_edit::Value::from(version);
                *val.decor_mut() = decor;
                changed = true;
            }
        }
    }
    changed
}

/// Update the version in Cargo.toml (format-preserving).
///
/// Handles both plain packages and Cargo workspaces:
/// - `[package]` with a string `version` is updated.
/// - `[workspace.package]` with a string `version` (the inherited version source) is updated.
/// - A member that inherits via `version.workspace = true` is left untouched (its `version`
///   is not a string), so workspace inheritance is preserved rather than overwritten.
/// - Internal path dependencies (`{ path = "...", version = "..." }`) in `[workspace.dependencies]`
///   and `[dependencies]`/`[dev-dependencies]`/`[build-dependencies]` have their version
///   requirement bumped in lockstep, so sibling crates in a monorepo still publish.
///
/// Returns `None` when nothing needed updating.
fn update_cargo_toml(content: &str, version: &str) -> Result<Option<String>> {
    let mut doc = content
        .parse::<toml_edit::DocumentMut>()
        .with_context(|| t!("file.cargo_parse_failed").to_string())?;

    // Update `version` in `table` only when it is currently a plain string. This skips
    // `version.workspace = true` (an inline table), preserving inheritance.
    let update_string_version = |table: &mut toml_edit::Table| -> bool {
        if table.get("version").and_then(|v| v.as_str()).is_some() {
            table["version"] = toml_edit::value(version);
            true
        } else {
            false
        }
    };

    let mut changed = false;
    // [package] version = "..."
    if let Some(pkg) = doc.get_mut("package").and_then(|p| p.as_table_mut()) {
        changed |= update_string_version(pkg);
    }
    // [workspace.package] version = "..." (the source of truth for inheriting members).
    if let Some(ws_pkg) = doc
        .get_mut("workspace")
        .and_then(|w| w.as_table_mut())
        .and_then(|w| w.get_mut("package"))
        .and_then(|p| p.as_table_mut())
    {
        changed |= update_string_version(ws_pkg);
    }

    // [workspace.dependencies] — internal path deps share the workspace version.
    if let Some(ws_deps) = doc
        .get_mut("workspace")
        .and_then(|w| w.as_table_mut())
        .and_then(|w| w.get_mut("dependencies"))
        .and_then(|d| d.as_table_like_mut())
    {
        changed |= sync_path_dep_versions(ws_deps, version);
    }
    // Per-crate dependency tables (members declaring sibling path deps directly).
    for table_name in ["dependencies", "dev-dependencies", "build-dependencies"] {
        if let Some(deps) = doc.get_mut(table_name).and_then(|d| d.as_table_like_mut()) {
            changed |= sync_path_dep_versions(deps, version);
        }
    }

    Ok(if changed { Some(doc.to_string()) } else { None })
}

/// Update the `[project]` or `[tool.poetry]` version in pyproject.toml (format-preserving).
fn update_pyproject_toml(content: &str, version: &str) -> Result<Option<String>> {
    let mut doc = content
        .parse::<toml_edit::DocumentMut>()
        .with_context(|| t!("file.pyproject_parse_failed").to_string())?;
    let mut changed = false;
    // PEP 621: [project] version
    if let Some(project) = doc.get_mut("project").and_then(|p| p.as_table_mut()) {
        if project.contains_key("version") {
            project["version"] = toml_edit::value(version);
            changed = true;
        }
    }
    // Poetry: [tool.poetry] version
    if let Some(poetry) = doc
        .get_mut("tool")
        .and_then(|t| t.as_table_mut())
        .and_then(|t| t.get_mut("poetry"))
        .and_then(|p| p.as_table_mut())
    {
        if poetry.contains_key("version") {
            poetry["version"] = toml_edit::value(version);
            changed = true;
        }
    }
    Ok(if changed { Some(doc.to_string()) } else { None })
}

/// Generate the WiX version file (`GitVersion_WixVersion.wxi`).
pub fn write_wix(vars: &VersionVariables, work_dir: &Path) -> Result<PathBuf> {
    let mut s = String::new();
    s.push('\u{feff}'); // UTF-8 BOM
    s.push_str("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
    s.push_str("<Include xmlns=\"http://schemas.microsoft.com/wix/2006/wi\">\n");
    for (key, value) in vars.to_map() {
        s.push_str(&format!("  <?define {key}=\"{value}\"?>\n"));
    }
    s.push_str("</Include>");
    let path = work_dir.join("GitVersion_WixVersion.wxi");
    std::fs::write(&path, s)?;
    Ok(path)
}

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

    fn vars() -> VersionVariables {
        VersionVariables {
            assembly_sem_ver: "1.0.1.0".into(),
            assembly_sem_file_ver: "1.0.1.0".into(),
            informational_version: "1.0.1-1+Branch.main".into(),
            sem_ver: "1.0.1-1".into(),
            ..Default::default()
        }
    }

    #[test]
    fn assembly_attribute_replacement() {
        let src = "[assembly: AssemblyVersion(\"0.0.0.0\")]\n\
                   [assembly: AssemblyFileVersion(\"0.0.0.0\")]\n\
                   [assembly: AssemblyInformationalVersion(\"0.0.0.0\")]\n";
        let out = replace_assembly_attributes(src, &vars());
        assert!(out.contains("AssemblyVersion(\"1.0.1.0\")"));
        assert!(out.contains("AssemblyFileVersion(\"1.0.1.0\")"));
        assert!(out.contains("AssemblyInformationalVersion(\"1.0.1-1+Branch.main\")"));
    }

    #[test]
    fn project_element_replacement_preserves_structure() {
        let src = "<Project Sdk=\"Microsoft.NET.Sdk\">\n  <!-- 주석 유지 -->\n  <PropertyGroup>\n    <Version>0.0.0</Version>\n    <AssemblyVersion>0.0.0.0</AssemblyVersion>\n  </PropertyGroup>\n</Project>";
        let out = replace_project_elements(src, &vars()).unwrap();
        assert!(out.contains("<Version>1.0.1-1</Version>"));
        assert!(out.contains("<AssemblyVersion>1.0.1.0</AssemblyVersion>"));
        // Comments and attributes are preserved.
        assert!(out.contains("<!-- 주석 유지 -->"));
        assert!(out.contains("Sdk=\"Microsoft.NET.Sdk\""));
    }

    #[test]
    fn project_does_not_touch_unrelated_text() {
        // Elements and text not in the target list must not be modified.
        let src = "<Project><PropertyGroup><Other>0.0.0</Other></PropertyGroup></Project>";
        let out = replace_project_elements(src, &vars()).unwrap();
        assert!(out.contains("<Other>0.0.0</Other>"));
    }

    #[test]
    fn package_json_version_update() {
        let src = "{\n  \"name\": \"x\",\n  \"version\": \"0.0.0\",\n  \"private\": true\n}";
        let out = update_package_json(src, "1.0.1-1").unwrap().unwrap();
        assert!(out.contains("\"version\": \"1.0.1-1\""));
        // Key order is preserved ("name" comes before "version").
        assert!(out.find("\"name\"").unwrap() < out.find("\"version\"").unwrap());
        assert!(out.contains("\"private\""));
    }

    #[test]
    fn cargo_toml_version_update_preserves_comments() {
        let src = "# comment\n[package]\nname = \"x\"  # inline\nversion = \"0.0.0\"\n";
        let out = update_cargo_toml(src, "1.0.1-1").unwrap().unwrap();
        assert!(out.contains("version = \"1.0.1-1\""));
        assert!(out.contains("# comment"));
        assert!(out.contains("# inline"));
    }

    #[test]
    fn package_json_without_version_is_skipped() {
        // No top-level "version" → nothing to update (e.g. an npm workspace root).
        let src =
            "{\n  \"name\": \"root\",\n  \"private\": true,\n  \"workspaces\": [\"packages/*\"]\n}";
        assert!(update_package_json(src, "1.2.3").unwrap().is_none());
    }

    #[test]
    fn package_json_preserves_other_fields_and_format() {
        let src = "{\n  \"name\": \"x\",\n  \"version\": \"0.0.0\",\n  \"scripts\": {\n    \"build\": \"tsc\"\n  },\n  \"dependencies\": {\n    \"left-pad\": \"^1.0.0\"\n  }\n}";
        let out = update_package_json(src, "2.5.0").unwrap().unwrap();
        assert!(out.contains("\"version\": \"2.5.0\""));
        // Nested objects and their values are preserved.
        assert!(out.contains("\"build\": \"tsc\""));
        assert!(out.contains("\"left-pad\": \"^1.0.0\""));
        // npm conventions: 2-space indent and a trailing newline.
        assert!(out.contains("\n  \"name\""));
        assert!(out.ends_with("}\n"));
    }

    #[test]
    fn pyproject_both_sections_updated() {
        // Both PEP 621 [project] and [tool.poetry] present → both bumped.
        let src =
            "[project]\nname = \"x\"\nversion = \"0.0.0\"\n\n[tool.poetry]\nversion = \"0.0.0\"\n";
        let out = update_pyproject_toml(src, "1.2.3").unwrap().unwrap();
        assert_eq!(out.matches("version = \"1.2.3\"").count(), 2);
    }

    #[test]
    fn pyproject_without_version_is_skipped() {
        // Only build-system metadata, no version anywhere → None.
        let src =
            "[build-system]\nrequires = [\"hatchling\"]\nbuild-backend = \"hatchling.build\"\n";
        assert!(update_pyproject_toml(src, "1.2.3").unwrap().is_none());
    }

    #[test]
    fn pyproject_dynamic_version_is_skipped() {
        // PEP 621 dynamic version (computed by the build backend) has no static `version`
        // key, so it must be left untouched.
        let src = "[project]\nname = \"x\"\ndynamic = [\"version\"]\n";
        assert!(update_pyproject_toml(src, "1.2.3").unwrap().is_none());
    }

    #[test]
    fn pyproject_preserves_comments() {
        let src = "# project metadata\n[project]\nname = \"x\"  # the name\nversion = \"0.0.0\"\n";
        let out = update_pyproject_toml(src, "9.0.1").unwrap().unwrap();
        assert!(out.contains("version = \"9.0.1\""));
        assert!(out.contains("# project metadata"));
        assert!(out.contains("# the name"));
    }

    #[test]
    fn cargo_toml_workspace_root_updates_workspace_package() {
        // Workspace root: the inherited version lives under [workspace.package].
        let src = "[workspace]\nmembers = [\"crates/*\"]\n\n[workspace.package]\nversion = \"0.0.1\"\nedition = \"2021\"\n";
        let out = update_cargo_toml(src, "1.2.3").unwrap().unwrap();
        assert!(out.contains("version = \"1.2.3\""));
        // Unrelated keys are preserved.
        assert!(out.contains("edition = \"2021\""));
        assert!(out.contains("members = [\"crates/*\"]"));
    }

    #[test]
    fn cargo_toml_inheriting_member_is_untouched() {
        // A member that inherits via `version.workspace = true` must NOT be rewritten.
        let src = "[package]\nname = \"member\"\nversion.workspace = true\n";
        assert!(update_cargo_toml(src, "1.2.3").unwrap().is_none());
    }

    #[test]
    fn cargo_toml_workspace_syncs_internal_path_dep_versions() {
        let src = "[workspace.package]\nversion = \"0.0.1\"\n\n\
                   [workspace.dependencies]\n\
                   git-warden-core = { path = \"crates/git-warden-core\", version = \"0.0.1\" }\n\
                   serde = \"1\"\n\
                   regex = { version = \"1\" }\n";
        let out = update_cargo_toml(src, "0.1.0").unwrap().unwrap();
        // Workspace version + the internal path dep are both bumped (formatting preserved).
        assert!(out.contains("[workspace.package]\nversion = \"0.1.0\""));
        assert!(out.contains(
            "git-warden-core = { path = \"crates/git-warden-core\", version = \"0.1.0\" }"
        ));
        // External deps (no `path`) are untouched.
        assert!(out.contains("serde = \"1\""));
        assert!(out.contains("regex = { version = \"1\" }"));
    }

    #[test]
    fn cargo_toml_member_syncs_sibling_path_dep() {
        let src = "[package]\nname = \"app\"\nversion = \"0.0.1\"\n\n\
                   [dependencies]\n\
                   core = { path = \"../core\", version = \"0.0.1\" }\n";
        let out = update_cargo_toml(src, "0.1.0").unwrap().unwrap();
        assert!(out.contains("core = { path = \"../core\", version = \"0.1.0\" }"));
    }

    #[test]
    fn cargo_toml_path_dep_without_version_is_untouched() {
        // A purely local path dep (no version) must not gain a version field.
        let src = "[dependencies]\nlocal = { path = \"../local\" }\n";
        assert!(update_cargo_toml(src, "1.0.0").unwrap().is_none());
    }

    #[test]
    fn cargo_toml_syncs_path_dep_in_full_table_form() {
        let src = "[workspace.package]\nversion = \"0.0.1\"\n\n\
                   [workspace.dependencies.core]\n\
                   path = \"crates/core\"\n\
                   version = \"0.0.1\"\n";
        let out = update_cargo_toml(src, "2.0.0").unwrap().unwrap();
        // Both the workspace version and the path dep's version become 2.0.0.
        assert_eq!(out.matches("\"2.0.0\"").count(), 2);
    }

    #[test]
    fn cargo_toml_root_package_and_workspace_both_updated() {
        // A root crate that is both a package and a workspace: update both string versions.
        let src = "[package]\nname = \"root\"\nversion = \"0.0.1\"\n\n[workspace.package]\nversion = \"0.0.1\"\n";
        let out = update_cargo_toml(src, "2.0.0").unwrap().unwrap();
        assert_eq!(out.matches("version = \"2.0.0\"").count(), 2);
    }

    #[test]
    fn pyproject_pep621_and_poetry() {
        let pep621 = "[project]\nname = \"x\"\nversion = \"0.0.0\"\n";
        let out = update_pyproject_toml(pep621, "1.0.1-1").unwrap().unwrap();
        assert!(out.contains("version = \"1.0.1-1\""));

        let poetry = "[tool.poetry]\nname = \"x\"\nversion = \"0.0.0\"\n";
        let out = update_pyproject_toml(poetry, "2.0.0").unwrap().unwrap();
        assert!(out.contains("version = \"2.0.0\""));
    }

    #[test]
    fn create_cs_assembly_info() {
        let out = create_assembly_info(Path::new("AssemblyInfo.cs"), &vars());
        assert!(out.contains("using System.Reflection;"));
        assert!(out.contains("[assembly: AssemblyFileVersion(\"1.0.1.0\")]"));
        assert!(out.starts_with("//---"));
    }
}