cvm_cli 1.1.2

A powerful command-line tool for managing semantic versioning of Rust crates. Easily bump versions (major, minor, patch), update Cargo.toml files, and streamline your release workflow with automated version management.
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
use anyhow::{Context, Result};
use semver::Version;
use std::collections::HashMap;
use std::fs;
use std::fs::OpenOptions;
use std::io::Write;
use std::time::{SystemTime, UNIX_EPOCH};
use toml::{Table, Value};

use crate::config;
use crate::project::{analyze_project, uses_workspace_version, CrateInfo};

/// Generate the TOML content for a pending change without writing it to disk.
pub fn generate_pending_toml(
    summary: &str,
    major: &[CrateInfo],
    minor: &[CrateInfo],
    patch: &[CrateInfo],
) -> Result<String> {
    let mut config = Table::new();
    let mut update_table = Table::new();
    update_table.insert("summary".to_string(), Value::String(summary.to_string()));
    update_table.insert(
        "major".to_string(),
        Value::Array(
            major
                .iter()
                .map(|c| Value::String(c.name.clone()))
                .collect(),
        ),
    );
    update_table.insert(
        "minor".to_string(),
        Value::Array(
            minor
                .iter()
                .map(|c| Value::String(c.name.clone()))
                .collect(),
        ),
    );
    update_table.insert(
        "patch".to_string(),
        Value::Array(
            patch
                .iter()
                .map(|c| Value::String(c.name.clone()))
                .collect(),
        ),
    );
    let is_prerelease = config::is_prerelease_enabled();
    update_table.insert("pre".to_string(), Value::Boolean(is_prerelease));
    config.insert("update".to_string(), Value::Table(update_table));
    toml::to_string(&config).with_context(|| "Failed to serialize config")
}

pub fn save_pending(
    summary: &str,
    major: &[CrateInfo],
    minor: &[CrateInfo],
    patch: &[CrateInfo],
) -> Result<()> {
    config::init_cvm_dir()?;
    let timestamp = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap()
        .as_secs();
    let filename = format!(".cvm/changes/{}.toml", timestamp);
    let config_content = generate_pending_toml(summary, major, minor, patch)?;
    let mut file = OpenOptions::new()
        .create(true)
        .write(true)
        .truncate(true)
        .open(&filename)?;
    file.write_all(config_content.as_bytes())?;
    file.sync_all()?;
    Ok(())
}

/// Replace version in TOML content while preserving formatting
fn replace_version_in_toml(content: &str, old_version: &str, new_version: &str) -> Result<String> {
    // Find and replace version = "old" with version = "new"
    // This preserves all formatting, comments, and order
    let version_patterns = [
        format!(r#"version = "{}""#, old_version),
        format!(r#"version="{}""#, old_version),
        format!(r#"version = '{}'"#, old_version),
        format!(r#"version='{}'"#, old_version),
    ];

    let replacements = [
        format!(r#"version = "{}""#, new_version),
        format!(r#"version="{}""#, new_version),
        format!(r#"version = '{}'"#, new_version),
        format!(r#"version='{}'"#, new_version),
    ];

    for (pattern, replacement) in version_patterns.iter().zip(replacements.iter()) {
        if content.contains(pattern) {
            // Only replace the first occurrence (in [package] section)
            let new_content = content.replacen(pattern, replacement, 1);
            return Ok(new_content);
        }
    }

    Err(anyhow::anyhow!(
        "Could not find version = \"{}\" in Cargo.toml",
        old_version
    ))
}

/// Like [`replace_version_in_toml`], but updates every matching `version = "…"` entry.
fn replace_all_versions_in_toml(
    content: &str,
    old_version: &str,
    new_version: &str,
) -> Result<String> {
    let version_patterns = [
        format!(r#"version = "{}""#, old_version),
        format!(r#"version="{}""#, old_version),
        format!(r#"version = '{}'"#, old_version),
        format!(r#"version='{}'"#, old_version),
    ];

    let replacements = [
        format!(r#"version = "{}""#, new_version),
        format!(r#"version="{}""#, new_version),
        format!(r#"version = '{}'"#, new_version),
        format!(r#"version='{}'"#, new_version),
    ];

    let mut result = content.to_string();
    let mut replaced = false;
    for (pattern, replacement) in version_patterns.iter().zip(replacements.iter()) {
        if result.contains(pattern) {
            result = result.replace(pattern, replacement);
            replaced = true;
        }
    }

    if replaced {
        Ok(result)
    } else {
        Err(anyhow::anyhow!(
            "Could not find version = \"{}\" in Cargo.toml",
            old_version
        ))
    }
}

/// Apply a single bump to a crate, respecting prerelease mode
fn apply_bump(
    crate_path: &str,
    crate_name: &str,
    bump_type: &str,
    is_prerelease: bool,
    prerelease_id: Option<&str>,
) -> Result<String> {
    let (manifest_path, current_version_str) =
        crate::project::resolve_version_for_crate(crate_path)?;
    let content = fs::read_to_string(&manifest_path)
        .with_context(|| format!("Failed to read {}", manifest_path))?;

    let current_version = Version::parse(&current_version_str)
        .with_context(|| format!("Invalid version: {}", current_version_str))?;

    let new_version_str = if is_prerelease {
        let tag = prerelease_id.context("Prerelease mode but no identifier")?;

        // Get the stored base version from when we entered prerelease mode
        let base_versions = config::get_base_versions();
        let stored_base = base_versions.get(crate_name);

        // Current version without prerelease
        let current_base = Version::new(
            current_version.major,
            current_version.minor,
            current_version.patch,
        );

        // Determine what the base version should be after this bump
        let (target_base, should_reset_number) = if bump_type == "patch" {
            // Patch in prerelease mode: always keep current base, increment prerelease number
            (current_base.clone(), false)
        } else if let Some(base_str) = stored_base {
            // Minor/Major: calculate new base from stored base
            let stored = Version::parse(base_str)
                .with_context(|| format!("Invalid stored base version: {}", base_str))?;

            let new_base = match bump_type {
                "major" => Version::new(stored.major + 1, 0, 0),
                "minor" => Version::new(stored.major, stored.minor + 1, 0),
                _ => current_base.clone(),
            };

            // If the new base is different from current, reset prerelease number
            (new_base.clone(), new_base != current_base)
        } else {
            // No stored base (shouldn't happen), calculate from current
            let new_base = match bump_type {
                "major" => Version::new(current_base.major + 1, 0, 0),
                "minor" => Version::new(current_base.major, current_base.minor + 1, 0),
                _ => current_base.clone(),
            };
            (new_base.clone(), new_base != current_base)
        };

        // Determine the prerelease number
        let prerelease_number = if should_reset_number {
            // Base changed, start from 0
            0
        } else {
            // Base stayed the same, increment the number
            if !current_version.pre.is_empty() && current_version_str.contains(&format!("-{}", tag))
            {
                // Parse current prerelease number
                let pre_str = current_version.pre.as_str();
                if let Some(num_part) = pre_str.strip_prefix(&format!("{}.", tag)) {
                    if let Some(dot_pos) = num_part.find('.') {
                        num_part[..dot_pos].parse::<u64>().unwrap_or(0) + 1
                    } else {
                        num_part.parse::<u64>().unwrap_or(0) + 1
                    }
                } else {
                    0
                }
            } else {
                0
            }
        };

        format!("{}-{}.{}", target_base, tag, prerelease_number)
    } else {
        // Regular bump (no prerelease)
        match bump_type {
            "major" => format!("{}.0.0", current_version.major + 1),
            "minor" => format!("{}.{}.0", current_version.major, current_version.minor + 1),
            "patch" => format!(
                "{}.{}.{}",
                current_version.major,
                current_version.minor,
                current_version.patch + 1
            ),
            _ => {
                return Err(anyhow::anyhow!(
                    "Invalid bump type: {}. Use major, minor or patch.",
                    bump_type
                ))
            }
        }
    };

    let workspace_root = uses_workspace_version(crate_path)?;
    let new_content = if workspace_root {
        replace_all_versions_in_toml(&content, &current_version_str, &new_version_str)?
    } else {
        replace_version_in_toml(&content, &current_version_str, &new_version_str)?
    };

    let mut file = OpenOptions::new()
        .create(true)
        .write(true)
        .truncate(true)
        .open(&manifest_path)?;
    file.write_all(new_content.as_bytes())?;
    file.sync_all()?;

    Ok(new_version_str)
}

/// Check for pending changes and print summary
pub fn check_pending_changes() -> Result<()> {
    let changes_dir = std::path::Path::new(".cvm/changes");
    if !changes_dir.exists() {
        println!("No pending changes.");
        return Ok(());
    }

    let mut entries: Vec<_> = std::fs::read_dir(changes_dir)
        .with_context(|| "Failed to read changes directory")?
        .collect::<Result<Vec<_>, _>>()?;
    entries.sort_by_key(|e| e.file_name());

    let toml_entries: Vec<_> = entries
        .iter()
        .filter(|e| e.path().extension() == Some(std::ffi::OsStr::new("toml")))
        .collect();

    if toml_entries.is_empty() {
        println!("No pending changes.");
        return Ok(());
    }

    println!("Found {} pending change(s):\n", toml_entries.len());

    for (idx, entry) in toml_entries.iter().enumerate() {
        let path = entry.path();
        let content = fs::read_to_string(&path)
            .with_context(|| format!("Failed to read {}", path.display()))?;
        let config: Table = toml::from_str(&content)
            .with_context(|| format!("Failed to parse {}", path.display()))?;

        let update = config
            .get("update")
            .and_then(|u| u.as_table())
            .context("No update section in config")?;

        let summary = update
            .get("summary")
            .and_then(|s| s.as_str())
            .unwrap_or("(no summary)");

        let is_pre = update.get("pre").and_then(|p| p.as_bool()).unwrap_or(false);

        println!("{}. {}", idx + 1, summary);
        if is_pre {
            println!("   Mode: prerelease");
        }

        let empty_array = vec![];
        let major_crates = update
            .get("major")
            .and_then(|m| m.as_array())
            .unwrap_or(&empty_array);
        let minor_crates = update
            .get("minor")
            .and_then(|m| m.as_array())
            .unwrap_or(&empty_array);
        let patch_crates = update
            .get("patch")
            .and_then(|p| p.as_array())
            .unwrap_or(&empty_array);

        if !major_crates.is_empty() {
            println!("   Major: {:?}", major_crates);
        }
        if !minor_crates.is_empty() {
            println!("   Minor: {:?}", minor_crates);
        }
        if !patch_crates.is_empty() {
            println!("   Patch: {:?}", patch_crates);
        }
        println!();
    }

    // Exit with code 1 to signal there are pending changes (useful for CI)
    std::process::exit(1);
}

pub fn load_and_apply_pending(dry_run: bool) -> Result<()> {
    let changes_dir = std::path::Path::new(".cvm/changes");
    if !changes_dir.exists() {
        println!("No pending updates found.");
        return Ok(());
    }

    let mut entries: Vec<_> = std::fs::read_dir(changes_dir)
        .with_context(|| "Failed to read changes directory")?
        .collect::<Result<Vec<_>, _>>()?;
    entries.sort_by_key(|e| e.file_name());

    if entries.is_empty() {
        println!("No pending updates found.");
        return Ok(());
    }

    if dry_run {
        println!("DRY RUN - No changes will be applied\n");
    }

    let all_crates = analyze_project()?;
    let crate_map: HashMap<String, &CrateInfo> =
        all_crates.iter().map(|c| (c.name.clone(), c)).collect();

    for entry in entries {
        let path = entry.path();
        if path.extension() == Some(std::ffi::OsStr::new("toml")) {
            let content = fs::read_to_string(&path)
                .with_context(|| format!("Failed to read {}", path.display()))?;
            let config: Table = toml::from_str(&content)
                .with_context(|| format!("Failed to parse {}", path.display()))?;

            let update = config
                .get("update")
                .and_then(|u| u.as_table())
                .context("No update section in config")?;

            let summary = update
                .get("summary")
                .and_then(|s| s.as_str())
                .context("No summary in update")?;

            let is_pre = update.get("pre").and_then(|p| p.as_bool()).unwrap_or(false);

            let prerelease_id = if is_pre {
                config::get_prerelease_identifier()
            } else {
                None
            };

            if dry_run {
                println!("[DRY RUN] Would apply: {}", summary);
            } else {
                println!("Applying update: {}", summary);
            }
            if is_pre {
                if let Some(id) = &prerelease_id {
                    println!("  (prerelease mode: {})", id);
                }
            }

            let empty_array = vec![];
            let major_crates = update
                .get("major")
                .and_then(|m| m.as_array())
                .unwrap_or(&empty_array);
            let minor_crates = update
                .get("minor")
                .and_then(|m| m.as_array())
                .unwrap_or(&empty_array);
            let patch_crates = update
                .get("patch")
                .and_then(|p| p.as_array())
                .unwrap_or(&empty_array);

            if !dry_run {
                let mut workspace_version_bumped = false;

                for crate_name in major_crates {
                    if let Some(name_str) = crate_name.as_str() {
                        if let Some(c) = crate_map.get(name_str) {
                            if workspace_version_bumped && uses_workspace_version(&c.path)? {
                                println!(
                                    "  {} major → (skipped; workspace version already bumped)",
                                    c.name
                                );
                                continue;
                            }
                            let new_version = apply_bump(
                                &c.path,
                                &c.name,
                                "major",
                                is_pre,
                                prerelease_id.as_deref(),
                            )?;
                            if uses_workspace_version(&c.path)? {
                                workspace_version_bumped = true;
                            }
                            println!("  {} major → {}", c.name, new_version);
                        }
                    }
                }

                for crate_name in minor_crates {
                    if let Some(name_str) = crate_name.as_str() {
                        if let Some(c) = crate_map.get(name_str) {
                            if workspace_version_bumped && uses_workspace_version(&c.path)? {
                                println!(
                                    "  {} minor → (skipped; workspace version already bumped)",
                                    c.name
                                );
                                continue;
                            }
                            let new_version = apply_bump(
                                &c.path,
                                &c.name,
                                "minor",
                                is_pre,
                                prerelease_id.as_deref(),
                            )?;
                            if uses_workspace_version(&c.path)? {
                                workspace_version_bumped = true;
                            }
                            println!("  {} minor → {}", c.name, new_version);
                        }
                    }
                }

                for crate_name in patch_crates {
                    if let Some(name_str) = crate_name.as_str() {
                        if let Some(c) = crate_map.get(name_str) {
                            if workspace_version_bumped && uses_workspace_version(&c.path)? {
                                println!(
                                    "  {} patch → (skipped; workspace version already bumped)",
                                    c.name
                                );
                                continue;
                            }
                            let new_version = apply_bump(
                                &c.path,
                                &c.name,
                                "patch",
                                is_pre,
                                prerelease_id.as_deref(),
                            )?;
                            if uses_workspace_version(&c.path)? {
                                workspace_version_bumped = true;
                            }
                            println!("  {} patch → {}", c.name, new_version);
                        }
                    }
                }

                std::fs::remove_file(&path)
                    .with_context(|| format!("Failed to remove {}", path.display()))?;
            } else {
                // Dry run: just show what would happen
                for crate_name in major_crates {
                    if let Some(name_str) = crate_name.as_str() {
                        if crate_map.contains_key(name_str) {
                            println!("  {} major", name_str);
                        }
                    }
                }
                for crate_name in minor_crates {
                    if let Some(name_str) = crate_name.as_str() {
                        if crate_map.contains_key(name_str) {
                            println!("  {} minor", name_str);
                        }
                    }
                }
                for crate_name in patch_crates {
                    if let Some(name_str) = crate_name.as_str() {
                        if crate_map.contains_key(name_str) {
                            println!("  {} patch", name_str);
                        }
                    }
                }
            }
        }
    }

    if dry_run {
        println!("\n[DRY RUN] No changes were made.");
    } else {
        println!("\nAll updates applied successfully!");
    }
    Ok(())
}