cargo-rail 0.13.0

Graph-aware testing, dependency unification, and crate extraction for Rust monorepos
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
//! Pre-release validation checks

use crate::config::{ChangelogRelativeTo, ReleaseConfig};
use crate::error::{RailError, RailResult};
use crate::release::changelog::ChangelogGenerator;
use crate::release::planner::ReleasePlan;
use crate::release::process;
use crate::utils;
use crate::workspace::WorkspaceContext;
use std::fs;
use std::path::PathBuf;

/// Result of a single validation check
#[derive(Debug, Clone)]
pub struct ValidationResult {
  /// Name of the check
  pub check_name: String,
  /// Whether the check passed
  pub passed: bool,
  /// Details about what was validated
  pub details: Option<String>,
  /// Error message if failed
  pub error: Option<String>,
}

impl ValidationResult {
  fn passed(name: impl Into<String>, details: impl Into<String>) -> Self {
    Self {
      check_name: name.into(),
      passed: true,
      details: Some(details.into()),
      error: None,
    }
  }

  fn failed(name: impl Into<String>, error: impl Into<String>) -> Self {
    Self {
      check_name: name.into(),
      passed: false,
      details: None,
      error: Some(error.into()),
    }
  }
}

/// Pre-release validator
pub struct ReleaseValidator<'a> {
  /// Workspace context
  ctx: &'a WorkspaceContext,
}

impl<'a> ReleaseValidator<'a> {
  /// Create a new release validator
  pub fn new(ctx: &'a WorkspaceContext) -> Self {
    Self { ctx }
  }

  /// Validate release readiness for crate(s)
  pub fn validate(&self, crate_names: &[String], require_clean: bool) -> RailResult<()> {
    // 1. Check working directory is clean
    if require_clean {
      self.check_clean_working_directory()?;
    }

    // 2. Validate crates exist in workspace
    let workspace_members = self.ctx.graph.workspace_members();
    for crate_name in crate_names {
      if !workspace_members.contains(crate_name) {
        return Err(RailError::with_help(
          format!("Crate '{}' not found in workspace", crate_name),
          format!("Available crates: {}", workspace_members.join(", ")),
        ));
      }
    }

    // 3. Check for uncommitted changes in crate directories
    if require_clean {
      for crate_name in crate_names {
        self.check_crate_uncommitted_changes(crate_name)?;
      }
    }

    // 4. Check for path dependencies
    for crate_name in crate_names {
      self.check_path_dependencies(crate_name)?;
    }

    Ok(())
  }

  /// Validate git branch state for release
  ///
  /// Checks:
  /// - Detached HEAD: hard error (cannot release without a branch)
  /// - Non-default branch: error unless `allow_non_default` is true, then returns warning
  ///
  /// Returns `Some(warning)` if releasing from non-default branch with `allow_non_default=true`.
  /// Returns `None` if on default branch or no default branch can be determined.
  pub fn validate_branch(&self, allow_non_default: bool) -> RailResult<Option<String>> {
    let git = &self.ctx.git;

    // Hard error: detached HEAD
    if git.is_detached_head()? {
      return Err(RailError::with_help(
        "Cannot release from detached HEAD",
        "Checkout a branch first: git checkout <branch-name>",
      ));
    }

    let current = git.current_branch()?;

    // Check if on default branch
    if let Some(default) = git.default_branch()? {
      if current != default && !allow_non_default {
        return Err(RailError::with_help(
          format!("Releasing from '{}', not default branch '{}'", current, default),
          format!("Pass --yes to confirm, or checkout {}", default),
        ));
      }
      if current != default {
        // Return warning for display
        return Ok(Some(format!(
          "warning: releasing from '{}', not default branch '{}'",
          current, default
        )));
      }
    }

    Ok(None) // No warnings
  }

  /// Check if working directory is clean (no uncommitted changes)
  fn check_clean_working_directory(&self) -> RailResult<()> {
    if self.ctx.git.git().is_dirty()? {
      return Err(RailError::with_help(
        "Working directory has uncommitted changes",
        "Commit or stash your changes before releasing, or set require_clean = false in [release] section of rail.toml",
      ));
    }

    Ok(())
  }

  /// Check for uncommitted changes in specific crate directory
  fn check_crate_uncommitted_changes(&self, crate_name: &str) -> RailResult<()> {
    let package = self
      .ctx
      .cargo
      .get_package(crate_name)
      .ok_or_else(|| RailError::message(format!("Crate '{}' not found", crate_name)))?;

    let crate_dir = package
      .manifest_path
      .parent()
      .ok_or_else(|| RailError::message("Invalid manifest path"))?;
    let relative_path = crate_dir
      .as_std_path()
      .strip_prefix(self.ctx.workspace_root())
      .unwrap_or_else(|_| crate_dir.as_std_path());
    let git_path = {
      let path = utils::path_to_git_format(relative_path);
      if path.is_empty() { ".".to_string() } else { path }
    };

    // Check for changes in this directory
    let output = self
      .ctx
      .git
      .git()
      .run_git(&["status", "--porcelain", "--", &git_path])?;

    let stdout = String::from_utf8_lossy(&output.stdout);
    if !stdout.trim().is_empty() {
      return Err(RailError::with_help(
        format!("Crate '{}' has uncommitted changes", crate_name),
        "Commit changes before releasing",
      ));
    }

    Ok(())
  }

  /// Validate that crate can be published to crates.io
  pub fn validate_publishable(&self, crate_name: &str) -> RailResult<()> {
    let package = self
      .ctx
      .cargo
      .get_package(crate_name)
      .ok_or_else(|| RailError::message(format!("Crate '{}' not found", crate_name)))?;

    // Check if publish = false in Cargo.toml
    if !crate::workspace::CargoState::is_package_publishable(package) {
      return Err(RailError::with_help(
        format!("Crate '{}' has publish = false in Cargo.toml", crate_name),
        "Remove 'publish = false' or exclude this crate from the release",
      ));
    }

    Ok(())
  }

  /// Validate preconditions for applying a release plan.
  pub fn validate_apply_preconditions(
    &self,
    plan: &ReleasePlan,
    skip_publish: bool,
    skip_tag: bool,
    require_clean: bool,
    require_release_notes: bool,
  ) -> RailResult<()> {
    if require_clean {
      self.check_clean_working_directory()?;
    }

    if !skip_tag {
      for crate_plan in &plan.crates {
        if self.ctx.git.git().tag_exists(&crate_plan.tag_name)? {
          return Err(RailError::with_help(
            format!("tag '{}' already exists", crate_plan.tag_name),
            "regenerate plan with a new version or delete the conflicting tag".to_string(),
          ));
        }
      }
    }

    if !skip_publish {
      let output = process::run(
        "cargo",
        &["search", "serde", "--limit", "1"],
        Some(self.ctx.workspace_root()),
      )?;
      if !output.status.success() {
        return Err(RailError::with_help(
          "crates.io precondition check failed",
          "verify network access and cargo credentials before publishing".to_string(),
        ));
      }
    }

    if require_release_notes {
      self.validate_release_notes(plan)?;
    }

    Ok(())
  }

  /// Ensure each crate being released has release notes for its target version.
  ///
  /// A crate passes if either:
  /// - changelog generation is disabled for that crate, or
  /// - changelog already contains `## [<version>]`, or
  /// - generated changelog entries for this release are non-empty.
  fn validate_release_notes(&self, plan: &ReleasePlan) -> RailResult<()> {
    let generator = ChangelogGenerator::new(self.ctx.workspace_root());

    for crate_plan in &plan.crates {
      if !crate_plan.generate_changelog {
        continue;
      }

      if changelog_contains_version_entry(&crate_plan.changelog_path, &crate_plan.new_version.to_string()) {
        continue;
      }

      let crate_dir = crate_plan
        .manifest_path
        .parent()
        .ok_or_else(|| RailError::message("Invalid manifest path"))?;
      let generated = generator.generate(
        crate_plan.changelog_range_start.as_deref(),
        &crate_plan.changelog_range_end,
        Some(&[crate_dir]),
      )?;

      if generated.trim().is_empty() {
        return Err(RailError::with_help(
          format!(
            "no release notes for {} v{} in {}",
            crate_plan.name,
            crate_plan.new_version,
            crate_plan.changelog_path.display()
          ),
          "add user-facing commits, pre-populate the version section, or set [release].require_release_notes = false",
        ));
      }
    }

    Ok(())
  }

  /// Check for path dependencies (which block publishing)
  ///
  /// This check is skipped for non-publishable crates since path-only
  /// dependencies only matter for crates going to crates.io.
  fn check_path_dependencies(&self, crate_name: &str) -> RailResult<()> {
    // Skip this check for non-publishable crates - path deps don't matter
    // if the crate will never be published to crates.io
    if !self.is_publishable(crate_name) {
      return Ok(());
    }

    let package = self
      .ctx
      .cargo
      .get_package(crate_name)
      .ok_or_else(|| RailError::message(format!("Crate '{}' not found", crate_name)))?;

    for dep in &package.dependencies {
      if dep.path.is_some() {
        // Allow dev-dependencies with paths (tests can use local crates)
        if dep.kind == cargo_metadata::DependencyKind::Development {
          continue;
        }

        // Allow path deps that also have a version requirement
        // These are workspace path deps: { version = "x.y", path = "../foo" }
        // Cargo will use the version when publishing, not the path
        let has_version = !dep.req.comparators.is_empty();
        if has_version {
          continue;
        }

        // Pure path-only dependencies cannot be published
        return Err(RailError::with_help(
          format!("Crate '{}' has path-only dependency '{}'", crate_name, dep.name),
          "Path-only dependencies cannot be published. Add a version: { version = \"x.y\", path = \"...\" }",
        ));
      }
    }

    Ok(())
  }

  /// Check if a crate is publishable (combined Cargo.toml + rail.toml check)
  ///
  /// A crate is considered publishable if:
  /// 1. Cargo.toml does not have `publish = false`, AND
  /// 2. rail.toml does not have `[crates.NAME.release] publish = false`
  ///
  /// rail.toml takes precedence: if it explicitly sets `publish = true`,
  /// that overrides Cargo.toml's `publish = false`.
  pub fn is_publishable(&self, crate_name: &str) -> bool {
    let package = match self.ctx.cargo.get_package(crate_name) {
      Some(pkg) => pkg,
      None => return false,
    };

    // Check Cargo.toml
    let publish_from_cargo = crate::workspace::CargoState::is_package_publishable(package);

    // Check rail.toml - takes precedence if set
    let publish_from_config = self
      .ctx
      .config
      .as_ref()
      .and_then(|c| c.crates.get(crate_name))
      .and_then(|c| c.release.as_ref())
      .map(|r| r.publish);

    // rail.toml takes precedence if explicitly set
    publish_from_config.unwrap_or(publish_from_cargo)
  }

  /// Get the reason why a crate is not publishable
  ///
  /// Returns `None` if the crate is publishable.
  pub fn unpublishable_reason(&self, crate_name: &str) -> Option<String> {
    let package = match self.ctx.cargo.get_package(crate_name) {
      Some(pkg) => pkg,
      None => return Some(format!("crate '{}' not found", crate_name)),
    };

    // Check rail.toml first (takes precedence)
    if let Some(config) = &self.ctx.config
      && let Some(crate_config) = config.crates.get(crate_name)
      && let Some(release_config) = &crate_config.release
    {
      // If rail.toml explicitly sets publish, use that
      if !release_config.publish {
        return Some("publish = false in rail.toml".to_string());
      }
      // If rail.toml explicitly sets publish = true, it's publishable
      // (overrides Cargo.toml)
      return None;
    }

    // Fall back to Cargo.toml check
    if !crate::workspace::CargoState::is_package_publishable(package) {
      return Some("publish = false in Cargo.toml".to_string());
    }

    None
  }

  /// Filter workspace members to only publishable crates
  ///
  /// Produces `(publishable_crates, skipped_with_reason)` for workspace members.
  pub fn publishable_members(&self) -> (Vec<String>, Vec<(String, String)>) {
    let all_members = self.ctx.graph.workspace_members();
    let member_count = all_members.len();
    let mut publishable = Vec::with_capacity(member_count);
    let mut skipped = Vec::with_capacity(member_count / 4); // Most crates are publishable

    for name in all_members {
      if let Some(reason) = self.unpublishable_reason(name) {
        skipped.push((name.clone(), reason));
      } else {
        publishable.push(name.clone());
      }
    }

    (publishable, skipped)
  }

  /// Run `cargo publish --dry-run` to validate package can be published
  ///
  /// This catches issues like:
  /// - Missing required Cargo.toml fields
  /// - Invalid README paths
  /// - Package size limits
  /// - Files that would be excluded
  pub fn validate_publish_dry_run(&self, crate_name: &str) -> ValidationResult {
    let package = match self.ctx.cargo.get_package(crate_name) {
      Some(pkg) => pkg,
      None => return ValidationResult::failed("publish-dry-run", format!("crate '{}' not found", crate_name)),
    };

    let crate_dir = match package.manifest_path.parent() {
      Some(dir) => dir,
      None => return ValidationResult::failed("publish-dry-run", "invalid manifest path"),
    };

    // Run cargo publish --dry-run
    let output = process::run(
      "cargo",
      &["publish", "--dry-run", "--allow-dirty"],
      Some(crate_dir.as_std_path()),
    );

    match output {
      Ok(result) => {
        if result.status.success() {
          ValidationResult::passed("publish-dry-run", "package is valid for publishing")
        } else {
          let stderr = String::from_utf8_lossy(&result.stderr);
          // Extract the meaningful error message (skip the "error:" prefix noise)
          let error_msg = stderr
            .lines()
            .find(|line| line.contains("error") || line.contains("Error"))
            .unwrap_or(&stderr)
            .trim();
          ValidationResult::failed("publish-dry-run", error_msg.to_string())
        }
      }
      Err(e) => ValidationResult::failed("publish-dry-run", format!("failed to run cargo: {}", e)),
    }
  }

  /// Verify the crate can be built with the declared MSRV
  ///
  /// If the workspace manifest has `rust-version`, this runs `cargo check`
  /// with that toolchain to ensure compatibility.
  pub fn validate_msrv(&self, crate_name: &str) -> ValidationResult {
    let package = match self.ctx.cargo.get_package(crate_name) {
      Some(pkg) => pkg,
      None => return ValidationResult::failed("msrv", format!("crate '{}' not found", crate_name)),
    };

    // Get MSRV from package or workspace
    let msrv = package.rust_version.as_ref();

    let msrv_str = match msrv {
      Some(v) => v.to_string(),
      None => {
        // No MSRV declared - check passes (nothing to verify)
        return ValidationResult::passed("msrv", "no rust-version declared (skipped)");
      }
    };

    let crate_dir = match package.manifest_path.parent() {
      Some(dir) => dir,
      None => return ValidationResult::failed("msrv", "invalid manifest path"),
    };

    // Check if the MSRV toolchain is available
    let toolchain = format!("+{}", msrv_str);
    let check_toolchain = process::run("rustup", &["run", &msrv_str, "rustc", "--version"], None);

    match check_toolchain {
      Ok(result) if !result.status.success() => {
        // Toolchain not installed - skip with warning
        return ValidationResult::passed(
          "msrv",
          format!(
            "rust {} not installed (skipped, install with: rustup install {})",
            msrv_str, msrv_str
          ),
        );
      }
      Err(_) => {
        return ValidationResult::passed("msrv", "rustup not available (skipped)");
      }
      _ => {}
    }

    // Run cargo check with the MSRV toolchain
    let output = process::run(
      "cargo",
      &[&toolchain, "check", "--lib", "--quiet"],
      Some(crate_dir.as_std_path()),
    );

    match output {
      Ok(result) => {
        if result.status.success() {
          ValidationResult::passed("msrv", format!("builds successfully with rust {}", msrv_str))
        } else {
          let stderr = String::from_utf8_lossy(&result.stderr);
          // Get first error line
          let error_msg = stderr
            .lines()
            .find(|line| line.contains("error"))
            .unwrap_or("compilation failed")
            .trim();
          ValidationResult::failed("msrv", format!("fails with rust {}: {}", msrv_str, error_msg))
        }
      }
      Err(e) => ValidationResult::failed("msrv", format!("failed to run cargo: {}", e)),
    }
  }

  /// Run extended validation checks (dry-run publish, MSRV)
  ///
  /// Runs all checks without fail-fast and returns grouped validation results.
  pub fn validate_extended(&self, crate_names: &[String]) -> Vec<(String, Vec<ValidationResult>)> {
    crate_names
      .iter()
      .map(|crate_name| {
        let results = vec![
          self.validate_publish_dry_run(crate_name),
          self.validate_msrv(crate_name),
        ];
        (crate_name.clone(), results)
      })
      .collect()
  }

  /// Validate changelog paths for all crates being released
  ///
  /// Checks that:
  /// - Changelog paths don't escape the workspace (no ".." traversal above root)
  /// - Resolved paths are within workspace bounds
  pub fn validate_changelog_paths(&self, crate_names: &[String], release_config: &ReleaseConfig) -> RailResult<()> {
    for crate_name in crate_names {
      // Skip if changelog is disabled for this crate
      if release_config.skip_changelog_for.iter().any(|c| c == crate_name) {
        continue;
      }

      // Check per-crate skip setting
      if let Some(config) = &self.ctx.config
        && let Some(crate_config) = config.crates.get(crate_name)
        && let Some(changelog_cfg) = &crate_config.changelog
        && changelog_cfg.skip
      {
        continue;
      }

      let changelog_path = self.resolve_changelog_path(crate_name, release_config)?;

      // Check for path traversal outside workspace
      self.validate_path_within_workspace(&changelog_path, crate_name)?;
    }

    Ok(())
  }

  /// Resolve changelog path for a crate (mirrors planner logic)
  fn resolve_changelog_path(&self, crate_name: &str, release_config: &ReleaseConfig) -> RailResult<PathBuf> {
    let package = self
      .ctx
      .cargo
      .get_package(crate_name)
      .ok_or_else(|| RailError::message(format!("Crate '{}' not found", crate_name)))?;

    let manifest_path = package.manifest_path.as_std_path();

    // Get changelog path from per-crate config or global config
    let changelog_relative_path = self
      .ctx
      .config
      .as_ref()
      .and_then(|c| c.crates.get(crate_name))
      .and_then(|c| c.changelog.as_ref())
      .and_then(|ch| ch.path.as_ref())
      .map(|p| p.to_string_lossy().to_string())
      .unwrap_or_else(|| release_config.changelog_path.clone());

    // Resolve based on changelog_relative_to setting
    let changelog_path = match release_config.changelog_relative_to {
      ChangelogRelativeTo::Crate => manifest_path
        .parent()
        .ok_or_else(|| RailError::message("Invalid manifest path"))?
        .join(&changelog_relative_path),
      ChangelogRelativeTo::Workspace => self.ctx.workspace_root().join(&changelog_relative_path),
    };

    Ok(changelog_path)
  }

  /// Validate that a path is within the workspace bounds
  fn validate_path_within_workspace(&self, path: &std::path::Path, crate_name: &str) -> RailResult<()> {
    let workspace_root = self.ctx.workspace_root();

    // Check for ".." in the path string (simple check)
    let path_str = path.to_string_lossy();
    if path_str.contains("..") {
      // More thorough check: canonicalize if possible to see if it escapes
      // If the path doesn't exist yet, we check by normalizing components
      let normalized = normalize_path(path);
      let workspace_canonical = workspace_root
        .canonicalize()
        .unwrap_or_else(|_| workspace_root.to_path_buf());

      // Check if normalized path starts with workspace root
      if !normalized.starts_with(&workspace_canonical) && !normalized.starts_with(workspace_root) {
        return Err(RailError::with_help(
          format!(
            "Changelog path for '{}' escapes workspace: {}",
            crate_name,
            path.display()
          ),
          "Ensure changelog paths stay within the workspace directory",
        ));
      }
    }

    Ok(())
  }
}

/// Normalize a path by resolving `.` and `..` components without requiring the path to exist
fn normalize_path(path: &std::path::Path) -> PathBuf {
  use std::path::Component;

  let mut components = Vec::new();

  for component in path.components() {
    match component {
      Component::Prefix(p) => components.push(Component::Prefix(p)),
      Component::RootDir => {
        components.clear();
        components.push(Component::RootDir);
      }
      Component::CurDir => {}
      Component::ParentDir => {
        if let Some(Component::Normal(_)) = components.last() {
          components.pop();
        } else if components.is_empty() || matches!(components.last(), Some(Component::ParentDir)) {
          components.push(Component::ParentDir);
        }
      }
      Component::Normal(c) => components.push(Component::Normal(c)),
    }
  }

  components.iter().collect()
}

fn changelog_contains_version_entry(path: &std::path::Path, version: &str) -> bool {
  let Ok(contents) = fs::read_to_string(path) else {
    return false;
  };
  let needle = format!("## [{}]", version);
  contents.lines().any(|line| line.trim_start().starts_with(&needle))
}