Skip to main content

verctl_core/versioning/
bump.rs

1use anyhow::{Context, Result, bail, ensure};
2use semver::Version;
3
4use crate::config::Prerelease;
5use crate::fragment::Bump;
6
7/// Whether `version` is a new package's placeholder: `0.0.0`, with or without
8/// a pre-release or build suffix. A new package releases `0.0.1` first, so a
9/// placeholder is never a release. A version that is not semver is not one.
10#[must_use]
11pub fn unreleased(version: &str) -> bool {
12    Version::parse(version)
13        .is_ok_and(|version| (version.major, version.minor, version.patch) == (0, 0, 0))
14}
15
16/// Whether a `0.0.0` package opens at `0.0.1` or `0.1.0`.
17#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
18pub enum FirstRelease {
19    /// A new package opens at `0.0.1` from a patch fragment (the default).
20    #[default]
21    Patch,
22    /// A new package opens at `0.1.0` (`first_minor: true`).
23    Minor,
24}
25
26/// The stable version `bump` moves `current` to: [`apply_with`] for a package
27/// that sets no `prerelease`.
28///
29/// A current prerelease keeps its base when the base already reaches the
30/// bump, so `1.2.3-rc.1` with a patch gives `1.2.3`.
31///
32/// # Errors
33///
34/// Returns an error as [`apply_with`] does without a `prerelease`.
35pub fn apply(current: &str, bump: Bump, first: FirstRelease) -> Result<String> {
36    apply_with(current, bump, first, None)
37}
38
39/// The version `bump` moves `current` to, as a stable release or, when the
40/// package sets `prerelease`, as a candidate. [`apply`] is this with no
41/// `prerelease`.
42///
43/// The base is `current` bumped by `bump`. A current prerelease keeps its
44/// base when the base already reaches the bump: a patch always, a minor when
45/// the patch is 0, a major when the minor and patch are 0. That is what
46/// node-semver's `inc` does, and Changesets versions through it.
47///
48/// With `prerelease`, the version is `<base>-<tag>.<count>`. The count is the
49/// current count plus 1 when the base and the tag are unchanged, and 1
50/// otherwise. Without it, the version is the base. A stable `current` that
51/// `bump` leaves alone stays as it is, and so does a candidate of the tag
52/// `prerelease` names.
53///
54/// Two bumps are refused:
55///
56/// - A `major` on any 0.x package, because 1.0 is a decision rather than a
57///   fragment.
58/// - A `minor` or `major` on a `0.0.0` package, including one with a
59///   pre-release or build suffix, because a new package releases `0.0.1` first.
60///
61/// The operator records `first_minor` on a package to open it at `0.1.0`.
62///
63/// # Errors
64///
65/// Returns an error in these cases:
66///
67/// - `current` is not a semver version;
68/// - the bump is one of the two refused above;
69/// - `prerelease` is set, and `current` has a prerelease that is not
70///   `<letters>.<number>`;
71/// - the candidate would sort below `current`, as `0.8.0-beta.1` does below
72///   `0.8.0-rc.2`.
73pub fn apply_with(
74    current: &str,
75    bump: Bump,
76    first: FirstRelease,
77    prerelease: Option<&Prerelease>,
78) -> Result<String> {
79    let version = Version::parse(current).with_context(|| format!("semver {current:?}"))?;
80    let counted = prerelease
81        .filter(|_| !version.pre.is_empty())
82        .map(|tag| Counted::read(&version, tag))
83        .transpose()?;
84    let settled = counted
85        .as_ref()
86        .map_or(version.pre.is_empty(), |counted| counted.same_tag);
87    if bump == Bump::None && settled {
88        return Ok(current.to_owned());
89    }
90    if unreleased(current) && bump > Bump::Patch && first == FirstRelease::Patch {
91        bail!(
92            "0.0.0 refuses a {} bump: a new package releases 0.0.1 first, from a patch \
93             fragment; set `first_minor: true` on the package to open at 0.1.0",
94            bump.as_str()
95        );
96    }
97    if bump == Bump::Major && version.major == 0 {
98        bail!("0.x refuses a major bump (current {current}); use minor or wait for 1.0");
99    }
100    let mut next = Version::new(version.major, version.minor, version.patch);
101    if version.pre.is_empty() || !reaches(&version, bump) {
102        match bump {
103            Bump::None => {}
104            Bump::Patch => next.patch += 1,
105            Bump::Minor => {
106                next.minor += 1;
107                next.patch = 0;
108            }
109            Bump::Major => {
110                next.major += 1;
111                next.minor = 0;
112                next.patch = 0;
113            }
114        }
115    }
116    let Some(tag) = prerelease else {
117        return Ok(next.to_string());
118    };
119    let same_base =
120        (next.major, next.minor, next.patch) == (version.major, version.minor, version.patch);
121    let count = match counted {
122        Some(counted) if counted.same_tag && same_base => counted.count + 1,
123        Some(_) | None => 1,
124    };
125    next.pre = semver::Prerelease::new(&format!("{}.{count}", tag.as_str()))
126        .with_context(|| format!("prerelease {:?}", tag.as_str()))?;
127    ensure!(
128        next > version,
129        "{next} sorts below the current {current}; set `prerelease` to a tag that sorts above \
130         the current one, or remove it to release the stable version"
131    );
132    Ok(next.to_string())
133}
134
135/// Whether a prerelease `version` already contains the base `bump` would reach.
136///
137/// A base of `0.0.0` contains no release bump, because `0.0.0` is the
138/// placeholder no release ever carries ([`unreleased`]): `0.0.0-alpha.1`
139/// with a patch reaches `0.0.1`.
140fn reaches(version: &Version, bump: Bump) -> bool {
141    let placeholder = (version.major, version.minor, version.patch) == (0, 0, 0);
142    match bump {
143        Bump::None => true,
144        Bump::Patch => !placeholder,
145        Bump::Minor => !placeholder && version.patch == 0,
146        Bump::Major => !placeholder && version.minor == 0 && version.patch == 0,
147    }
148}
149
150/// A current prerelease read in the shape verctl writes, `<tag>.<count>`.
151struct Counted {
152    /// Whether the tag is the one the package sets.
153    same_tag: bool,
154    /// The count after the tag.
155    count: u64,
156}
157
158impl Counted {
159    fn read(version: &Version, tag: &Prerelease) -> Result<Self> {
160        let pre = version.pre.as_str();
161        let shaped = pre
162            .split_once('.')
163            .filter(|(name, _)| {
164                !name.is_empty() && name.bytes().all(|byte| byte.is_ascii_lowercase())
165            })
166            .and_then(|(name, count)| Some((name, count.parse::<u64>().ok()?)));
167        let Some((name, count)) = shaped else {
168            let base = format!("{}.{}.{}", version.major, version.minor, version.patch);
169            bail!(
170                "{version} has a prerelease verctl cannot count from; verctl writes \
171                 `<tag>.<count>`, such as {base}-{}.2: change the version in the manifest to that \
172                 shape",
173                tag.as_str()
174            );
175        };
176        Ok(Self {
177            same_tag: name == tag.as_str(),
178            count,
179        })
180    }
181}