odometer 0.6.1

A workspace version management tool that keeps package versions synchronized across projects
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
use anyhow::{Context, Result};
use std::{fs, path::Path};
use toml_edit::{DocumentMut, Formatted, Item, Value};

use crate::domain::VersionField;

/// Parse a Cargo.toml file and return (name, version, has_workspace_inheritance)
pub fn parse(path: &Path) -> Result<(Option<String>, VersionField)> {
    let content = fs::read_to_string(path). //-
        with_context(|| format!("Failed to read {}", path.display()))?;

    let doc = content
        .parse::<DocumentMut>()
        .with_context(|| format!("Failed to parse {}", path.display()))?;

    let package = get_package_section(&doc);

    let name = package
        .and_then(|p| p.get("name"))
        .and_then(|n| n.as_str())
        .map(|s| s.to_string());

    let version = if uses_workspace_inheritance(&doc, "package", "version") {
        VersionField::Inherited
    } else {
        match package.and_then(|p| p.get("version")) {
            None => VersionField::Absent,
            Some(v) => v
                .as_str()
                .map(|s| VersionField::Concrete(s.to_string()))
                .ok_or_else(|| anyhow::anyhow!("Version field must be a string"))?,
        }
    };

    Ok((name, version))
}

/// Update the version in a Cargo.toml file, preserving formatting
///
/// This function will update the version in the Cargo.toml file at the given path.
/// It will preserve the existing formatting of the version field, including comments.
///
/// # Arguments
/// * `path` - The path to the Cargo.toml file to update.
pub fn update_version(path: &Path, new_version: &VersionField) -> Result<()> {
    let new_version = match new_version {
        VersionField::Concrete(version) => version,
        _ => return Ok(()),
    };

    let content = fs::read_to_string(path). //-
        with_context(|| format!("Failed to read {}", path.display()))?;

    let mut doc = content
        .parse::<DocumentMut>()
        .with_context(|| format!("Failed to parse {}", path.display()))?;

    let package = get_package_section_mut(&mut doc).ok_or_else(|| {
        anyhow::anyhow!(
            "No workspace or package section found in {}",
            path.display()
        )
    })?;

    // Get the existing decor (comments) from the version field
    let decor = package
        .get("version")
        .and_then(|v| v.as_value())
        .map(|v| v.decor().clone());

    // Create new value with the same decor
    let mut new_value = Value::String(Formatted::new(new_version.to_string()));
    if let Some(d) = decor {
        if let Some(prefix_str) = d.prefix().and_then(|p| p.as_str()) {
            new_value.decor_mut().set_prefix(prefix_str.to_string());
        }
        if let Some(suffix_str) = d.suffix().and_then(|s| s.as_str()) {
            new_value.decor_mut().set_suffix(suffix_str.to_string());
        }
    }

    package["version"] = Item::Value(new_value);

    fs::write(path, doc.to_string())
        .with_context(|| format!("Failed to write {}", path.display()))?;

    Ok(())
}

/// Get the package section from either workspace.package or package
fn get_package_section(doc: &DocumentMut) -> Option<&Item> {
    // Try workspace.package first (virtual workspace)
    if let Some(pkg) = doc.get("workspace").and_then(|w| w.get("package")) {
        Some(pkg)
    } else {
        // Fall back to regular package (including root package in workspace)
        doc.get("package")
    }
}

/// Get a mutable reference to the package section from either workspace.package or package
fn get_package_section_mut(doc: &mut DocumentMut) -> Option<&mut Item> {
    // Check if workspace.package exists first (without mutable borrow)
    let has_workspace_package = doc
        .get("workspace")
        .and_then(|w| w.get("package"))
        .is_some();

    if has_workspace_package {
        // Try workspace.package first (virtual workspace)
        doc.get_mut("workspace").and_then(|w| w.get_mut("package"))
    } else {
        // Fall back to regular package (including root package in workspace)
        doc.get_mut("package")
    }
}

/// Check if a field uses workspace inheritance (field = { workspace = true })
///
/// Handles both regular tables and inline tables since Cargo can use either:
/// - `version = { workspace = true }` (inline table)
/// - `[package.version] workspace = true` (regular table)
fn uses_workspace_inheritance(doc: &DocumentMut, section: &str, field: &str) -> bool {
    doc.get("workspace").is_none()
        && doc
            .get(section)
            .and_then(|s| s.get(field))
            .and_then(|value| {
                // Check both regular tables and inline tables for workspace = true
                if let Some(table) = value.as_table() {
                    table.get("workspace").and_then(|w| w.as_bool())
                } else if let Some(inline_table) = value.as_inline_table() {
                    inline_table.get("workspace").and_then(|w| w.as_bool())
                } else {
                    None
                }
            })
            .unwrap_or(false)
}

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

    fn write_temp_toml(contents: &str) -> NamedTempFile {
        let mut file = NamedTempFile::new().unwrap();
        write!(file, "{}", contents).unwrap();
        file
    }

    #[test]
    fn test_parse_basic_package() {
        let toml = r#"
            [package]
            name = "my-package"
            version = "1.2.3"
        "#;
        let file = write_temp_toml(toml);
        let (name, version) = parse(file.path()).unwrap();
        assert_eq!(name, Some("my-package".to_string()));
        assert_eq!(version, VersionField::Concrete("1.2.3".to_string()));
    }

    #[test]
    fn test_parse_workspace_inheritance_one() {
        let toml = r#"
            [package]
            name = "my-package"
            version = { workspace = true }
        "#;
        let file = write_temp_toml(toml);
        let (name, version) = parse(file.path()).unwrap();
        assert_eq!(name, Some("my-package".to_string()));
        assert_eq!(version, VersionField::Inherited);
    }

    #[test]
    fn test_parse_workspace_inheritance_two() {
        let toml = r#"
            [package]
            name = "my-package"
            version.workspace = true
        "#;
        let file = write_temp_toml(toml);
        let (name, version) = parse(file.path()).unwrap();
        assert_eq!(name, Some("my-package".to_string()));
        assert_eq!(version, VersionField::Inherited);
    }

    #[test]
    fn test_update_version_basic() {
        let toml = r#"
            [package]
            name = "my-package"
            version = "1.2.3"
        "#;
        let file = write_temp_toml(toml);
        let new_version = VersionField::Concrete("2.0.0".to_string());
        update_version(file.path(), &new_version).unwrap();
        let content = fs::read_to_string(file.path()).unwrap();
        assert!(content.contains("version = \"2.0.0\""));
    }

    #[test]
    fn test_update_version_workspace_inheritance() {
        let toml = r#"
            [package]
            name = "my-package"
            version = { workspace = true }
        "#;
        let file = write_temp_toml(toml);
        let new_version = VersionField::Concrete("2.0.0".to_string());
        update_version(file.path(), &new_version).unwrap();
        let content = fs::read_to_string(file.path()).unwrap();
        assert!(content.contains("version = \"2.0.0\""));
    }

    // Workspace package tests
    #[test]
    fn test_parse_workspace_package() {
        let toml = r#"
            [workspace.package]
            name = "workspace-package"
            version = "1.0.0"
            
            [workspace]
            members = ["crate1", "crate2"]
        "#;
        let file = write_temp_toml(toml);
        let (name, version) = parse(file.path()).unwrap();
        assert_eq!(name, Some("workspace-package".to_string()));
        assert_eq!(version, VersionField::Concrete("1.0.0".to_string()));
    }

    #[test]
    fn test_update_workspace_package_version() {
        let toml = r#"
            [workspace.package]
            name = "workspace-package"
            version = "1.0.0"
            
            [workspace]
            members = ["crate1"]
        "#;
        let file = write_temp_toml(toml);
        let new_version = VersionField::Concrete("2.0.0".to_string());
        update_version(file.path(), &new_version).unwrap();
        let content = fs::read_to_string(file.path()).unwrap();
        assert!(content.contains("version = \"2.0.0\""));
    }

    // Edge cases and missing fields
    #[test]
    fn test_parse_package_missing_name() {
        let toml = r#"
            [package]
            version = "1.2.3"
        "#;
        let file = write_temp_toml(toml);
        let (name, version) = parse(file.path()).unwrap();
        assert_eq!(name, None);
        assert_eq!(version, VersionField::Concrete("1.2.3".to_string()));
    }

    #[test]
    fn test_parse_package_missing_version() {
        let toml = r#"
            [package]
            name = "my-package"
        "#;
        let file = write_temp_toml(toml);
        let (name, version) = parse(file.path()).unwrap();
        assert_eq!(name, Some("my-package".to_string()));
        assert_eq!(version, VersionField::Absent);
    }

    // Error cases
    #[test]
    fn test_parse_no_package_or_workspace() {
        let toml = r#"
            [dependencies]
            serde = "1.0"
        "#;
        let file = write_temp_toml(toml);
        let (name, version) = parse(file.path()).unwrap();
        assert_eq!(name, None);
        assert_eq!(version, VersionField::Absent);
    }

    #[test]
    fn test_update_version_no_package_or_workspace() {
        let toml = r#"
            [dependencies]
            serde = "1.0"
        "#;
        let file = write_temp_toml(toml);
        let new_version = VersionField::Concrete("2.0.0".to_string());
        let result = update_version(file.path(), &new_version);
        assert!(result.is_err());
        assert!(result
            .unwrap_err()
            .to_string()
            .contains("No workspace or package section found"));
    }

    #[test]
    fn test_parse_invalid_toml() {
        let toml = r#"
            [package
            name = "invalid"
        "#;
        let file = write_temp_toml(toml);
        let result = parse(file.path());
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("Failed to parse"));
    }

    // Workspace inheritance edge cases
    #[test]
    fn test_workspace_inheritance_false() {
        let toml = r#"
            [package]
            name = "my-package"
            version = "1.0.0"
        "#;
        let file = write_temp_toml(toml);
        let (name, version) = parse(file.path()).unwrap();
        assert_eq!(name, Some("my-package".to_string()));
        assert_eq!(version, VersionField::Concrete("1.0.0".to_string()));
    }

    #[test]
    fn test_workspace_inheritance_with_other_fields() {
        let toml = r#"
            [package]
            name = "my-package"
            version = { workspace = true, optional = true }
        "#;
        let file = write_temp_toml(toml);
        let (name, version) = parse(file.path()).unwrap();
        assert_eq!(name, Some("my-package".to_string()));
        assert_eq!(version, VersionField::Inherited);
    }

    // Formatting preservation test
    #[test]
    fn test_update_version_preserves_formatting() {
        let toml = r#"
# This is a comment
[package]
name = "my-package"
version = "1.2.3"  # inline comment
description = "A test package"
        "#;
        let file = write_temp_toml(toml);
        let new_version = VersionField::Concrete("2.0.0".to_string());
        update_version(file.path(), &new_version).unwrap();
        let content = fs::read_to_string(file.path()).unwrap();

        // Check that version was updated
        assert!(content.contains("version = \"2.0.0\""));
        // Check that comments are preserved
        assert!(content.contains("# This is a comment"));
        assert!(content.contains("# inline comment"));
        // Check that other fields are preserved
        assert!(content.contains("description = \"A test package\""));
    }

    // File I/O error cases (harder to test, but worth mentioning)
    #[test]
    fn test_parse_nonexistent_file() {
        let result = parse(Path::new("/nonexistent/path/Cargo.toml"));
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("Failed to read"));
    }

    #[test]
    fn test_parse_version_with_comments() {
        let toml = r#"
            [package]
            # This is a comment
            name = "my-package"
            # Version comment
            version = "1.2.3" # Inline comment
        "#;
        let file = write_temp_toml(toml);
        let (name, version) = parse(file.path()).unwrap();
        assert_eq!(name, Some("my-package".to_string()));
        assert_eq!(version, VersionField::Concrete("1.2.3".to_string()));
    }

    #[test]
    fn test_parse_version_with_whitespace() {
        let toml = r#"
            [package]
            name = "my-package"
            version = "1.2.3"  
        "#;
        let file = write_temp_toml(toml);
        let (name, version) = parse(file.path()).unwrap();
        assert_eq!(name, Some("my-package".to_string()));
        assert_eq!(version, VersionField::Concrete("1.2.3".to_string()));
    }

    #[test]
    fn test_parse_workspace_inheritance_invalid_value() {
        // Test that using a string "true" instead of boolean true for workspace inheritance
        // is rejected, as per Cargo.toml schema
        let toml = r#"
            [package]
            name = "my-package"
            version = { workspace = "true" }
        "#;
        let file = write_temp_toml(toml);
        let result = parse(file.path());
        assert!(result.is_err());
        assert!(result
            .unwrap_err()
            .to_string()
            .contains("Version field must be a string"));
    }

    #[test]
    fn test_parse_workspace_inheritance_with_additional_fields() {
        let toml = r#"
            [package]
            name = "my-package"
            version = { workspace = true, other = "value" }
        "#;
        let file = write_temp_toml(toml);
        let (name, version) = parse(file.path()).unwrap();
        assert_eq!(name, Some("my-package".to_string()));
        assert_eq!(version, VersionField::Inherited);
    }

    #[test]
    fn test_parse_workspace_only_no_package() {
        let toml = r#"
            [workspace]
            members = ["crate1"]
        "#;
        let file = write_temp_toml(toml);
        let (name, version) = parse(file.path()).unwrap();
        assert_eq!(name, None);
        assert_eq!(version, VersionField::Absent);
    }

    #[test]
    fn test_parse_both_workspace_and_package() {
        let toml = r#"
            [workspace.package]
            name = "workspace-package"
            version = "1.0.0"
            
            [package]
            name = "my-package"
            version = "2.0.0"
        "#;
        let file = write_temp_toml(toml);
        let (name, version) = parse(file.path()).unwrap();
        assert_eq!(name, Some("workspace-package".to_string()));
        assert_eq!(version, VersionField::Concrete("1.0.0".to_string()));
    }

    #[test]
    fn test_update_version_preserves_inline_table() {
        let toml = r#"
            [package]
            name = "my-package"
            version = { workspace = true, other = "value" }
        "#;
        let file = write_temp_toml(toml);
        let new_version = VersionField::Concrete("2.0.0".to_string());
        update_version(file.path(), &new_version).unwrap();
        let content = fs::read_to_string(file.path()).unwrap();
        assert!(content.contains("version = \"2.0.0\""));
    }

    #[test]
    fn test_parse_version_invalid_semver() {
        let toml = r#"
            [package]
            name = "my-package"
            version = "not-a-version"
        "#;
        let file = write_temp_toml(toml);
        let (name, version) = parse(file.path()).unwrap();
        assert_eq!(name, Some("my-package".to_string()));
        assert_eq!(version, VersionField::Concrete("not-a-version".to_string()));
    }

    // Bug reproduction tests - mixed workspace with root package
    #[test]
    fn test_parse_mixed_workspace_with_root_package() {
        // This reproduces the elf-magic bug: workspace with members but also a root package
        let toml = r#"
            [workspace]
            members = [".", "ecosystem/*"]
            
            [package]
            name = "elf-magic"
            version = "0.3.1"
        "#;
        let file = write_temp_toml(toml);
        let (name, version) = parse(file.path()).unwrap();

        // Currently FAILS: returns (None, Absent) because get_package_section only looks for workspace.package
        // Should PASS: return ("elf-magic", "0.3.1") because there's a [package] section
        assert_eq!(name, Some("elf-magic".to_string()));
        assert_eq!(version, VersionField::Concrete("0.3.1".to_string()));
    }

    #[test]
    fn test_update_mixed_workspace_with_root_package() {
        // Test that update_version works for mixed workspace + root package
        let toml = r#"
            [workspace]
            members = [".", "ecosystem/*"]
            
            [package]
            name = "elf-magic"
            version = "0.3.1"
        "#;
        let file = write_temp_toml(toml);
        let new_version = VersionField::Concrete("0.4.0".to_string());

        // First verify we can parse (this should fail with current code)
        let (name, version) = parse(file.path()).unwrap();
        println!("Parsed: name={:?}, version={:?}", name, version);

        // This should also fail because get_package_section_mut should return None
        update_version(file.path(), &new_version).unwrap();
        let content = fs::read_to_string(file.path()).unwrap();
        println!("Updated content: {}", content);
        assert!(content.contains("version = \"0.4.0\""));
    }

    // Regression tests - ensure our fix doesn't break existing behavior
    #[test]
    fn test_virtual_workspace_precedence_over_package() {
        // When both [workspace.package] AND [package] exist, workspace.package should win
        let toml = r#"
            [workspace.package]
            name = "workspace-pkg"
            version = "2.0.0"
            
            [workspace]
            members = ["crate1"]
            
            [package]
            name = "regular-pkg"
            version = "1.0.0"
        "#;
        let file = write_temp_toml(toml);
        let (name, version) = parse(file.path()).unwrap();

        // Should prioritize workspace.package over package
        assert_eq!(name, Some("workspace-pkg".to_string()));
        assert_eq!(version, VersionField::Concrete("2.0.0".to_string()));
    }

    #[test]
    fn test_virtual_workspace_update_precedence() {
        // Ensure update_version targets workspace.package when both sections exist
        let toml = r#"
            [workspace.package]
            name = "workspace-pkg"
            version = "2.0.0"
            
            [workspace]
            members = ["crate1"]
            
            [package]
            name = "regular-pkg"
            version = "1.0.0"
        "#;
        let file = write_temp_toml(toml);
        let new_version = VersionField::Concrete("3.0.0".to_string());

        update_version(file.path(), &new_version).unwrap();
        let content = fs::read_to_string(file.path()).unwrap();

        // Should update workspace.package, not package
        assert!(content.contains("[workspace.package]"));
        assert!(content.contains("workspace-pkg"));
        assert!(content.contains("version = \"3.0.0\""));
        // Package section should remain unchanged
        assert!(content.contains("version = \"1.0.0\""));
    }

    #[test]
    fn test_regular_package_still_works() {
        // Ensure regular packages (no workspace) still work correctly
        let toml = r#"
            [package]
            name = "simple-pkg"
            version = "1.5.0"
            
            [dependencies]
            serde = "1.0"
        "#;
        let file = write_temp_toml(toml);

        // Parse should work
        let (name, version) = parse(file.path()).unwrap();
        assert_eq!(name, Some("simple-pkg".to_string()));
        assert_eq!(version, VersionField::Concrete("1.5.0".to_string()));

        // Update should work
        let new_version = VersionField::Concrete("1.6.0".to_string());
        update_version(file.path(), &new_version).unwrap();
        let content = fs::read_to_string(file.path()).unwrap();
        assert!(content.contains("version = \"1.6.0\""));
        assert!(content.contains("simple-pkg"));
    }
}