cyrup_release 0.5.4

Production-quality release management for Rust workspaces
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
//! Workspace version synchronization and update coordination.
//!
//! This module orchestrates atomic version updates across the entire workspace,
//! ensuring internal dependencies are properly synchronized.

use crate::error::{Result, VersionError};
use crate::version::{TomlEditor, TomlBackup};
use crate::workspace::WorkspaceInfo;
use semver::Version;
use std::collections::HashMap;
use std::path::PathBuf;

/// Coordinates version updates across the entire workspace
#[derive(Debug)]
pub struct VersionUpdater {
    /// Workspace information
    workspace: WorkspaceInfo,
    /// Created backups for rollback
    backups: Vec<TomlBackup>,
}

/// Result of a version update operation
#[derive(Debug, Clone)]
pub struct UpdateResult {
    /// Previous version before update
    pub previous_version: Version,
    /// New version after update
    pub new_version: Version,
    /// Number of packages updated
    pub packages_updated: usize,
    /// Number of internal dependencies updated
    pub dependencies_updated: usize,
    /// Files that were modified
    pub modified_files: Vec<PathBuf>,
}

/// Configuration for version update operations
#[derive(Debug, Clone)]
pub struct UpdateConfig {
    /// Whether to create backups before updating
    pub create_backups: bool,
    /// Whether to update internal dependency versions
    pub update_internal_dependencies: bool,
    /// Whether to preserve workspace inheritance where possible
    pub preserve_workspace_inheritance: bool,
}

impl Default for UpdateConfig {
    fn default() -> Self {
        Self {
            create_backups: true,
            update_internal_dependencies: true,
            preserve_workspace_inheritance: true,
        }
    }
}

impl VersionUpdater {
    /// Create a new version updater for the workspace
    pub fn new(workspace: WorkspaceInfo) -> Self {
        Self {
            workspace,
            backups: Vec::new(),
        }
    }

    /// Update workspace to new version with atomic operation
    pub fn update_workspace_version(
        &mut self,
        new_version: &Version,
        config: UpdateConfig,
    ) -> Result<UpdateResult> {
        let current_version = self.workspace.workspace_version()
            .and_then(|v| Version::parse(&v).map_err(|e| VersionError::ParseFailed {
                version: v,
                source: e,
            }.into()))?;

        // Validate version progression
        if new_version <= &current_version {
            return Err(VersionError::InvalidVersion {
                version: new_version.to_string(),
                reason: format!(
                    "New version '{}' must be greater than current version '{}'",
                    new_version, current_version
                ),
            }.into());
        }

        let mut modified_files = Vec::new();
        let mut packages_updated = 0;
        let mut dependencies_updated = 0;

        // Update workspace version in root Cargo.toml
        if let Err(e) = self.update_root_workspace_version(new_version, &config, &mut modified_files) {
            self.rollback_all_changes()?;
            return Err(e);
        }

        // Collect package data to avoid borrow conflicts
        let packages_to_update: Vec<(String, crate::workspace::PackageInfo)> =
            self.workspace.packages.iter()
                .map(|(name, info)| (name.clone(), info.clone()))
                .collect();

        // Update all packages in the workspace
        for (package_name, package_info) in packages_to_update {
            match self.update_package_version(
                &package_name,
                &package_info,
                new_version,
                &config,
                &mut modified_files,
                &mut packages_updated,
                &mut dependencies_updated,
            ) {
                Ok(()) => {}
                Err(e) => {
                    self.rollback_all_changes()?;
                    return Err(e);
                }
            }
        }

        Ok(UpdateResult {
            previous_version: current_version,
            new_version: new_version.clone(),
            packages_updated,
            dependencies_updated,
            modified_files,
        })
    }

    /// Update root workspace version
    fn update_root_workspace_version(
        &mut self,
        new_version: &Version,
        config: &UpdateConfig,
        modified_files: &mut Vec<PathBuf>,
    ) -> Result<()> {
        let workspace_cargo_toml = self.workspace.root.join("Cargo.toml");
        let mut editor = TomlEditor::open(&workspace_cargo_toml)?;

        // Create backup if requested
        if config.create_backups {
            self.backups.push(editor.create_backup());
        }

        // Update workspace version
        editor.update_workspace_version(new_version)?;
        editor.save()?;

        modified_files.push(workspace_cargo_toml);
        Ok(())
    }

    /// Update a single package and its dependencies
    fn update_package_version(
        &mut self,
        _package_name: &str,
        package_info: &crate::workspace::PackageInfo,
        new_version: &Version,
        config: &UpdateConfig,
        modified_files: &mut Vec<PathBuf>,
        packages_updated: &mut usize,
        dependencies_updated: &mut usize,
    ) -> Result<()> {
        let mut editor = TomlEditor::open(&package_info.cargo_toml_path)?;

        // Create backup if requested
        if config.create_backups {
            self.backups.push(editor.create_backup());
        }

        let mut package_modified = false;

        // Update package version if not using workspace inheritance
        if !editor.uses_workspace_version() || !config.preserve_workspace_inheritance {
            editor.update_package_version(new_version)?;
            package_modified = true;
            *packages_updated += 1;
        }

        // Update internal dependency versions if requested
        if config.update_internal_dependencies {
            let internal_deps_to_update = self.collect_internal_dependencies_to_update(package_info, new_version);
            
            for (dep_name, dep_version) in internal_deps_to_update {
                editor.update_dependency_version(&dep_name, &dep_version)?;
                package_modified = true;
                *dependencies_updated += 1;
            }
        }

        // Save changes if any modifications were made
        if package_modified {
            editor.save()?;
            modified_files.push(package_info.cargo_toml_path.clone());
        }

        Ok(())
    }

    /// Collect internal dependencies that need version updates
    fn collect_internal_dependencies_to_update(
        &self,
        package_info: &crate::workspace::PackageInfo,
        new_version: &Version,
    ) -> HashMap<String, Version> {
        let mut updates = HashMap::new();

        for dep_name in &package_info.workspace_dependencies {
            if self.workspace.packages.contains_key(dep_name) {
                // This is an internal workspace dependency, update its version
                updates.insert(dep_name.clone(), new_version.clone());
            }
        }

        updates
    }

    /// Rollback all changes made during the update
    pub fn rollback_all_changes(&self) -> Result<()> {
        let mut rollback_errors = Vec::new();

        // Restore all backups in reverse order
        for backup in self.backups.iter().rev() {
            if let Err(e) = TomlEditor::restore_from_backup(backup) {
                rollback_errors.push(format!("Failed to restore {}: {}", backup.file_path.display(), e));
            }
        }

        if !rollback_errors.is_empty() {
            return Err(VersionError::TomlUpdateFailed {
                path: PathBuf::from("multiple_files"),
                reason: format!("Rollback failures: {}", rollback_errors.join("; ")),
            }.into());
        }

        Ok(())
    }

    /// Clear all backups (call after successful operation)
    pub fn clear_backups(&mut self) {
        self.backups.clear();
    }

    /// Validate workspace version consistency
    pub fn validate_version_consistency(&self) -> Result<ConsistencyReport> {
        let workspace_version = self.workspace.workspace_version()
            .and_then(|v| Version::parse(&v).map_err(|e| VersionError::ParseFailed {
                version: v,
                source: e,
            }.into()))?;

        let mut inconsistencies = Vec::new();
        let mut packages_checked = 0;
        let mut dependencies_checked = 0;

        for (package_name, package_info) in &self.workspace.packages {
            // Skip packages with publish = false
            if let Some(toml::Value::Boolean(false)) = package_info.config.other.get("publish") {
                continue;
            }
            
            packages_checked += 1;

            // Check package version consistency
            if let Ok(package_version) = Version::parse(&package_info.version) {
                if package_version != workspace_version {
                    inconsistencies.push(VersionInconsistency {
                        package: package_name.clone(),
                        dependency: None,
                        expected_version: workspace_version.clone(),
                        actual_version: package_version,
                        inconsistency_type: InconsistencyType::PackageVersion,
                    });
                }
            }

            // Check internal dependency versions
            for dep_name in &package_info.workspace_dependencies {
                dependencies_checked += 1;

                if let Some(dep_spec) = package_info.all_dependencies.get(dep_name) {
                    if let Some(dep_version_str) = &dep_spec.version {
                        if let Ok(dep_version) = Version::parse(dep_version_str) {
                            if dep_version != workspace_version {
                                inconsistencies.push(VersionInconsistency {
                                    package: package_name.clone(),
                                    dependency: Some(dep_name.clone()),
                                    expected_version: workspace_version.clone(),
                                    actual_version: dep_version,
                                    inconsistency_type: InconsistencyType::DependencyVersion,
                                });
                            }
                        }
                    } else {
                        // Missing version specification for internal dependency
                        // This is only an inconsistency if the DEPENDENCY is publishable
                        // For publish=false dependencies, missing versions are correct
                        let dep_package = self.workspace.packages.get(dep_name);
                        let dep_is_publishable = dep_package
                            .and_then(|p| p.config.other.get("publish"))
                            .and_then(|v| v.as_bool())
                            .unwrap_or(true); // Default to true if not specified
                        
                        if dep_is_publishable {
                            inconsistencies.push(VersionInconsistency {
                                package: package_name.clone(),
                                dependency: Some(dep_name.clone()),
                                expected_version: workspace_version.clone(),
                                actual_version: Version::new(0, 0, 0), // Placeholder
                                inconsistency_type: InconsistencyType::MissingVersion,
                            });
                        }
                    }
                }
            }
        }

        Ok(ConsistencyReport {
            workspace_version,
            packages_checked,
            dependencies_checked,
            inconsistencies,
        })
    }

    /// Preview version update without making changes
    pub fn preview_update(&self, new_version: &Version) -> Result<UpdatePreview> {
        let current_version = self.workspace.workspace_version()
            .and_then(|v| Version::parse(&v).map_err(|e| VersionError::ParseFailed {
                version: v,
                source: e,
            }.into()))?;

        let mut files_to_modify = Vec::new();
        let mut packages_to_update = Vec::new();
        let mut dependencies_to_update = Vec::new();

        // Root workspace file
        files_to_modify.push(self.workspace.root.join("Cargo.toml"));

        // Check each package
        for (package_name, package_info) in &self.workspace.packages {
            let editor = TomlEditor::open(&package_info.cargo_toml_path)?;
            
            let mut package_changes = Vec::new();
            
            // Package version change
            if !editor.uses_workspace_version() {
                package_changes.push(VersionChange {
                    field: "version".to_string(),
                    from: current_version.clone(),
                    to: new_version.clone(),
                });
            }

            // Internal dependency changes
            for dep_name in &package_info.workspace_dependencies {
                if self.workspace.packages.contains_key(dep_name) {
                    package_changes.push(VersionChange {
                        field: format!("dependencies.{}", dep_name),
                        from: current_version.clone(),
                        to: new_version.clone(),
                    });
                    dependencies_to_update.push(DependencyUpdate {
                        package: package_name.clone(),
                        dependency: dep_name.clone(),
                        from: current_version.clone(),
                        to: new_version.clone(),
                    });
                }
            }

            if !package_changes.is_empty() {
                files_to_modify.push(package_info.cargo_toml_path.clone());
                packages_to_update.push(PackageUpdate {
                    name: package_name.clone(),
                    file_path: package_info.cargo_toml_path.clone(),
                    changes: package_changes,
                });
            }
        }

        Ok(UpdatePreview {
            from_version: current_version,
            to_version: new_version.clone(),
            files_to_modify,
            packages_to_update,
            dependencies_to_update,
        })
    }

    /// Get workspace information
    pub fn workspace(&self) -> &WorkspaceInfo {
        &self.workspace
    }

    /// Get number of backups created
    pub fn backup_count(&self) -> usize {
        self.backups.len()
    }
}

/// Report of version consistency across the workspace
#[derive(Debug, Clone)]
pub struct ConsistencyReport {
    /// Expected workspace version
    pub workspace_version: Version,
    /// Number of packages checked
    pub packages_checked: usize,
    /// Number of dependencies checked
    pub dependencies_checked: usize,
    /// Found inconsistencies
    pub inconsistencies: Vec<VersionInconsistency>,
}

/// A version inconsistency found during validation
#[derive(Debug, Clone)]
pub struct VersionInconsistency {
    /// Package where inconsistency was found
    pub package: String,
    /// Dependency name (if inconsistency is in dependency)
    pub dependency: Option<String>,
    /// Expected version
    pub expected_version: Version,
    /// Actual version found
    pub actual_version: Version,
    /// Type of inconsistency
    pub inconsistency_type: InconsistencyType,
}

/// Type of version inconsistency
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum InconsistencyType {
    /// Package version doesn't match workspace version
    PackageVersion,
    /// Internal dependency version doesn't match expected version
    DependencyVersion,
    /// Missing version specification for internal dependency
    MissingVersion,
}

/// Preview of version update operation
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct UpdatePreview {
    /// Current version
    pub from_version: Version,
    /// Target version
    pub to_version: Version,
    /// Files that will be modified
    pub files_to_modify: Vec<PathBuf>,
    /// Packages that will be updated
    pub packages_to_update: Vec<PackageUpdate>,
    /// Dependencies that will be updated
    pub dependencies_to_update: Vec<DependencyUpdate>,
}

/// Preview of package update
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct PackageUpdate {
    /// Package name
    pub name: String,
    /// Path to Cargo.toml file
    pub file_path: PathBuf,
    /// List of changes to be made
    pub changes: Vec<VersionChange>,
}

/// Preview of dependency update
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct DependencyUpdate {
    /// Package containing the dependency
    pub package: String,
    /// Dependency name
    pub dependency: String,
    /// Current version
    pub from: Version,
    /// Target version
    pub to: Version,
}

/// A single version change
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct VersionChange {
    /// Field being changed (e.g., "version", "dependencies.foo")
    pub field: String,
    /// Current version
    pub from: Version,
    /// Target version
    pub to: Version,
}

impl ConsistencyReport {
    /// Check if the workspace has any version inconsistencies
    pub fn is_consistent(&self) -> bool {
        self.inconsistencies.is_empty()
    }

    /// Get inconsistencies by type
    pub fn inconsistencies_by_type(&self, inconsistency_type: InconsistencyType) -> Vec<&VersionInconsistency> {
        self.inconsistencies
            .iter()
            .filter(|inc| inc.inconsistency_type == inconsistency_type)
            .collect()
    }

    /// Format report for display
    pub fn format_report(&self) -> String {
        if self.is_consistent() {
            format!(
                "✅ Workspace version consistency: {} packages and {} dependencies are all at version {}",
                self.packages_checked, self.dependencies_checked, self.workspace_version
            )
        } else {
            let mut report = format!(
                "❌ Found {} version inconsistencies (workspace version: {})\n",
                self.inconsistencies.len(), self.workspace_version
            );

            for inconsistency in &self.inconsistencies {
                let location = match &inconsistency.dependency {
                    Some(dep) => format!("{}::{}", inconsistency.package, dep),
                    None => inconsistency.package.clone(),
                };

                report.push_str(&format!(
                    "  - {}: expected {}, found {}\n",
                    location, inconsistency.expected_version, inconsistency.actual_version
                ));
            }

            report
        }
    }
}

impl UpdatePreview {
    /// Get total number of changes
    pub fn total_changes(&self) -> usize {
        self.packages_to_update.iter().map(|p| p.changes.len()).sum::<usize>()
            + self.dependencies_to_update.len()
    }

    /// Format preview for display
    pub fn format_preview(&self) -> String {
        let mut preview = format!(
            "Version update preview: {}{}\n",
            self.from_version, self.to_version
        );

        preview.push_str(&format!("Files to modify: {}\n", self.files_to_modify.len()));
        preview.push_str(&format!("Packages to update: {}\n", self.packages_to_update.len()));
        preview.push_str(&format!("Dependencies to update: {}\n", self.dependencies_to_update.len()));
        preview.push_str(&format!("Total changes: {}\n", self.total_changes()));

        if !self.packages_to_update.is_empty() {
            preview.push_str("\nPackages:\n");
            for package in &self.packages_to_update {
                preview.push_str(&format!("  - {}\n", package.name));
            }
        }

        preview
    }
}