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
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
//! Release state tracking and serialization.
//!
//! This module provides comprehensive state tracking for release operations,
//! enabling resume capabilities and rollback coordination.

use crate::error::{Result, StateError};
use crate::git::{CommitInfo, TagInfo, PushInfo};
use crate::publish::PublishResult;
use crate::version::{VersionBump, UpdateResult};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::path::PathBuf;

/// Current version of the state format (for migration)
pub const STATE_FORMAT_VERSION: u32 = 1;

/// Complete release operation state
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ReleaseState {
    /// Version of the state format
    pub format_version: u32,
    /// Unique ID for this release operation
    pub release_id: String,
    /// Version being released
    pub target_version: semver::Version,
    /// Type of version bump
    pub version_bump: VersionBump,
    /// Timestamp when release started
    pub started_at: chrono::DateTime<chrono::Utc>,
    /// Timestamp when release was last updated
    pub updated_at: chrono::DateTime<chrono::Utc>,
    /// Current phase of the release
    pub current_phase: ReleasePhase,
    /// Checkpoints passed during release
    pub checkpoints: Vec<ReleaseCheckpoint>,
    /// Version management state
    pub version_state: Option<VersionState>,
    /// Git operation state
    pub git_state: Option<GitState>,
    /// Publishing state
    pub publish_state: Option<PublishState>,
    /// Any errors encountered during release
    pub errors: Vec<ReleaseError>,
    /// Release configuration
    pub config: ReleaseConfig,
    /// Original package versions before release (for rollback)
    pub original_versions: Option<HashMap<String, String>>,
}

/// Phase of the release operation
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum ReleasePhase {
    /// Initial validation and preparation
    Validation,
    /// Version updating and file modifications
    VersionUpdate,
    /// Git operations (commit, tag)
    GitOperations,
    /// Package publishing
    Publishing,
    /// Post-release cleanup
    Cleanup,
    /// Release completed successfully
    Completed,
    /// Release failed and needs rollback
    Failed,
    /// Rollback in progress
    RollingBack,
    /// Rollback completed
    RolledBack,
}

/// Checkpoint in the release process
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ReleaseCheckpoint {
    /// Checkpoint name
    pub name: String,
    /// Phase this checkpoint belongs to
    pub phase: ReleasePhase,
    /// Timestamp when checkpoint was reached
    pub timestamp: chrono::DateTime<chrono::Utc>,
    /// Any data associated with this checkpoint
    pub data: Option<serde_json::Value>,
    /// Whether this checkpoint can be rolled back
    pub rollback_capable: bool,
}

/// Version management state
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct VersionState {
    /// Previous version before update
    pub previous_version: semver::Version,
    /// New version after update
    pub new_version: semver::Version,
    /// Result of version update operation
    pub update_result: Option<VersionUpdateInfo>,
    /// Files that were modified during version update
    pub modified_files: Vec<PathBuf>,
    /// Backup locations for rollback
    pub backup_files: Vec<FileBackup>,
}

/// Git operation state
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GitState {
    /// Previous HEAD commit before release
    pub previous_head: Option<String>,
    /// Commit created for this release
    pub release_commit: Option<GitCommitInfo>,
    /// Tag created for this release
    pub release_tag: Option<GitTagInfo>,
    /// Push information
    pub push_info: Option<GitPushInfo>,
    /// Whether git operations have been pushed to remote
    pub pushed_to_remote: bool,
}

/// Publishing state
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PublishState {
    /// Packages that have been successfully published
    pub published_packages: HashMap<String, PublishPackageInfo>,
    /// Packages that failed to publish
    pub failed_packages: HashMap<String, String>,
    /// Current tier being published
    pub current_tier: usize,
    /// Total tiers to publish
    pub total_tiers: usize,
    /// Publishing start time
    pub publishing_started_at: Option<chrono::DateTime<chrono::Utc>>,
}

/// Error encountered during release
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ReleaseError {
    /// Error message
    pub message: String,
    /// Phase where error occurred
    pub phase: ReleasePhase,
    /// Timestamp when error occurred
    pub timestamp: chrono::DateTime<chrono::Utc>,
    /// Whether this error is recoverable
    pub recoverable: bool,
    /// Stack trace or additional context
    pub context: Option<String>,
}

/// Release configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ReleaseConfig {
    /// Whether to perform dry run first
    pub dry_run_first: bool,
    /// Whether to push to remote
    pub push_to_remote: bool,
    /// Inter-package delay in milliseconds
    pub inter_package_delay_ms: u64,
    /// Registry to publish to
    pub registry: Option<String>,
    /// Whether to allow dirty working directory
    pub allow_dirty: bool,
    /// Additional configuration options
    pub additional_options: HashMap<String, serde_json::Value>,
}

/// Simplified version update information for serialization
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct VersionUpdateInfo {
    /// Number of packages updated
    pub packages_updated: usize,
    /// Number of dependencies updated
    pub dependencies_updated: usize,
    /// Duration in milliseconds
    pub duration_ms: u64,
}

/// Git commit information for serialization
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GitCommitInfo {
    /// Commit hash
    pub hash: String,
    /// Short commit hash
    pub short_hash: String,
    /// Commit message
    pub message: String,
    /// Author name
    pub author_name: String,
    /// Author email
    pub author_email: String,
    /// Commit timestamp
    pub timestamp: chrono::DateTime<chrono::Utc>,
}

/// Git tag information for serialization
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GitTagInfo {
    /// Tag name
    pub name: String,
    /// Tag message
    pub message: Option<String>,
    /// Target commit hash
    pub target_commit: String,
    /// Tag timestamp
    pub timestamp: chrono::DateTime<chrono::Utc>,
    /// Whether this is an annotated tag
    pub is_annotated: bool,
}

/// Git push information for serialization
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GitPushInfo {
    /// Remote name
    pub remote_name: String,
    /// Number of commits pushed
    pub commits_pushed: usize,
    /// Number of tags pushed
    pub tags_pushed: usize,
    /// Any warnings
    pub warnings: Vec<String>,
}

/// Information about a published package
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PublishPackageInfo {
    /// Package name
    pub package_name: String,
    /// Version published
    pub version: semver::Version,
    /// Duration of publish operation in milliseconds
    pub duration_ms: u64,
    /// Number of retry attempts
    pub retry_attempts: usize,
    /// Warnings from publish
    pub warnings: Vec<String>,
    /// Timestamp when published
    pub published_at: chrono::DateTime<chrono::Utc>,
}

/// File backup information
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FileBackup {
    /// Original file path
    pub file_path: PathBuf,
    /// Backup content
    pub backup_content: String,
    /// Timestamp of backup
    pub backup_timestamp: chrono::DateTime<chrono::Utc>,
}

impl ReleaseState {
    /// Create a new release state
    pub fn new(
        target_version: semver::Version,
        version_bump: VersionBump,
        config: ReleaseConfig,
    ) -> Self {
        let now = chrono::Utc::now();
        let release_id = format!("release-{}-{}", target_version, now.timestamp());

        Self {
            format_version: STATE_FORMAT_VERSION,
            release_id,
            target_version,
            version_bump,
            started_at: now,
            updated_at: now,
            current_phase: ReleasePhase::Validation,
            checkpoints: Vec::new(),
            version_state: None,
            git_state: None,
            publish_state: None,
            errors: Vec::new(),
            config,
            original_versions: None,
        }
    }

    /// Add a checkpoint to the release state
    pub fn add_checkpoint(
        &mut self,
        name: String,
        phase: ReleasePhase,
        data: Option<serde_json::Value>,
        rollback_capable: bool,
    ) {
        let checkpoint = ReleaseCheckpoint {
            name,
            phase,
            timestamp: chrono::Utc::now(),
            data,
            rollback_capable,
        };

        self.checkpoints.push(checkpoint);
        self.updated_at = chrono::Utc::now();
    }

    /// Set current phase
    pub fn set_phase(&mut self, phase: ReleasePhase) {
        self.current_phase = phase;
        self.updated_at = chrono::Utc::now();
    }

    /// Add an error to the release state
    pub fn add_error(
        &mut self,
        message: String,
        phase: ReleasePhase,
        recoverable: bool,
        context: Option<String>,
    ) {
        let error = ReleaseError {
            message,
            phase,
            timestamp: chrono::Utc::now(),
            recoverable,
            context,
        };

        self.errors.push(error);
        self.updated_at = chrono::Utc::now();
    }

    /// Update version state
    pub fn set_version_state(&mut self, update_result: &UpdateResult) {
        self.version_state = Some(VersionState {
            previous_version: update_result.previous_version.clone(),
            new_version: update_result.new_version.clone(),
            update_result: Some(VersionUpdateInfo {
                packages_updated: update_result.packages_updated,
                dependencies_updated: update_result.dependencies_updated,
                duration_ms: 0, // This would need to be tracked separately
            }),
            modified_files: update_result.modified_files.clone(),
            backup_files: Vec::new(), // This would be populated by the version manager
        });

        self.updated_at = chrono::Utc::now();
    }

    /// Set original package versions (for rollback support)
    pub fn set_original_versions(&mut self, versions: HashMap<String, String>) {
        self.original_versions = Some(versions);
        self.updated_at = chrono::Utc::now();
    }

    /// Update git state
    pub fn set_git_state(&mut self, commit: Option<&CommitInfo>, tag: Option<&TagInfo>) {
        if self.git_state.is_none() {
            self.git_state = Some(GitState {
                previous_head: None,
                release_commit: None,
                release_tag: None,
                push_info: None,
                pushed_to_remote: false,
            });
        }

        if let Some(git_state) = &mut self.git_state {
            if let Some(commit) = commit {
                git_state.release_commit = Some(GitCommitInfo {
                    hash: commit.hash.clone(),
                    short_hash: commit.short_hash.clone(),
                    message: commit.message.clone(),
                    author_name: commit.author_name.clone(),
                    author_email: commit.author_email.clone(),
                    timestamp: commit.timestamp,
                });
            }

            if let Some(tag) = tag {
                git_state.release_tag = Some(GitTagInfo {
                    name: tag.name.clone(),
                    message: tag.message.clone(),
                    target_commit: tag.target_commit.clone(),
                    timestamp: tag.timestamp,
                    is_annotated: tag.is_annotated,
                });
            }
        }

        self.updated_at = chrono::Utc::now();
    }

    /// Update git push state
    pub fn set_git_push_state(&mut self, push_info: &PushInfo) {
        if let Some(git_state) = &mut self.git_state {
            git_state.push_info = Some(GitPushInfo {
                remote_name: push_info.remote_name.clone(),
                commits_pushed: push_info.commits_pushed,
                tags_pushed: push_info.tags_pushed,
                warnings: push_info.warnings.clone(),
            });
            git_state.pushed_to_remote = true;
        }

        self.updated_at = chrono::Utc::now();
    }

    /// Initialize publishing state
    pub fn init_publish_state(&mut self, total_tiers: usize) {
        self.publish_state = Some(PublishState {
            published_packages: HashMap::new(),
            failed_packages: HashMap::new(),
            current_tier: 0,
            total_tiers,
            publishing_started_at: Some(chrono::Utc::now()),
        });

        self.updated_at = chrono::Utc::now();
    }

    /// Add published package
    pub fn add_published_package(&mut self, publish_result: &PublishResult) {
        if let Some(publish_state) = &mut self.publish_state {
            let package_info = PublishPackageInfo {
                package_name: publish_result.package_name.clone(),
                version: publish_result.version.clone(),
                duration_ms: publish_result.duration.as_millis() as u64,
                retry_attempts: publish_result.retry_attempts,
                warnings: publish_result.warnings.clone(),
                published_at: chrono::Utc::now(),
            };

            publish_state.published_packages.insert(
                publish_result.package_name.clone(),
                package_info,
            );
        }

        self.updated_at = chrono::Utc::now();
    }

    /// Add failed package
    pub fn add_failed_package(&mut self, package_name: String, error: String) {
        if let Some(publish_state) = &mut self.publish_state {
            publish_state.failed_packages.insert(package_name, error);
        }

        self.updated_at = chrono::Utc::now();
    }

    /// Set current publishing tier
    pub fn set_current_tier(&mut self, tier: usize) {
        if let Some(publish_state) = &mut self.publish_state {
            publish_state.current_tier = tier;
        }

        self.updated_at = chrono::Utc::now();
    }

    /// Check if release is resumable
    pub fn is_resumable(&self) -> bool {
        matches!(
            self.current_phase,
            ReleasePhase::Validation
                | ReleasePhase::VersionUpdate
                | ReleasePhase::GitOperations
                | ReleasePhase::Publishing
        ) && !self.has_critical_errors()
    }

    /// Check if release has critical errors
    pub fn has_critical_errors(&self) -> bool {
        self.errors.iter().any(|e| !e.recoverable)
    }

    /// Get rollback checkpoints (in reverse order)
    pub fn get_rollback_checkpoints(&self) -> Vec<&ReleaseCheckpoint> {
        self.checkpoints
            .iter()
            .filter(|cp| cp.rollback_capable)
            .rev()
            .collect()
    }

    /// Get progress percentage
    pub fn progress_percentage(&self) -> f64 {
        match self.current_phase {
            ReleasePhase::Validation => 10.0,
            ReleasePhase::VersionUpdate => 30.0,
            ReleasePhase::GitOperations => 50.0,
            ReleasePhase::Publishing => {
                if let Some(publish_state) = &self.publish_state {
                    if publish_state.total_tiers > 0 {
                        let tier_progress = (publish_state.current_tier as f64 / publish_state.total_tiers as f64) * 40.0;
                        50.0 + tier_progress
                    } else {
                        70.0
                    }
                } else {
                    70.0
                }
            }
            ReleasePhase::Cleanup => 95.0,
            ReleasePhase::Completed => 100.0,
            ReleasePhase::Failed | ReleasePhase::RollingBack | ReleasePhase::RolledBack => {
                // Progress doesn't apply to failure states
                0.0
            }
        }
    }

    /// Get elapsed time
    pub fn elapsed_time(&self) -> chrono::Duration {
        self.updated_at - self.started_at
    }

    /// Validate state consistency
    pub fn validate(&self) -> Result<()> {
        // Check format version
        if self.format_version != STATE_FORMAT_VERSION {
            return Err(StateError::VersionMismatch {
                expected: STATE_FORMAT_VERSION.to_string(),
                found: self.format_version.to_string(),
            }.into());
        }

        // Check that phase transitions make sense
        match self.current_phase {
            ReleasePhase::VersionUpdate => {
                if self.version_state.is_none() {
                    return Err(StateError::Corrupted {
                        reason: "Version update phase but no version state".to_string(),
                    }.into());
                }
            }
            ReleasePhase::GitOperations => {
                if self.git_state.is_none() {
                    return Err(StateError::Corrupted {
                        reason: "Git operations phase but no git state".to_string(),
                    }.into());
                }
            }
            ReleasePhase::Publishing => {
                if self.publish_state.is_none() {
                    return Err(StateError::Corrupted {
                        reason: "Publishing phase but no publish state".to_string(),
                    }.into());
                }
            }
            _ => {}
        }

        Ok(())
    }

    /// Create a summary of the release state
    pub fn summary(&self) -> String {
        let elapsed = self.elapsed_time();
        let progress = self.progress_percentage();

        format!(
            "Release v{} ({:?}) - {:.1}% complete - {} elapsed",
            self.target_version,
            self.current_phase,
            progress,
            format_duration(elapsed)
        )
    }
}

/// Format duration for display
fn format_duration(duration: chrono::Duration) -> String {
    let total_seconds = duration.num_seconds();
    let hours = total_seconds / 3600;
    let minutes = (total_seconds % 3600) / 60;
    let seconds = total_seconds % 60;

    if hours > 0 {
        format!("{}h {}m {}s", hours, minutes, seconds)
    } else if minutes > 0 {
        format!("{}m {}s", minutes, seconds)
    } else {
        format!("{}s", seconds)
    }
}

impl Default for ReleaseConfig {
    fn default() -> Self {
        Self {
            dry_run_first: true,
            push_to_remote: true,
            inter_package_delay_ms: 15000, // 15 seconds as requested
            registry: None,
            allow_dirty: false,
            additional_options: HashMap::new(),
        }
    }
}

impl std::fmt::Display for ReleasePhase {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            ReleasePhase::Validation => write!(f, "Validation"),
            ReleasePhase::VersionUpdate => write!(f, "Version Update"),
            ReleasePhase::GitOperations => write!(f, "Git Operations"),
            ReleasePhase::Publishing => write!(f, "Publishing"),
            ReleasePhase::Cleanup => write!(f, "Cleanup"),
            ReleasePhase::Completed => write!(f, "Completed"),
            ReleasePhase::Failed => write!(f, "Failed"),
            ReleasePhase::RollingBack => write!(f, "Rolling Back"),
            ReleasePhase::RolledBack => write!(f, "Rolled Back"),
        }
    }
}