cargo-rail 0.27.0

Cargo-native Rust workspace engine for affected CI, Rust source-surface analysis, compiler reuse, dependency coherence, exact-SHA releases, and split/sync
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
//! Version bumping and Cargo.toml manipulation

use crate::config::Pre1BreakingBump;
use crate::error::{RailError, RailResult};
use semver::Version;
use serde::{Deserialize, Serialize};
use std::fs;
use std::path::Path;
use std::str::FromStr;
use toml_edit::DocumentMut;

/// Version bump strategy
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum BumpType {
    /// Increment patch version (0.0.Z or X.Y.z)
    Patch,
    /// Increment minor version (0.Y.0 or X.y.0)
    Minor,
    /// Increment major version (X.0.0 or 0.Y.0 for 0.x)
    Major,
    /// Increment prerelease version (1.0.0-rc.1 -> 1.0.0-rc.2)
    /// If no prerelease exists, adds -rc.1
    Prerelease,
    /// Strip prerelease suffix (1.0.0-rc.2 -> 1.0.0)
    /// If no prerelease exists, this is a no-op
    Release,
    /// Set exact version
    Exact(Version),
}

impl FromStr for BumpType {
    type Err = RailError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s.to_lowercase().as_str() {
            "major" => Ok(Self::Major),
            "minor" => Ok(Self::Minor),
            "patch" => Ok(Self::Patch),
            "prerelease" | "pre" | "rc" => Ok(Self::Prerelease),
            "release" => Ok(Self::Release),
            _ => {
                // Try parsing as explicit version
                let version = Version::parse(s).map_err(|e| {
          RailError::with_help(
            format!("Invalid version bump: {}", s),
            format!(
              "Use 'major', 'minor', 'patch', 'prerelease', 'release', or a valid semver version (e.g., '1.2.3'). Parse error: {}",
              e
            ),
          )
        })?;
                Ok(Self::Exact(version))
            }
        }
    }
}

impl BumpType {
    /// Apply bump to a version
    pub fn apply(&self, current: &Version) -> Version {
        match self {
            Self::Patch => {
                let mut next = current.clone();
                next.patch += 1;
                next.pre = semver::Prerelease::EMPTY;
                next.build = semver::BuildMetadata::EMPTY;
                next
            }
            Self::Minor => {
                let mut next = current.clone();
                next.minor += 1;
                next.patch = 0;
                next.pre = semver::Prerelease::EMPTY;
                next.build = semver::BuildMetadata::EMPTY;
                next
            }
            Self::Major => {
                let mut next = current.clone();
                // Always bump major version - including 0.x -> 1.0.0
                // Users who want semver-compatible "breaking change" on 0.x can use --bump minor
                next.major += 1;
                next.minor = 0;
                next.patch = 0;
                next.pre = semver::Prerelease::EMPTY;
                next.build = semver::BuildMetadata::EMPTY;
                next
            }
            Self::Prerelease => {
                let mut next = current.clone();
                next.build = semver::BuildMetadata::EMPTY;

                if current.pre.is_empty() {
                    // No prerelease - add rc.1 ("rc.1" is always valid per semver spec)
                    next.pre = semver::Prerelease::new("rc.1").unwrap_or(semver::Prerelease::EMPTY);
                } else {
                    // Increment the numeric part of the prerelease
                    // Supports: rc.1 -> rc.2, alpha.3 -> alpha.4, beta.0 -> beta.1
                    let pre_str = current.pre.as_str();
                    if let Some((prefix, num_str)) = pre_str.rsplit_once('.') {
                        if let Ok(num) = num_str.parse::<u64>() {
                            let new_pre = format!("{}.{}", prefix, num + 1);
                            next.pre = semver::Prerelease::new(&new_pre).unwrap_or_else(|_| current.pre.clone());
                        } else {
                            // Not a number suffix, append .1
                            let new_pre = format!("{}.1", pre_str);
                            next.pre = semver::Prerelease::new(&new_pre).unwrap_or_else(|_| current.pre.clone());
                        }
                    } else {
                        // No dot in prerelease (e.g., "alpha"), append .1
                        let new_pre = format!("{}.1", pre_str);
                        next.pre = semver::Prerelease::new(&new_pre).unwrap_or_else(|_| current.pre.clone());
                    }
                }
                next
            }
            Self::Release => {
                // Strip prerelease and build metadata
                let mut next = current.clone();
                next.pre = semver::Prerelease::EMPTY;
                next.build = semver::BuildMetadata::EMPTY;
                next
            }
            Self::Exact(version) => version.clone(),
        }
    }
}

/// How the user asked versions to be computed
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum BumpRequest {
    /// One bump applied to every target crate
    Explicit(BumpType),
    /// Per-crate inference from the configured release source and dependency cascades
    Auto,
}

impl FromStr for BumpRequest {
    type Err = RailError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        if s.eq_ignore_ascii_case("auto") {
            Ok(Self::Auto)
        } else {
            s.parse::<BumpType>().map(Self::Explicit)
        }
    }
}

/// Semver impact level, ordered so `max()` folds commit history
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum BumpLevel {
    /// Bug fixes and performance improvements
    Patch,
    /// New features
    Minor,
    /// Breaking changes
    Major,
}

impl BumpLevel {
    /// Map a level to a concrete bump, honoring the pre-1.0 breaking policy
    pub fn to_bump_type(self, current: &Version, pre_1_breaking: Pre1BreakingBump) -> BumpType {
        match self {
            Self::Major if current.major == 0 && pre_1_breaking == Pre1BreakingBump::Minor => BumpType::Minor,
            Self::Major => BumpType::Major,
            Self::Minor => BumpType::Minor,
            Self::Patch => BumpType::Patch,
        }
    }

    /// String form used in plan output and change files
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::Patch => "patch",
            Self::Minor => "minor",
            Self::Major => "major",
        }
    }
}

impl FromStr for BumpLevel {
    type Err = RailError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s.to_lowercase().as_str() {
            "patch" => Ok(Self::Patch),
            "minor" => Ok(Self::Minor),
            "major" => Ok(Self::Major),
            _ => Err(RailError::with_help(
                format!("invalid bump level: {}", s),
                "use 'patch', 'minor', or 'major'",
            )),
        }
    }
}

impl std::fmt::Display for BumpLevel {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.as_str())
    }
}

/// Semver impact of one conventional commit
///
/// Fixed semantics regardless of custom changelog groups: breaking → major,
/// feat → minor, fix/perf → patch, everything else (including custom types
/// and unconventional commits) → no bump.
pub(crate) fn commit_bump_level(parsed: &crate::release::changelog::ParsedSubject<'_>) -> Option<BumpLevel> {
    if parsed.breaking {
        return Some(BumpLevel::Major);
    }
    match parsed.commit_type? {
        "feat" => Some(BumpLevel::Minor),
        "fix" | "perf" => Some(BumpLevel::Patch),
        _ => None,
    }
}

/// Version bumper for Cargo.toml files
#[derive(Debug)]
pub struct VersionBumper;

impl VersionBumper {
    /// Get current version from Cargo.toml
    pub fn get_version(manifest_path: &Path) -> RailResult<Version> {
        let content = fs::read_to_string(manifest_path)
            .map_err(|e| RailError::message(format!("Failed to read {}: {}", manifest_path.display(), e)))?;

        let doc: DocumentMut = content
            .parse()
            .map_err(|e| RailError::message(format!("Failed to parse {} as TOML: {}", manifest_path.display(), e)))?;

        let version_str = doc
            .get("package")
            .and_then(|p| p.get("version"))
            .and_then(|v| v.as_str())
            .ok_or_else(|| {
                RailError::with_help(
                    format!("No version field in {}", manifest_path.display()),
                    "Ensure [package.version] is set or use workspace inheritance",
                )
            })?;

        Version::parse(version_str).map_err(|e| {
            RailError::message(format!(
                "Invalid version '{}' in {}: {}",
                version_str,
                manifest_path.display(),
                e
            ))
        })
    }

    /// Bump version in Cargo.toml
    ///
    /// Uses lossless TOML editing to preserve comments and formatting.
    ///
    /// # Errors
    /// Fails when the crate uses workspace version inheritance.
    pub fn bump_version(manifest_path: &Path, bump_type: BumpType) -> RailResult<Version> {
        use crate::toml::editor::TomlEditor;

        let mut editor = TomlEditor::open(manifest_path)?;
        let doc = editor.doc();

        // Get current version - check for workspace inheritance
        let version_item = doc.get("package").and_then(|p| p.get("version"));

        // Check if using workspace inheritance
        if let Some(item) = version_item
            && (item.is_inline_table() || item.is_table())
        {
            // Check for { workspace = true }
            if let Some(tbl) = item.as_inline_table() {
                if tbl.get("workspace").and_then(|v| v.as_bool()) == Some(true) {
                    return Err(RailError::with_help(
                        format!(
                            "cannot bump version in {}: uses workspace inheritance",
                            manifest_path.display()
                        ),
                        "Set a specific version in this crate's Cargo.toml, or update [workspace.package.version] in the root Cargo.toml",
                    ));
                }
            } else if let Some(tbl) = item.as_table()
                && tbl.get("workspace").and_then(|v| v.as_bool()) == Some(true)
            {
                return Err(RailError::with_help(
                    format!(
                        "cannot bump version in {}: uses workspace inheritance",
                        manifest_path.display()
                    ),
                    "Set a specific version in this crate's Cargo.toml, or update [workspace.package.version] in the root Cargo.toml",
                ));
            }
        }

        let current_str = version_item.and_then(|v| v.as_str()).ok_or_else(|| {
            RailError::with_help(
                format!("No version field in {}", manifest_path.display()),
                "Ensure [package.version] is set",
            )
        })?;

        let current = Version::parse(current_str).map_err(|e| {
            RailError::message(format!(
                "Invalid version '{}' in {}: {}",
                current_str,
                manifest_path.display(),
                e
            ))
        })?;

        // Calculate new version
        let new_version = bump_type.apply(&current);

        // Update in document
        editor.set("package.version", new_version.to_string())?;

        // Write back (atomic write handled by editor)
        editor.write()?;

        Ok(new_version)
    }

    /// Update dependency version in a Cargo.toml
    ///
    /// Updates dependencies that reference a specific crate to use a new version.
    /// This is needed when bumping versions in a workspace - dependent crates
    /// need to update their dependency declarations.
    pub fn update_dependency_version(manifest_path: &Path, dep_name: &str, new_version: &Version) -> RailResult<bool> {
        use crate::toml::editor::TomlEditor;

        let mut editor = TomlEditor::open(manifest_path)?;
        let doc = editor.doc_mut();
        let mut updated = false;

        // Check all dependency sections
        for section in &["dependencies", "dev-dependencies", "build-dependencies"] {
            if let Some(deps) = doc.get_mut(section).and_then(|d| d.as_table_like_mut())
                && let Some(dep) = deps.get_mut(dep_name)
            {
                // Update version field
                if let Some(dep_table) = dep.as_inline_table_mut()
                    && dep_table.contains_key("version")
                {
                    dep_table.insert("version", format!("^{}", new_version).into());
                    updated = true;
                } else if let Some(dep_table) = dep.as_table_mut()
                    && dep_table.contains_key("version")
                {
                    dep_table["version"] = toml_edit::value(format!("^{}", new_version));
                    updated = true;
                }
            }
        }

        if updated {
            // Write back
            editor.write()?;
        }

        Ok(updated)
    }

    /// Update [workspace.dependencies] entry for a crate
    ///
    /// When a workspace member is bumped, the workspace.dependencies entry
    /// needs to be updated too if it has a version field.
    pub fn update_workspace_dependency(
        manifest_path: &Path,
        dep_name: &str,
        new_version: &Version,
    ) -> RailResult<bool> {
        use crate::toml::editor::TomlEditor;

        let mut editor = TomlEditor::open(manifest_path)?;
        let doc = editor.doc_mut();
        let mut updated = false;

        // Check [workspace.dependencies]
        if let Some(workspace) = doc.get_mut("workspace")
            && let Some(deps) = workspace.get_mut("dependencies").and_then(|d| d.as_table_like_mut())
            && let Some(dep) = deps.get_mut(dep_name)
        {
            // Update version field if present
            if let Some(dep_table) = dep.as_inline_table_mut()
                && dep_table.contains_key("version")
            {
                dep_table.insert("version", new_version.to_string().into());
                updated = true;
            } else if let Some(dep_table) = dep.as_table_mut()
                && dep_table.contains_key("version")
            {
                dep_table["version"] = toml_edit::value(new_version.to_string());
                updated = true;
            }
        }

        if updated {
            editor.write()?;
        }

        Ok(updated)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_bump_patch() {
        let v = Version::parse("1.2.3").unwrap();
        let next = BumpType::Patch.apply(&v);
        assert_eq!(next, Version::parse("1.2.4").unwrap());
    }

    #[test]
    fn test_bump_minor() {
        let v = Version::parse("1.2.3").unwrap();
        let next = BumpType::Minor.apply(&v);
        assert_eq!(next, Version::parse("1.3.0").unwrap());
    }

    #[test]
    fn test_bump_major() {
        let v = Version::parse("1.2.3").unwrap();
        let next = BumpType::Major.apply(&v);
        assert_eq!(next, Version::parse("2.0.0").unwrap());
    }

    #[test]
    fn test_bump_major_pre_1() {
        // For 0.x versions, major bump goes to 1.0.0
        let v = Version::parse("0.2.3").unwrap();
        let next = BumpType::Major.apply(&v);
        assert_eq!(next, Version::parse("1.0.0").unwrap());
    }

    #[test]
    fn test_bump_strips_prerelease() {
        let v = Version::parse("1.2.3-beta.1").unwrap();
        let next = BumpType::Patch.apply(&v);
        assert_eq!(next, Version::parse("1.2.4").unwrap());
    }

    #[test]
    fn test_bump_prerelease_from_stable() {
        // Stable version gets rc.1 added
        let v = Version::parse("1.0.0").unwrap();
        let next = BumpType::Prerelease.apply(&v);
        assert_eq!(next, Version::parse("1.0.0-rc.1").unwrap());
    }

    #[test]
    fn test_bump_prerelease_increment_rc() {
        // rc.1 -> rc.2
        let v = Version::parse("1.0.0-rc.1").unwrap();
        let next = BumpType::Prerelease.apply(&v);
        assert_eq!(next, Version::parse("1.0.0-rc.2").unwrap());
    }

    #[test]
    fn test_bump_prerelease_increment_alpha() {
        // alpha.3 -> alpha.4
        let v = Version::parse("2.0.0-alpha.3").unwrap();
        let next = BumpType::Prerelease.apply(&v);
        assert_eq!(next, Version::parse("2.0.0-alpha.4").unwrap());
    }

    #[test]
    fn test_bump_prerelease_increment_beta() {
        // beta.0 -> beta.1
        let v = Version::parse("1.5.0-beta.0").unwrap();
        let next = BumpType::Prerelease.apply(&v);
        assert_eq!(next, Version::parse("1.5.0-beta.1").unwrap());
    }

    #[test]
    fn test_bump_release_strips_prerelease() {
        // rc.2 -> stable
        let v = Version::parse("1.0.0-rc.2").unwrap();
        let next = BumpType::Release.apply(&v);
        assert_eq!(next, Version::parse("1.0.0").unwrap());
    }

    #[test]
    fn test_bump_release_noop_on_stable() {
        // Stable version stays stable
        let v = Version::parse("1.0.0").unwrap();
        let next = BumpType::Release.apply(&v);
        assert_eq!(next, Version::parse("1.0.0").unwrap());
    }

    #[test]
    fn test_parse_bump_prerelease() {
        assert_eq!(BumpType::from_str("prerelease").unwrap(), BumpType::Prerelease);
        assert_eq!(BumpType::from_str("pre").unwrap(), BumpType::Prerelease);
        assert_eq!(BumpType::from_str("rc").unwrap(), BumpType::Prerelease);
        assert_eq!(BumpType::from_str("PRERELEASE").unwrap(), BumpType::Prerelease);
    }

    #[test]
    fn test_parse_bump_release() {
        assert_eq!(BumpType::from_str("release").unwrap(), BumpType::Release);
        assert_eq!(BumpType::from_str("RELEASE").unwrap(), BumpType::Release);
    }
}