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
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
//! Workspace validation for pre-release checks.
//!
//! This module performs comprehensive validation to ensure the workspace is ready
//! for release operations, preventing failures during the release process.

use crate::error::{Result, GitError, PublishError};
use crate::workspace::WorkspaceInfo;
use serde::{Deserialize, Serialize};
use std::path::PathBuf;
use std::process::Stdio;
use tokio::process::Command as AsyncCommand;

/// Comprehensive workspace validator
#[derive(Debug)]
pub struct WorkspaceValidator {
    workspace: WorkspaceInfo,
    repo_path: PathBuf,
}

/// Validation result with detailed pass/fail information
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ValidationResult {
    /// Overall validation success
    pub success: bool,
    /// Individual validation checks and their results
    pub checks: Vec<ValidationCheck>,
    /// Critical errors that must be fixed before release
    pub critical_errors: Vec<String>,
    /// Warnings that should be addressed but don't block release
    pub warnings: Vec<String>,
}

/// Individual validation check result
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ValidationCheck {
    /// Name of the validation check
    pub name: String,
    /// Whether this check passed
    pub passed: bool,
    /// Detailed message about the check result
    pub message: String,
    /// Whether this is a critical check (failure blocks release)
    pub critical: bool,
    /// Duration of the check in milliseconds
    pub duration_ms: u64,
}

impl WorkspaceValidator {
    /// Create a new workspace validator
    pub fn new(workspace: WorkspaceInfo) -> Result<Self> {
        let repo_path = workspace.root.clone();

        Ok(Self {
            workspace,
            repo_path,
        })
    }

    /// Perform comprehensive workspace validation
    pub async fn validate(&self) -> Result<ValidationResult> {
        let mut checks = Vec::new();
        let mut critical_errors = Vec::new();
        let mut warnings = Vec::new();

        // Git repository validation
        self.validate_git_state(&mut checks, &mut critical_errors).await?;

        // Version consistency validation
        self.validate_version_consistency(&mut checks, &mut critical_errors, &mut warnings).await?;

        // Build validation
        self.validate_builds(&mut checks, &mut critical_errors, &mut warnings).await?;

        // Credentials validation
        self.validate_credentials(&mut checks, &mut warnings).await?;

        // Dependency validation
        self.validate_dependencies(&mut checks, &mut critical_errors, &mut warnings).await?;

        // Crates.io validation
        self.validate_crates_io_readiness(&mut checks, &mut warnings).await?;

        let success = critical_errors.is_empty();

        Ok(ValidationResult {
            success,
            checks,
            critical_errors,
            warnings,
        })
    }

    /// Validate git repository state
    async fn validate_git_state(
        &self,
        checks: &mut Vec<ValidationCheck>,
        critical_errors: &mut Vec<String>,
    ) -> Result<()> {
        let start_time = std::time::Instant::now();

        // Check working directory status
        let status_result = self.check_working_directory_clean().await;
        let duration = start_time.elapsed().as_millis() as u64;

        match status_result {
            Ok(true) => {
                checks.push(ValidationCheck {
                    name: "Git Working Directory".to_string(),
                    passed: true,
                    message: "Working directory is clean".to_string(),
                    critical: true,
                    duration_ms: duration,
                });
            }
            Ok(false) => {
                let error_msg = "Working directory has uncommitted changes";
                checks.push(ValidationCheck {
                    name: "Git Working Directory".to_string(),
                    passed: false,
                    message: error_msg.to_string(),
                    critical: true,
                    duration_ms: duration,
                });
                critical_errors.push(error_msg.to_string());
            }
            Err(e) => {
                let error_msg = format!("Failed to check git status: {}", e);
                checks.push(ValidationCheck {
                    name: "Git Working Directory".to_string(),
                    passed: false,
                    message: error_msg.clone(),
                    critical: true,
                    duration_ms: duration,
                });
                critical_errors.push(error_msg);
            }
        }

        // Check if we're on a valid branch
        let branch_check_start = std::time::Instant::now();
        let branch_result = self.check_valid_branch().await;
        let branch_duration = branch_check_start.elapsed().as_millis() as u64;

        match branch_result {
            Ok(branch_name) => {
                checks.push(ValidationCheck {
                    name: "Git Branch".to_string(),
                    passed: true,
                    message: format!("On branch: {}", branch_name),
                    critical: false,
                    duration_ms: branch_duration,
                });
            }
            Err(e) => {
                let error_msg = format!("Invalid git branch state: {}", e);
                checks.push(ValidationCheck {
                    name: "Git Branch".to_string(),
                    passed: false,
                    message: error_msg.clone(),
                    critical: true,
                    duration_ms: branch_duration,
                });
                critical_errors.push(error_msg);
            }
        }

        Ok(())
    }

    /// Check if working directory is clean
    async fn check_working_directory_clean(&self) -> Result<bool> {
        // Use is_dirty() - the correct gix 0.73.0 API for status checking
        // Use git CLI to check status
        let output = AsyncCommand::new("git")
            .args(&["status", "--porcelain"])
            .current_dir(&self.repo_path)
            .output()
            .await
            .map_err(|e| GitError::OperationFailed {
                operation: "git status".to_string(),
                reason: e.to_string(),
            })?;
        
        if !output.status.success() {
            return Err(GitError::OperationFailed {
                operation: "git status".to_string(),
                reason: String::from_utf8_lossy(&output.stderr).to_string(),
            }.into());
        }
        
        // Return true if clean (empty output)
        Ok(output.stdout.is_empty())
    }

    /// Check if we're on a valid branch
    async fn check_valid_branch(&self) -> Result<String> {
        let output = AsyncCommand::new("git")
            .args(&["branch", "--show-current"])
            .current_dir(&self.repo_path)
            .output()
            .await
            .map_err(|e| GitError::OperationFailed {
                operation: "git branch".to_string(),
                reason: e.to_string(),
            })?;
        
        if !output.status.success() {
            return Err(GitError::OperationFailed {
                operation: "git branch".to_string(),
                reason: String::from_utf8_lossy(&output.stderr).to_string(),
            }.into());
        }
        
        let branch_name = String::from_utf8_lossy(&output.stdout).trim().to_string();
        if branch_name.is_empty() {
            Ok("detached HEAD".to_string())
        } else {
            Ok(branch_name)
        }
    }

    /// Validate version consistency across packages
    async fn validate_version_consistency(
        &self,
        checks: &mut Vec<ValidationCheck>,
        critical_errors: &mut Vec<String>,
        warnings: &mut Vec<String>,
    ) -> Result<()> {
        let start_time = std::time::Instant::now();

        let workspace_version = match self.workspace.workspace_version() {
            Ok(version) => version,
            Err(e) => {
                let error_msg = format!("Failed to get workspace version: {}", e);
                checks.push(ValidationCheck {
                    name: "Version Consistency".to_string(),
                    passed: false,
                    message: error_msg.clone(),
                    critical: true,
                    duration_ms: start_time.elapsed().as_millis() as u64,
                });
                critical_errors.push(error_msg);
                return Ok(());
            }
        };

        let mut version_mismatches = Vec::new();
        let mut dependency_version_issues = Vec::new();

        // Check each package's version
        for (package_name, package_info) in &self.workspace.packages {
            // Check if package version matches workspace version (if using workspace inheritance)
            if package_info.version != workspace_version {
                let mismatch = format!(
                    "Package '{}' version '{}' doesn't match workspace version '{}'",
                    package_name, package_info.version, workspace_version
                );
                version_mismatches.push(mismatch);
            }

            // Check internal dependency versions
            for dep_name in &package_info.workspace_dependencies {
                if let Some(dep_package) = self.workspace.packages.get(dep_name) {
                    if let Some(dep_spec) = package_info.all_dependencies.get(dep_name) {
                        if let Some(dep_version) = &dep_spec.version {
                            if dep_version != &dep_package.version {
                                let issue = format!(
                                    "Package '{}' depends on '{}' version '{}' but '{}' is at version '{}'",
                                    package_name, dep_name, dep_version, dep_name, dep_package.version
                                );
                                dependency_version_issues.push(issue);
                            }
                        }
                    }
                }
            }
        }

        let duration = start_time.elapsed().as_millis() as u64;

        if version_mismatches.is_empty() && dependency_version_issues.is_empty() {
            checks.push(ValidationCheck {
                name: "Version Consistency".to_string(),
                passed: true,
                message: format!("All packages consistent with workspace version {}", workspace_version),
                critical: true,
                duration_ms: duration,
            });
        } else {
            let mut message_parts = Vec::new();
            
            if !version_mismatches.is_empty() {
                message_parts.extend(version_mismatches.iter().cloned());
                critical_errors.extend(version_mismatches.clone());
            }
            
            if !dependency_version_issues.is_empty() {
                message_parts.extend(dependency_version_issues.iter().cloned());
                warnings.extend(dependency_version_issues);
            }

            checks.push(ValidationCheck {
                name: "Version Consistency".to_string(),
                passed: false,
                message: message_parts.join("; "),
                critical: !version_mismatches.is_empty(),
                duration_ms: duration,
            });
        }

        Ok(())
    }

    /// Validate that all packages can be built successfully
    async fn validate_builds(
        &self,
        checks: &mut Vec<ValidationCheck>,
        critical_errors: &mut Vec<String>,
        warnings: &mut Vec<String>,
    ) -> Result<()> {
        let start_time = std::time::Instant::now();

        let mut build_failures = Vec::new();
        let mut build_warnings = Vec::new();

        // Test build each package
        for (package_name, package_info) in &self.workspace.packages {
            match self.test_package_build(package_info).await {
                Ok(BuildResult::Success) => {
                    // Package builds successfully
                }
                Ok(BuildResult::Warning(warning)) => {
                    build_warnings.push(format!("{}: {}", package_name, warning));
                }
                Err(e) => {
                    build_failures.push(format!("{}: {}", package_name, e));
                }
            }
        }

        let duration = start_time.elapsed().as_millis() as u64;

        if build_failures.is_empty() {
            let message = if build_warnings.is_empty() {
                "All packages build successfully".to_string()
            } else {
                format!("All packages build successfully ({} warnings)", build_warnings.len())
            };

            checks.push(ValidationCheck {
                name: "Package Builds".to_string(),
                passed: true,
                message,
                critical: true,
                duration_ms: duration,
            });

            warnings.extend(build_warnings);
        } else {
            checks.push(ValidationCheck {
                name: "Package Builds".to_string(),
                passed: false,
                message: format!("{} packages failed to build", build_failures.len()),
                critical: true,
                duration_ms: duration,
            });

            critical_errors.extend(build_failures);
            warnings.extend(build_warnings);
        }

        Ok(())
    }

    /// Test building a single package
    async fn test_package_build(&self, package_info: &crate::workspace::PackageInfo) -> Result<BuildResult> {
        let mut cmd = AsyncCommand::new("cargo");
        cmd.arg("check")
            .arg("--manifest-path")
            .arg(&package_info.cargo_toml_path)
            .stdout(Stdio::piped())
            .stderr(Stdio::piped());

        let output = cmd.output().await
            .map_err(|e| PublishError::PublishFailed {
                package: package_info.name.clone(),
                reason: format!("Failed to execute cargo check: {}", e),
            })?;

        if output.status.success() {
            let stderr = String::from_utf8_lossy(&output.stderr);
            if stderr.contains("warning:") {
                Ok(BuildResult::Warning(stderr.to_string()))
            } else {
                Ok(BuildResult::Success)
            }
        } else {
            let stderr = String::from_utf8_lossy(&output.stderr);
            Err(PublishError::DryRunFailed {
                package: package_info.name.clone(),
                reason: stderr.to_string(),
            }.into())
        }
    }

    /// Validate crates.io credentials and authentication
    async fn validate_credentials(
        &self,
        checks: &mut Vec<ValidationCheck>,
        warnings: &mut Vec<String>,
    ) -> Result<()> {
        let start_time = std::time::Instant::now();

        match self.check_cargo_login().await {
            Ok(true) => {
                checks.push(ValidationCheck {
                    name: "Crates.io Authentication".to_string(),
                    passed: true,
                    message: "Successfully authenticated with crates.io".to_string(),
                    critical: false,
                    duration_ms: start_time.elapsed().as_millis() as u64,
                });
            }
            Ok(false) => {
                let warning_msg = "Not authenticated with crates.io - run 'cargo login' first";
                checks.push(ValidationCheck {
                    name: "Crates.io Authentication".to_string(),
                    passed: false,
                    message: warning_msg.to_string(),
                    critical: false,
                    duration_ms: start_time.elapsed().as_millis() as u64,
                });
                warnings.push(warning_msg.to_string());
            }
            Err(e) => {
                let warning_msg = format!("Could not verify crates.io authentication: {}", e);
                checks.push(ValidationCheck {
                    name: "Crates.io Authentication".to_string(),
                    passed: false,
                    message: warning_msg.clone(),
                    critical: false,
                    duration_ms: start_time.elapsed().as_millis() as u64,
                });
                warnings.push(warning_msg);
            }
        }

        Ok(())
    }

    /// Check if user is logged into cargo/crates.io
    async fn check_cargo_login(&self) -> Result<bool> {
        let mut cmd = AsyncCommand::new("cargo");
        cmd.arg("login")
            .arg("--help")
            .stdout(Stdio::null())
            .stderr(Stdio::null());

        // Try to get current login status by attempting a dry run operation
        let mut whoami_cmd = AsyncCommand::new("cargo");
        whoami_cmd.arg("owner")
            .arg("--list")
            .arg("nonexistent-crate-name-12345")
            .stdout(Stdio::piped())
            .stderr(Stdio::piped());

        let output = whoami_cmd.output().await
            .map_err(|_e| PublishError::AuthenticationError)?;

        // If we get an authentication error, we're not logged in
        let stderr = String::from_utf8_lossy(&output.stderr);
        Ok(!stderr.contains("authentication") && !stderr.contains("token"))
    }

    /// Validate workspace dependencies
    async fn validate_dependencies(
        &self,
        checks: &mut Vec<ValidationCheck>,
        critical_errors: &mut Vec<String>,
        warnings: &mut Vec<String>,
    ) -> Result<()> {
        let start_time = std::time::Instant::now();

        let mut missing_dependencies = Vec::new();
        let mut version_conflicts = Vec::new();

        // Check that all workspace dependencies exist and are properly versioned
        for (package_name, package_info) in &self.workspace.packages {
            for dep_name in &package_info.workspace_dependencies {
                if !self.workspace.packages.contains_key(dep_name) {
                    missing_dependencies.push(format!(
                        "Package '{}' depends on missing workspace package '{}'",
                        package_name, dep_name
                    ));
                }

                // Check for version specification in published dependencies
                if let Some(dep_spec) = package_info.all_dependencies.get(dep_name) {
                    if dep_spec.version.is_none() && dep_spec.path.is_some() {
                        version_conflicts.push(format!(
                            "Package '{}' dependency on '{}' lacks version (needed for crates.io)",
                            package_name, dep_name
                        ));
                    }
                }
            }
        }

        let duration = start_time.elapsed().as_millis() as u64;

        if missing_dependencies.is_empty() && version_conflicts.is_empty() {
            checks.push(ValidationCheck {
                name: "Workspace Dependencies".to_string(),
                passed: true,
                message: "All workspace dependencies are properly configured".to_string(),
                critical: true,
                duration_ms: duration,
            });
        } else {
            let mut all_issues = Vec::new();
            all_issues.extend(missing_dependencies.iter().cloned());
            all_issues.extend(version_conflicts.iter().cloned());

            checks.push(ValidationCheck {
                name: "Workspace Dependencies".to_string(),
                passed: false,
                message: format!("{} dependency issues found", all_issues.len()),
                critical: !missing_dependencies.is_empty(),
                duration_ms: duration,
            });

            if !missing_dependencies.is_empty() {
                critical_errors.extend(missing_dependencies);
            }
            if !version_conflicts.is_empty() {
                warnings.extend(version_conflicts);
            }
        }

        Ok(())
    }

    /// Validate crates.io readiness
    async fn validate_crates_io_readiness(
        &self,
        checks: &mut Vec<ValidationCheck>,
        warnings: &mut Vec<String>,
    ) -> Result<()> {
        let start_time = std::time::Instant::now();

        let mut readiness_issues = Vec::new();

        // Check that packages have required metadata for crates.io
        for (package_name, package_info) in &self.workspace.packages {
            if package_info.config.description.is_none() {
                readiness_issues.push(format!(
                    "Package '{}' missing description (recommended for crates.io)",
                    package_name
                ));
            }

            if package_info.config.license.is_none() {
                readiness_issues.push(format!(
                    "Package '{}' missing license (required for crates.io)",
                    package_name
                ));
            }

            if package_info.config.homepage.is_none() && package_info.config.repository.is_none() {
                readiness_issues.push(format!(
                    "Package '{}' missing homepage or repository (recommended for crates.io)",
                    package_name
                ));
            }
        }

        let duration = start_time.elapsed().as_millis() as u64;

        if readiness_issues.is_empty() {
            checks.push(ValidationCheck {
                name: "Crates.io Readiness".to_string(),
                passed: true,
                message: "All packages ready for crates.io publishing".to_string(),
                critical: false,
                duration_ms: duration,
            });
        } else {
            checks.push(ValidationCheck {
                name: "Crates.io Readiness".to_string(),
                passed: false,
                message: format!("{} metadata issues found", readiness_issues.len()),
                critical: false,
                duration_ms: duration,
            });

            warnings.extend(readiness_issues);
        }

        Ok(())
    }
}

/// Result of a package build test
#[derive(Debug)]
enum BuildResult {
    Success,
    Warning(String),
}

impl ValidationResult {
    /// Get all failed checks
    pub fn failed_checks(&self) -> Vec<&ValidationCheck> {
        self.checks.iter().filter(|check| !check.passed).collect()
    }

    /// Get all critical failed checks
    pub fn critical_failed_checks(&self) -> Vec<&ValidationCheck> {
        self.checks
            .iter()
            .filter(|check| !check.passed && check.critical)
            .collect()
    }

    /// Get total validation duration
    pub fn total_duration_ms(&self) -> u64 {
        self.checks.iter().map(|check| check.duration_ms).sum()
    }

    /// Check if validation passed with only warnings
    pub fn passed_with_warnings(&self) -> bool {
        self.success && !self.warnings.is_empty()
    }

    /// Get summary of validation results
    pub fn summary(&self) -> String {
        let total_checks = self.checks.len();
        let passed_checks = self.checks.iter().filter(|c| c.passed).count();
        let critical_failures = self.critical_failed_checks().len();

        if self.success {
            if self.warnings.is_empty() {
                format!("✅ All {} checks passed", total_checks)
            } else {
                format!(
                    "{}/{} checks passed ({} warnings)",
                    passed_checks, total_checks, self.warnings.len()
                )
            }
        } else {
            format!(
                "{}/{} checks passed ({} critical failures)",
                passed_checks, total_checks, critical_failures
            )
        }
    }
}

impl ValidationCheck {
    /// Check if this validation check is considered a failure
    pub fn is_failure(&self) -> bool {
        !self.passed
    }

    /// Check if this is a critical failure
    pub fn is_critical_failure(&self) -> bool {
        !self.passed && self.critical
    }

    /// Format the check result for display
    pub fn format_result(&self) -> String {
        let status = if self.passed { "" } else { "" };
        let criticality = if self.critical { " [CRITICAL]" } else { "" };
        
        format!(
            "{} {} ({}ms){}: {}",
            status, self.name, self.duration_ms, criticality, self.message
        )
    }
}