masterminds/semver

repository·master·Indexed 23 days ago

https://github.com/masterminds/semver

A Go package for parsing, sorting, and comparing Semantic Versions (SemVer) and validating them against complex version constraints. Version v3 focuses on constraint compatibility for range handling similar to npm/js and Rust/Cargo, supporting operators such as tilde (~), caret (^), wildcards, and hyphen ranges.

Tokens
2.9K
Snippets
4
Records
24
Agent score
81%

What's inside masterminds/semver

  1. Install and import semver v3

    master
    To use the latest stable version of the semver package, import github.com/Masterminds/semver/v3. The v3 release is the active version focused on constraint compatibility for range handling (similar to npm/js and Rust/Cargo).
  2. Configure prerelease inclusion in constraints

    master

    By default, constraints typically exclude prerelease versions unless the constraint string itself explicitly includes a prerelease. You can override this behavior using the IncludePrerelease field on the Constraints struct.

    Behavioral Note: If a specific constraint group within the Constraints object contains a prerelease requirement, that group will always include prereleases for its check, even if IncludePrerelease is set to false.

  3. Sort a collection of semantic versions

    master

    You can sort a slice of *semver.Version pointers using the standard library sort package and the semver.Collection type.

    raw := []string{"1.2.3", "1.0", "1.3", "2", "0.4.2",}
    vs := make([]*semver.Version, len(raw))
    for i, r := range raw {
        v, err := semver.NewVersion(r)
        if err != nil {
            t.Errorf("Error parsing version: %s", err)
        }
    
        vs[i] = v
    }
    
    sort.Sort(semver.Collection(vs))
  4. Parse semantic versions with NewVersion and StrictNewVersion

    master

    Use semver.NewVersion to parse a version string. This function attempts to coerce the input into a valid semantic version (e.g., converting v1.2 to 1.2.0). Use semver.StrictNewVersion if you only want to parse valid version 2 semantic versions without coercion.

    Global Configuration

    • semver.CoerceNewVersion (bool, default true): When true, non-compliant versions (like those with leading zeros in major/minor/patch parts) are coerced into valid SemVer. This allows for CalVer support.
    • semver.DetailedNewVersionErrors (bool): When false, parsing is faster but error messages are less descriptive. This only affects behavior when CoerceNewVersion is false.
    v, err := semver.NewVersion("1.2.3-beta.1+build345")
  5. Validate a version against a constraint

    master

    If you need to know why a version failed to meet a constraint, use the .Validate(v) method. It returns a boolean indicating if the version is valid and a slice of strings containing descriptive error messages.

    c, err := semver.NewConstraint("<= 1.2.3, >= 1.4")
    if err != nil {
        // Handle constraint not being parseable.
    }
    
    v, err := semver.NewVersion("1.3")
    if err != nil {
        // Handle version not being parsable.
    }
    
    // Validate a version against a constraint.
    a, msgs := c.Validate(v)
    // a is false
    for _, m := range msgs {
        fmt.Println(m)
        // Loops over the errors which would read
        // "1.3 is greater than 1.2.3"
        // "1.3 is less than 1.4"
    }
  6. Check if a version meets a constraint

    master

    To check if a version satisfies a specific range, use semver.NewConstraint to create a constraint object and then call its .Check(v) method.

    Note on Pre-releases: By default, constraint checking follows npm/js and Cargo/Rust patterns, meaning pre-releases are considered invalid if the range does not explicitly include a pre-release. To include pre-releases in a range, you can append -0 to the version (e.g., >=1.2.3-0). Alternatively, you can set the IncludePrerelease property on the Constraints instance to true.

    c, err := semver.NewConstraint(">= 1.2.3")
    if err != nil {
        // Handle constraint not being parsable.
    }
    
    v, err := semver.NewVersion("1.3")
    if err != nil {
        // Handle version not being parsable.
    }
    // Check if the version meets the constraints. The variable a will be true.
    a := c.Check(v)
  7. Configure NewVersion parsing behavior

    master

    The NewVersion function's behavior can be modified via package-level variables:

    • CoerceNewVersion (bool): If true (default), NewVersion will attempt to convert non-standard versions like 1.2 into 1.2.0. If false, it will return an error for such strings.
    • DetailedNewVersionErrors (bool): If true (default), NewVersion returns specific error types (like ErrSegmentStartsZero) when parsing fails. If false, it returns ErrInvalidSemVer more quickly to save processing time.
  8. Reference: Tilde (~) range comparisons

    master

    The tilde operator is used for patch-level ranges. If a minor version is specified, it restricts changes to the patch level. If the minor version is missing, it restricts changes to the minor level.

    • ~1.2.3 is equivalent to >= 1.2.3, < 1.3.0
    • ~1 is equivalent to >= 1, < 2
    • ~2.3 is equivalent to >= 2.3, < 2.4
    • ~1.2.x is equivalent to >= 1.2.0, < 1.3.0
    • ~1.x is equivalent to >= 1, < 2
  9. Reference: Basic comparison operators

    master

    Constraint strings can be composed of space or comma-separated AND comparisons, or separated by || for OR comparisons. The following operators are supported:

    • =: equal (aliased to no operator)
    • !=: not equal
    • >: greater than
    • <: less than
    • >=: greater than or equal to
    • <=: less than or equal to
  10. Reference: Hyphen range comparisons

    master

    Hyphen ranges define an inclusive range between two versions. Note that whitespace is required; 1.2-1.4.5 (no spaces) is interpreted as a single version 1.2.0 with a pre-release 1.4.5.

    • 1.2 - 1.4.5 is equivalent to >= 1.2 <= 1.4.5
    • 2.3.4 - 4.5 is equivalent to >= 2.3.4 <= 4.5
  11. Reference: Wildcard comparisons

    master

    The x, X, and * characters act as wildcards. When used with the = operator, they fall back to patch-level comparison.

    • 1.2.x is equivalent to >= 1.2.0, < 1.3.0
    • >= 1.2.x is equivalent to >= 1.2.0
    • <= 2.x is equivalent to < 3
    • * is equivalent to >= 0.0.0
  12. Reference: Caret (^) range comparisons

    master

    The caret operator allows for major-level changes once a stable (1.0.0) release has occurred. For versions below 1.0.0, the minor version acts as the API stability level.

    • ^1.2.3 is equivalent to >= 1.2.3, < 2.0.0
    • ^1.2.x is equivalent to >= 1.2.0, < 2.0.0
    • ^2.3 is equivalent to >= 2.3, < 3
    • ^2.x is equivalent to >= 2.0.0, < 3
    • ^0.2.3 is equivalent to >=0.2.3 <0.3.0
    • ^0.2 is equivalent to >=0.2.0 <0.3.0
    • ^0.0.3 is equivalent to >=0.0.3 <0.0.4
    • ^0.0 is equivalent to >=0.0.0 <0.1.0
    • ^0 is equivalent to >=0.0.0 <1.0.0