Semver Requirement Matching

Parse semantic versions and requirement ranges, test whether a release satisfies a range, and pick the highest matching version.

RustData Integrity

Code

rustsnippet
32 lines
use semver::{Version, VersionReq};

fn matches(version: &str, requirement: &str) -> Result<bool, semver::Error> {
    let parsed = Version::parse(version)?;
    let requirement = VersionReq::parse(requirement)?;
    Ok(requirement.matches(&parsed))
}

fn best_match(versions: &[&str], requirement: &str) -> Result<Option<Version>, semver::Error> {
    let requirement = VersionReq::parse(requirement)?;
    let mut best: Option<Version> = None;
    for raw in versions {
        let version = Version::parse(raw)?;
        if !requirement.matches(&version) {
            continue;
        }
        if best.as_ref().map_or(true, |current| version > *current) {
            best = Some(version);
        }
    }
    Ok(best)
}

fn main() {
    let versions = ["1.2.0", "1.4.3", "2.0.0", "2.1.0-rc.1"];

    println!("1.9.0 in ^1.2: {:?}", matches("1.9.0", "^1.2"));
    println!("2.0.0 in ^1.2: {:?}", matches("2.0.0", "^1.2"));
    println!("rc.1 in ^2.1: {:?}", matches("2.1.0-rc.1", "^2.1"));
    println!("best in ~1.2: {:?}", best_match(&versions, "~1.2"));
    println!("invalid range: {}", matches("1.0.0", "not-a-version").is_err());
}

How the snippet works

Semver Requirement Matching reduces to the functions matches, best_match and main.

The file repeats itself only inside for raw in versions. Fallible operations return Result, and the ? operator short-circuits errors up to the caller.

Watch out for

  • Requires semver:: as a package; the snippet will not run without it.
  • Errors travel through Result; if you drop the ? operators while adapting, each call site needs its own match.

Applying it

Entry signature: fn matches(version: &str, requirement: &str) -> Result<bool, semver::Error>

Running the file prints labeled results such as 1.9.0 in ^1.2:, 2.0.0 in ^1.2:, rc.1 in ^2.1: — each operation’s effect is visible in the output.

Running the file executes main, which drives matches and best_match in order.

Statements that matter

fn matches(version: &str, requirement: &str) -> Result<bool, semver::Error> {
let parsed = Version::parse(version)?;
let requirement = VersionReq::parse(requirement)?;
Ok(requirement.matches(&parsed))
}
let mut best: Option<Version> = None;
let version = Version::parse(raw)?;

Interactive Tools for This Topic

FAQ

How should callers handle failures?
As data, not exceptions: `Result` makes the caller handle both arms.
Are there third-party dependencies?
`semver::` — install it with the package manager before running.