gitversion-rs 0.2.0

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
//! 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))
}

/// Update the `[package]` version in Cargo.toml (format-preserving).
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())?;
    let Some(pkg) = doc.get_mut("package").and_then(|p| p.as_table_mut()) else {
        return Ok(None);
    };
    if !pkg.contains_key("version") {
        return Ok(None);
    }
    pkg["version"] = toml_edit::value(version);
    Ok(Some(doc.to_string()))
}

/// 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 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("//---"));
    }
}