### Tilde Operator Examples Source: https://github.com/masterminds/semver/blob/master/_autodocs/api-reference/constraints.md Demonstrates the behavior of the tilde operator for patch, minor, and major level changes based on the version specified. ```Go ~1.2.3 // >= 1.2.3, < 1.3.0 (patch changes allowed) ~1.2 // >= 1.2.0, < 1.3.0 (patch changes allowed) ~1 // >= 1.0.0, < 2.0.0 (minor changes allowed) ~1.2.x // >= 1.2.0, < 1.3.0 (same as ~1.2) ``` -------------------------------- ### Global Configuration Scope Example Source: https://github.com/masterminds/semver/blob/master/_autodocs/configuration.md Shows how global configuration variables affect all parts of the package, including imported libraries. Changes made in one file are visible in others within the same package. ```go // In main.go semver.CoerceNewVersion = false // In util.go (same package) v, _ := semver.NewVersion(input) // Uses CoerceNewVersion = false // In library.go (imported package) import "github.com/Masterminds/semver/v3" func parseVersion(input string) { v, _ := semver.NewVersion(input) // Also uses CoerceNewVersion = false } ``` -------------------------------- ### Hyphen Range Examples Source: https://github.com/masterminds/semver/blob/master/_autodocs/api-reference/constraints.md Shows how hyphen ranges define inclusive version ranges, with shorthand for patch versions when only minor is specified. ```Go 1.2 - 1.4.5 // >= 1.2, <= 1.4.5 (1.2 means 1.2.0) 2.3.4 - 4.5 // >= 2.3.4, <= 4.5 (4.5 means 4.5.0) ``` -------------------------------- ### Retrieve Original Version String Source: https://github.com/masterminds/semver/blob/master/_autodocs/api-reference/version.md Use Original() to get the exact string that was parsed, including any 'v' prefix or other formatting. ```go v, _ := semver.NewVersion("v1.2.3") fmt.Println(v.Original()) // Output: v1.2.3 fmt.Println(v.String()) // Output: 1.2.3 ``` -------------------------------- ### Caret Operator Examples Source: https://github.com/masterminds/semver/blob/master/_autodocs/api-reference/constraints.md Illustrates the caret operator's behavior, allowing major-level changes for versions 1.0.0 and above, and minor-level changes for pre-1.0 versions. ```Go ^1.2.3 // >= 1.2.3, < 2.0.0 (1.0.0+: major constrained) ^0.2.3 // >= 0.2.3, < 0.3.0 (0.y.z: minor constrained) ^0.0.3 // >= 0.0.3, < 0.0.4 (0.0.z: patch constrained) ^0.0 // >= 0.0.0, < 0.1.0 ^0 // >= 0.0.0, < 1.0.0 ``` -------------------------------- ### Handle Segment Starts With Zero Error Source: https://github.com/masterminds/semver/blob/master/_autodocs/errors.md Detect errors where version segments (major, minor, patch, or numeric prerelease) incorrectly start with a '0' followed by other digits, violating semver rules. ```go // With StrictNewVersion v, err := semver.StrictNewVersion("01.2.3") if err == semver.ErrSegmentStartsZero { fmt.Println("Version segment has invalid leading zero") } // With NewVersion (when CoerceNewVersion is false) semver.CoerceNewVersion = false v, err := semver.NewVersion("01.2.3") if err == semver.ErrSegmentStartsZero { fmt.Println("Leading zero not allowed") } ``` -------------------------------- ### Handle Improper Constraint Syntax Source: https://github.com/masterminds/semver/blob/master/_autodocs/errors.md This example shows how to identify and handle syntax errors in constraint strings, such as invalid operators or malformed version formats within the constraint. It checks the error message for a specific format. ```Go c, err := semver.NewConstraint(">>= 1.2.3") // Invalid operator if err != nil && err.Error() == `improper constraint: ">=> 1.2.3"` { fmt.Println("Invalid constraint syntax") } ``` -------------------------------- ### Get Build Metadata Identifier Source: https://github.com/masterminds/semver/blob/master/_autodocs/api-reference/version.md Metadata() returns the build metadata without the plus prefix. It returns an empty string if no metadata is set. ```go v := semver.MustParse("1.2.3+build345") fmt.Println(v.Metadata()) // Output: build345 v = semver.MustParse("1.2.3") fmt.Println(v.Metadata()) // Output: (empty) ``` -------------------------------- ### Get Canonical String Representation of Constraints Source: https://github.com/masterminds/semver/blob/master/_autodocs/api-reference/constraints.md Returns the canonical string representation of the constraints. Useful for debugging or displaying the constraints in a human-readable format. ```Go func (cs Constraints) String() string ``` ```Go c, _ := semver.NewConstraint(">= 1.2.3") fmt.Println(c.String()) // Output: >= 1.2.3 c, _ = semver.NewConstraint(">= 1.2.3, < 2.0.0 || >= 3.0.0") fmt.Println(c.String()) // Output: >= 1.2.3 < 2.0.0 || >= 3.0.0 ``` -------------------------------- ### Create and Sort a Collection of Versions Source: https://github.com/masterminds/semver/blob/master/_autodocs/api-reference/collection.md Demonstrates how to create a slice of Version pointers from raw strings, convert it to a Collection, and then sort it in ascending order. ```go 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 { log.Fatal(err) } vs[i] = v } sort.Sort(semver.Collection(vs)) // vs is now sorted: [0.4.2, 1.0.0, 1.2.3, 1.3.0, 2.0.0] ``` -------------------------------- ### Get Collection Length Source: https://github.com/masterminds/semver/blob/master/_autodocs/api-reference/collection.md Returns the number of Version instances in the collection. Implements sort.Interface. ```go versions := semver.Collection{ semver.MustParse("1.2.3"), semver.MustParse("1.0.0"), } fmt.Println(versions.Len()) // Output: 2 ``` -------------------------------- ### Get Patch Version Component Source: https://github.com/masterminds/semver/blob/master/_autodocs/api-reference/version.md The Patch() method returns the patch version number as a uint64. ```go v := semver.MustParse("1.2.3") fmt.Println(v.Patch()) // Output: 3 ``` -------------------------------- ### Create Version from Components Source: https://github.com/masterminds/semver/blob/master/_autodocs/api-reference/version.md Constructs a Version instance directly from major, minor, and patch numbers, along with optional prerelease and metadata strings. Does not validate prerelease or metadata formats. ```Go v := semver.New(1, 2, 3, "beta.1", "build345") fmt.Println(v.String()) // Output: 1.2.3-beta.1+build345 v = semver.New(2, 0, 0, "", "") fmt.Println(v.String()) // Output: 2.0.0 ``` -------------------------------- ### Including Prerelease Versions Source: https://github.com/masterminds/semver/blob/master/_autodocs/api-reference/constraints.md Demonstrates how to explicitly include prerelease versions in constraints by appending a prerelease identifier. ```Go c, _ := semver.NewConstraint(">= 1.2.3-0") // Now matches: 1.2.3-0, 1.2.3-alpha, 1.2.3, 1.2.4-beta, 1.2.4, etc. ``` -------------------------------- ### Get Minor Version Component Source: https://github.com/masterminds/semver/blob/master/_autodocs/api-reference/version.md The Minor() method returns the minor version number as a uint64. ```go v := semver.MustParse("1.2.3") fmt.Println(v.Minor()) // Output: 2 ``` -------------------------------- ### Default Configuration: Flexible Parsing with Specific Errors Source: https://github.com/masterminds/semver/blob/master/_autodocs/configuration.md Shows the recommended default configuration where CoerceNewVersion is true, allowing flexible input, and DetailedNewVersionErrors is true, providing specific error feedback. ```go // Default settings (no configuration needed) // CoerceNewVersion = true // DetailedNewVersionErrors = true // Accepts flexible input but provides specific error feedback v, err := semver.NewVersion("1.2") // ✓ Works, becomes "1.2.0" v, err := semver.NewVersion("v1.2") // ✓ Works, becomes "1.2.0" v, err := semver.NewVersion("1.a") // Specific error about invalid characters // For strict validation, use StrictNewVersion v, err := semver.StrictNewVersion("1.2") // ✗ Error: does not have 3 parts ``` -------------------------------- ### Get Major Version Component Source: https://github.com/masterminds/semver/blob/master/_autodocs/api-reference/version.md The Major() method returns the major version number as a uint64. ```go v := semver.MustParse("1.2.3") fmt.Println(v.Major()) // Output: 1 ``` -------------------------------- ### Get Prerelease Identifier Source: https://github.com/masterminds/semver/blob/master/_autodocs/api-reference/version.md Prerelease() returns the prerelease identifier without the hyphen prefix. It returns an empty string if no prerelease is set. ```go v := semver.MustParse("1.2.3-beta.1") fmt.Println(v.Prerelease()) // Output: beta.1 v = semver.MustParse("1.2.3") fmt.Println(v.Prerelease()) // Output: (empty) ``` -------------------------------- ### Using Collection with Go's Standard Sort Package Source: https://github.com/masterminds/semver/blob/master/_autodocs/api-reference/collection.md Demonstrates how to use the semver.Collection type with standard Go sort functions like sort.Sort, sort.Reverse, sort.Stable, and sort.IsSorted. It also shows how to perform a binary search on a sorted collection. ```go versions := semver.Collection{...} // Standard sort sort.Sort(versions) // Reverse sort sort.Sort(sort.Reverse(versions)) // Stable sort (preserves order of equal elements) sort.Stable(versions) // Check if sorted isSorted := sort.IsSorted(versions) // Search for a version target := semver.MustParse("1.2.3") // Note: Search requires the collection to be sorted first idx, found := sort.Search(len(versions), func(i int) bool { return !versions[i].LessThan(target) }) ``` -------------------------------- ### Compare Versions Source: https://github.com/masterminds/semver/blob/master/_autodocs/api-reference/version.md Compares this version to another, returning -1 if less than, 0 if equal, or 1 if greater than. Prerelease versions are considered lower than their release counterparts, and build metadata is ignored. ```go v1 := semver.MustParse("1.2.3") v2 := semver.MustParse("1.2.4") fmt.Println(v1.Compare(v2)) // Output: -1 fmt.Println(v2.Compare(v1)) // Output: 1 fmt.Println(v1.Compare(v1)) // Output: 0 // Prerelease comparison pre := semver.MustParse("1.2.3-beta") rel := semver.MustParse("1.2.3") fmt.Println(pre.Compare(rel)) // Output: -1 (prerelease < release) // Metadata is ignored v3 := semver.MustParse("1.2.3+build1") v4 := semver.MustParse("1.2.3+build2") fmt.Println(v3.Compare(v4)) // Output: 0 (metadata ignored) ``` -------------------------------- ### Compare Versions: Equal Source: https://github.com/masterminds/semver/blob/master/_autodocs/api-reference/version.md Use Equal to determine if two versions are identical in terms of major, minor, patch, and prerelease components. Build metadata is ignored. ```go v1 := semver.MustParse("1.2.3+build1") v2 := semver.MustParse("1.2.3+build2") fmt.Println(v1.Equal(v2)) // Output: true (metadata ignored) v3 := semver.MustParse("1.2.3-beta") v4 := semver.MustParse("1.2.3") fmt.Println(v3.Equal(v4)) // Output: false (different prerelease) ``` -------------------------------- ### Create Constraints with AND Logic Source: https://github.com/masterminds/semver/blob/master/_autodocs/api-reference/constraints.md Combine multiple constraints with spaces or commas to enforce AND logic, meaning all constraints must be met. Useful for defining precise version ranges. ```Go c, _ := semver.NewConstraint(">= 1.2.3, < 2.0.0") // Matches: [1.2.3, 2.0.0) ``` -------------------------------- ### Set Build Metadata Source: https://github.com/masterminds/semver/blob/master/_autodocs/api-reference/version.md Returns a new Version with the build metadata updated. Pass an empty string to remove the metadata. The metadata value must not include the plus prefix. ```go v := semver.MustParse("1.2.3") next, _ := v.SetMetadata("build.123") fmt.Println(next.String()) // Output: 1.2.3+build.123 next, _ = next.SetMetadata("") fmt.Println(next.String()) // Output: 1.2.3 ``` -------------------------------- ### Handle Constraint String Too Long Error Source: https://github.com/masterminds/semver/blob/master/_autodocs/errors.md This example demonstrates how to catch the `ErrConstraintTooLong` error, which occurs when a constraint string exceeds the maximum allowed length of 512 bytes. This prevents excessive memory allocation. ```Go longConstraint := ">= " + strings.Repeat("1.2.3", 200) c, err := semver.NewConstraint(longConstraint) if err == semver.ErrConstraintTooLong { fmt.Println("Constraint string exceeds maximum length") } ``` -------------------------------- ### New Source: https://github.com/masterminds/semver/blob/master/_autodocs/api-reference/version.md Creates a Version instance directly from component parts (major, minor, patch, prerelease, and metadata) without parsing a string. This method is useful for constructing versions programmatically when the string format is not readily available or needs to be assembled from separate pieces. ```APIDOC ## New ### Description Creates a Version instance directly from component parts without parsing a string. Does not validate prerelease or metadata formats. ### Method func New(major, minor, patch uint64, pre, metadata string) *Version ### Parameters #### Path Parameters - **major** (uint64) - Required - Major version number - **minor** (uint64) - Required - Minor version number - **patch** (uint64) - Required - Patch version number - **pre** (string) - Required - Prerelease identifier (without hyphen prefix), or empty string - **metadata** (string) - Required - Build metadata identifier (without plus prefix), or empty string ### Response #### Success Response - **Version** (*Version) - Version instance constructed from the given parts. ### Request Example ```go v := semver.New(1, 2, 3, "beta.1", "build345") fmt.Println(v.String()) // Output: 1.2.3-beta.1+build345 v = semver.New(2, 0, 0, "", "") fmt.Println(v.String()) // Output: 2.0.0 ``` ``` -------------------------------- ### Check version against constraints Source: https://github.com/masterminds/semver/blob/master/README.md Parses a constraint string and a version string, then evaluates if the version satisfies the constraint. ```go 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) ``` -------------------------------- ### Safe Goroutine Configuration Pattern Source: https://github.com/masterminds/semver/blob/master/_autodocs/configuration.md Illustrates the safe pattern for configuring global variables: set them once at program startup before spawning any goroutines that might access them. ```go // ✓ SAFE: Configure once at program start func init() { semver.CoerceNewVersion = true semver.DetailedNewVersionErrors = true } func main() { // Now safe to use from any goroutine go parseVersions(versions) } ``` -------------------------------- ### Compare() Source: https://github.com/masterminds/semver/blob/master/_autodocs/api-reference/version.md Compares this version to another. Returns -1 if less than, 0 if equal, or 1 if greater than the other version. Build metadata is ignored in comparison. Prerelease versions are considered lower than their release counterparts. ```APIDOC ## Compare(o *Version) ### Description Compares this version to another. Returns -1 if less than, 0 if equal, or 1 if greater than the other version. Build metadata is ignored in comparison. Prerelease versions are considered lower than their release counterparts. Pre-releases are always included in the comparison per the semantic versioning specification. ### Method func (v *Version) Compare(o *Version) int ### Parameters #### Path Parameters - **o** (*Version) - Required - Version to compare against ### Returns `int` — `-1` if v < o, `0` if v == o, `1` if v > o. ### Example ```go v1 := semver.MustParse("1.2.3") v2 := semver.MustParse("1.2.4") fmt.Println(v1.Compare(v2)) // Output: -1 fmt.Println(v2.Compare(v1)) // Output: 1 fmt.Println(v1.Compare(v1)) // Output: 0 // Prerelease comparison pre := semver.MustParse("1.2.3-beta") rel := semver.MustParse("1.2.3") fmt.Println(pre.Compare(rel)) // Output: -1 (prerelease < release) // Metadata is ignored v3 := semver.MustParse("1.2.3+build1") v4 := semver.MustParse("1.2.3+build2") fmt.Println(v3.Compare(v4)) // Output: 0 (metadata ignored) ``` ``` -------------------------------- ### Check Version Against Constraints Source: https://github.com/masterminds/semver/blob/master/_autodocs/api-reference/constraints.md Tests if a given Version satisfies the Constraints. By default, prerelease versions are not included unless explicitly allowed by the constraint or if `IncludePrerelease` is set to true. ```go c, _ := semver.NewConstraint(">= 1.2.3") v, _ := semver.NewVersion("1.3.0") fmt.Println(c.Check(v)) // Output: true // Prerelease handling c, _ = semver.NewConstraint(">= 1.2.3") v, _ = semver.NewVersion("1.3.0-beta") fmt.Println(c.Check(v)) // Output: false (prerelease not included) // Include prerelease explicitly c.IncludePrerelease = true fmt.Println(c.Check(v)) // Output: true // OR constraints c, _ = semver.NewConstraint(">= 1.0.0, < 1.5.0 || >= 2.0.0") v, _ = semver.NewVersion("2.1.0") fmt.Println(c.Check(v)) // Output: true (matches second OR group) v, _ = semver.NewVersion("1.6.0") fmt.Println(c.Check(v)) // Output: false (between groups) ``` -------------------------------- ### Sort Collection with Prerelease Versions Source: https://github.com/masterminds/semver/blob/master/_autodocs/api-reference/collection.md Demonstrates sorting a collection that includes prerelease versions. Prerelease versions sort before their release counterparts. ```go versions := semver.Collection{ semver.MustParse("1.0.0"), semver.MustParse("1.0.0-beta"), semver.MustParse("1.0.0-alpha"), semver.MustParse("1.0.0-rc.1"), } sort.Sort(versions) for _, v := range versions { fmt.Println(v.String()) } // Output: // 1.0.0-alpha // 1.0.0-beta // 1.0.0-rc.1 // 1.0.0 ``` -------------------------------- ### Validate Version Against Constraints Source: https://github.com/masterminds/semver/blob/master/_autodocs/errors.md Demonstrates validating a version against multiple constraints and iterating through validation errors. Use this to check if a version satisfies a set of rules. ```Go c, _ := semver.NewConstraint("<= 1.2.3, >= 1.4") v, _ := semver.NewVersion("1.3") valid, errors := c.Validate(v) if !valid { for _, err := range errors { fmt.Println(err) } } ``` -------------------------------- ### String() Source: https://github.com/masterminds/semver/blob/master/_autodocs/api-reference/version.md Converts a Version to its string representation in the format major.minor.patch[-prerelease][+metadata]. Does not include a leading v prefix, even if the original parsed string had one. See Original() to retrieve the original input. ```APIDOC ## String() Converts a Version to its string representation in the format `major.minor.patch[-prerelease][+metadata]`. Does not include a leading `v` prefix, even if the original parsed string had one. See `Original()` to retrieve the original input. ### Method Signature ```go func (v Version) String() string ``` ### Returns - **`string`** — Canonical string representation of the version. ### Example ```go v := semver.MustParse("v1.2.3-beta.1+build345") fmt.Println(v.String()) // Output: 1.2.3-beta.1+build345 ``` ``` -------------------------------- ### Create Version from String (Coercing) Source: https://github.com/masterminds/semver/blob/master/_autodocs/api-reference/version.md Parses a version string, attempting to coerce non-compliant formats into semantic versions. Handles incomplete versions (e.g., '1.2' becomes '1.2.0') and leading 'v' prefixes. ```Go v, err := semver.NewVersion("1.2.3-beta.1+build345") if err != nil { log.Fatal(err) } fmt.Println(v.String()) // Output: 1.2.3-beta.1+build345 // Coerces incomplete versions v, err = semver.NewVersion("1.2") if err == nil { fmt.Println(v.String()) // Output: 1.2.0 } // Handles v prefix v, err = semver.NewVersion("v1.2.3") if err == nil { fmt.Println(v.String()) // Output: 1.2.3 } ``` -------------------------------- ### Create Semver Constraint Source: https://github.com/masterminds/semver/blob/master/_autodocs/api-reference/constraints.md Creates a Constraints instance from a string. Supports basic operators, wildcards, hyphen ranges, tilde (~), and caret (^) operators. Multiple constraints can be combined with spaces/commas for AND logic or `||` for OR logic. ```go c, err := semver.NewConstraint(">= 1.2.3") if err != nil { log.Fatal(err) } // Complex AND/OR c, _ = semver.NewConstraint(">= 1.0.0, < 2.0.0 || >= 3.0.0, < 4.0.0") // Caret (compatible with major versions) c, _ = semver.NewConstraint("^1.2.3") // >= 1.2.3, < 2.0.0 // Tilde (compatible with minor versions) c, _ = semver.NewConstraint("~1.2.3") // >= 1.2.3, < 1.3.0 // Hyphen range c, _ = semver.NewConstraint("1.2 - 1.4.5") // >= 1.2, <= 1.4.5 // Wildcards c, _ = semver.NewConstraint("1.2.x") // >= 1.2.0, < 1.3.0 ``` -------------------------------- ### Metadata() Source: https://github.com/masterminds/semver/blob/master/_autodocs/api-reference/version.md Returns the build metadata without the plus prefix. Returns empty string if no metadata is set. ```APIDOC ## Metadata() Returns the build metadata without the plus prefix. Returns empty string if no metadata is set. ### Method Signature ```go func (v Version) Metadata() string ``` ### Returns - **`string`** — Build metadata identifier, or empty string. ### Example ```go v := semver.MustParse("1.2.3+build345") fmt.Println(v.Metadata()) // Output: build345 v = semver.MustParse("1.2.3") fmt.Println(v.Metadata()) // Output: (empty) ``` ``` -------------------------------- ### Create Strict Version from String Source: https://github.com/masterminds/semver/blob/master/_autodocs/api-reference/version.md Parses a version string strictly adhering to the semantic version format (major.minor.patch). Does not support leading 'v' prefixes or incomplete versions. ```Go v, err := semver.StrictNewVersion("1.2.3") if err != nil { log.Fatal(err) } // These fail with StrictNewVersion but work with NewVersion _, err = semver.StrictNewVersion("1.2") // Error: does not have 3 parts _, err = semver.StrictNewVersion("v1.2.3") // Error: invalid character 'v' _, err = semver.StrictNewVersion("01.2.3") // Error: segment starts with 0 ``` -------------------------------- ### MustParse Source: https://github.com/masterminds/semver/blob/master/_autodocs/api-reference/version.md Creates a Version instance by parsing a version string. Panics if parsing fails. Useful for hardcoded version constants where parsing failure indicates a code error. ```APIDOC ## MustParse Creates a Version instance by parsing a version string. Panics if parsing fails. Useful for hardcoded version constants where parsing failure indicates a code error. ### Function Signature ```go func MustParse(v string) *Version ``` ### Parameters #### Path Parameters - **v** (string) - Required - Version string to parse ### Returns - **`*Version`** — Parsed Version instance. ### Panics When the version string cannot be parsed. ### Example ```go const latest = "1.2.3" v := semver.MustParse(latest) // Safe, version is constant // Panics on error (for testing only, not production) v := semver.MustParse("invalid version") // Panic! ``` ``` -------------------------------- ### Parse Version String with MustParse Source: https://github.com/masterminds/semver/blob/master/_autodocs/api-reference/version.md Use MustParse to create a Version instance from a string. It panics on invalid input, making it suitable for hardcoded constants where errors indicate a code issue. ```go const latest = "1.2.3" v := semver.MustParse(latest) // Safe, version is constant // Panics on error (for testing only, not production) v := semver.MustParse("invalid version") // Panic! ``` -------------------------------- ### Set Prerelease Identifier Source: https://github.com/masterminds/semver/blob/master/_autodocs/api-reference/version.md Returns a new Version with the prerelease identifier updated. Pass an empty string to remove the prerelease. The prerelease value must not include the hyphen prefix. ```go v := semver.MustParse("1.2.3") next, _ := v.SetPrerelease("beta.1") fmt.Println(next.String()) // Output: 1.2.3-beta.1 next, _ = next.SetPrerelease("") fmt.Println(next.String()) // Output: 1.2.3 ``` -------------------------------- ### CalVer Support with Coercion Source: https://github.com/masterminds/semver/blob/master/_autodocs/configuration.md Enable CoerceNewVersion to true and DetailedNewVersionErrors to true to accept calendar versioning and other flexible formats. The library will attempt to coerce non-standard formats into a SemVer-compatible structure. ```go semver.CoerceNewVersion = true semver.DetailedNewVersionErrors = true // Accepts CalVer and other flexible formats v, _ := semver.NewVersion("2024.01.15") // ✓ Becomes "2024.1.15" v, _ := semver.NewVersion("v2024.1") // ✓ Becomes "2024.1.0" ``` -------------------------------- ### Equal() Source: https://github.com/masterminds/semver/blob/master/_autodocs/api-reference/version.md Checks if the current version is equal to another version. Equality is determined by matching major, minor, and patch components, ignoring build metadata. ```APIDOC ## Equal() ### Description Returns true if this version equals another version. Versions are equal if major, minor, patch, and prerelease components match. Build metadata is ignored. ### Method `func (v *Version) Equal(o *Version) bool` ### Parameters #### Path Parameters - **o** (*Version) - Required - Version to compare against ### Returns - **bool** - True if versions are equal (ignoring metadata). ### Example ```go v1 := semver.MustParse("1.2.3+build1") v2 := semver.MustParse("1.2.3+build2") fmt.Println(v1.Equal(v2)) // Output: true (metadata ignored) v3 := semver.MustParse("1.2.3-beta") v4 := semver.MustParse("1.2.3") fmt.Println(v3.Equal(v4)) // Output: false (different prerelease) ``` ``` -------------------------------- ### SetMetadata() Source: https://github.com/masterminds/semver/blob/master/_autodocs/api-reference/version.md Returns a new Version with the build metadata updated. The metadata value must not include the plus prefix. Pass an empty string to remove the metadata. ```APIDOC ## SetMetadata(metadata string) ### Description Returns a new Version with the build metadata updated. The metadata value must not include the plus prefix. Pass an empty string to remove the metadata. ### Method func (v Version) SetMetadata(metadata string) (Version, error) ### Parameters #### Path Parameters - **metadata** (string) - Required - New metadata identifier without plus prefix, or empty to remove ### Returns `Version`, `error` — New Version with updated metadata, or error if invalid. ### Throws/Rejects - `ErrInvalidMetadata`: When the metadata string contains invalid characters or is empty (when non-zero length) ### Example ```go v := semver.MustParse("1.2.3") next, _ := v.SetMetadata("build.123") fmt.Println(next.String()) // Output: 1.2.3+build.123 next, _ = next.SetMetadata("") fmt.Println(next.String()) // Output: 1.2.3 ``` ``` -------------------------------- ### Convert Version to String Source: https://github.com/masterminds/semver/blob/master/_autodocs/api-reference/version.md The String() method converts a Version object to its canonical string representation. It does not include a 'v' prefix. ```go v := semver.MustParse("v1.2.3-beta.1+build345") fmt.Println(v.String()) // Output: 1.2.3-beta.1+build345 ``` -------------------------------- ### NewVersion Source: https://github.com/masterminds/semver/blob/master/_autodocs/api-reference/version.md Creates a Version instance by parsing a version string. It attempts to coerce non-compliant versions into semantic version format by default. This function handles common variations like incomplete versions (e.g., '1.2' becomes '1.2.0') and leading 'v' prefixes. ```APIDOC ## NewVersion ### Description Creates a Version instance by parsing a version string. Attempts to coerce non-compliant versions into semantic version format when the global `CoerceNewVersion` flag is true (default). For example, parses `1.2` as `1.2.0` and removes a leading `v` prefix. ### Method func NewVersion(v string) (*Version, error) ### Parameters #### Path Parameters - **v** (string) - Required - Version string to parse, e.g., `1.2.3`, `v1.2.3`, `1.2`, or `1.2.3-beta.1+build345` ### Response #### Success Response - **Version** (*Version) - Parsed Version instance - **error** (error) - nil if parsing is successful #### Error Response - **ErrEmptyString** - When the input string is empty - **ErrVersionTooLong** - When the version string exceeds `MaxVersionLen` (256 bytes) - **ErrInvalidSemVer** - When the version string cannot be coerced into a valid semantic version - **ErrSegmentStartsZero** - When a version segment starts with 0 and `CoerceNewVersion` is false (e.g., `01.2.3`) - **ErrInvalidCharacters** - When the version contains invalid characters - **ErrInvalidPrerelease** - When the prerelease identifier is invalid - **ErrInvalidMetadata** - When the metadata identifier is invalid ### Request Example ```go v, err := semver.NewVersion("1.2.3-beta.1+build345") if err != nil { log.Fatal(err) } fmt.Println(v.String()) // Output: 1.2.3-beta.1+build345 // Coerces incomplete versions v, err = semver.NewVersion("1.2") if err == nil { fmt.Println(v.String()) // Output: 1.2.0 } // Handles v prefix v, err = semver.NewVersion("v1.2.3") if err == nil { fmt.Println(v.String()) // Output: 1.2.3 } ``` ``` -------------------------------- ### Create Constraints with OR Logic Source: https://github.com/masterminds/semver/blob/master/_autodocs/api-reference/constraints.md Combine multiple constraint sets with '||' to enforce OR logic, meaning at least one set of constraints must be met. Useful for defining alternative valid version ranges. ```Go c, _ := semver.NewConstraint(">= 1.0.0, < 2.0.0 || >= 3.0.0, < 4.0.0") // Matches: [1.0.0, 2.0.0) ∪ [3.0.0, 4.0.0) ``` -------------------------------- ### CoerceNewVersion: Default and Strict Parsing Source: https://github.com/masterminds/semver/blob/master/_autodocs/configuration.md Demonstrates how CoerceNewVersion affects NewVersion parsing. When true (default), it allows flexible input like 'v1.2' or '1.2'. When false, it enforces strict semantic versioning rules. ```go // Default: CoerceNewVersion = true v, _ := semver.NewVersion("v1.2") // ✓ "1.2.0" v, _ := semver.NewVersion("1.2") // ✓ "1.2.0" v, _ := semver.NewVersion("01.2.3") // ✓ "1.2.3" (CalVer support) // Strict mode: CoerceNewVersion = false semver.CoerceNewVersion = false v, err := semver.NewVersion("v1.2") // ✗ error (has v prefix) v, err := semver.NewVersion("1.2") // ✗ error (only 2 parts) v, err := semver.NewVersion("01.2.3") // ✗ error (leading zero) // StrictNewVersion always uses strict validation regardless v, err := semver.StrictNewVersion("v1.2.3") // ✗ error (has v prefix) ``` -------------------------------- ### Check Source: https://github.com/masterminds/semver/blob/master/_autodocs/api-reference/constraints.md Tests whether a version satisfies the constraints. Returns true if the version meets at least one of the OR groups and all AND conditions within that group. Prerelease versions are handled based on the `IncludePrerelease` setting. ```APIDOC ## Check() Tests whether a version satisfies the constraints. Returns true if the version meets at least one of the OR groups (constraints connected by `||`) and all AND conditions within that group. Prerelease versions are skipped unless `IncludePrerelease` is true or the constraint range explicitly includes a prerelease identifier (e.g., `-0`). ### Method Signature ```go func (cs Constraints) Check(v *Version) bool ``` ### Parameters #### Path Parameters - **v** (*Version) - Required - Version to check against the constraints ### Returns - **`bool`**: True if the version satisfies the constraints. ### Example ```go c, _ := semver.NewConstraint(">= 1.2.3") v, _ := semver.NewVersion("1.3.0") fmt.Println(c.Check(v)) // Output: true // Prerelease handling c, _ = semver.NewConstraint(">= 1.2.3") v, _ = semver.NewVersion("1.3.0-beta") fmt.Println(c.Check(v)) // Output: false (prerelease not included) // Include prerelease explicitly c.IncludePrerelease = true fmt.Println(c.Check(v)) // Output: true // OR constraints c, _ = semver.NewConstraint(">= 1.0.0, < 1.5.0 || >= 2.0.0") v, _ = semver.NewVersion("2.1.0") fmt.Println(c.Check(v)) // Output: true (matches second OR group) v, _ = semver.NewVersion("1.6.0") fmt.Println(c.Check(v)) // Output: false (between groups) ``` ``` -------------------------------- ### Validate Version Against Constraints Source: https://github.com/masterminds/semver/blob/master/_autodocs/api-reference/constraints.md Tests if a version satisfies the constraints. Returns a boolean indicating success and a slice of errors if validation fails. Useful for detailed error reporting on version mismatches. ```Go func (cs Constraints) Validate(v *Version) (bool, []error) ``` ```Go c, _ := semver.NewConstraint("<= 1.2.3, >= 1.4") v, _ := semver.NewVersion("1.3") valid, errors := c.Validate(v) fmt.Println(valid) // Output: false for _, err := range errors { fmt.Println(err) // Output: 1.3 is greater than 1.2.3 // 1.3 is less than 1.4 } // Successful validation c, _ = semver.NewConstraint(">= 1.2.3") v, _ = semver.NewVersion("1.3.0") valid, errors = c.Validate(v) fmt.Println(valid) // Output: true fmt.Println(len(errors)) // Output: 0 ``` -------------------------------- ### String() Source: https://github.com/masterminds/semver/blob/master/_autodocs/api-reference/constraints.md Returns the canonical string representation of the constraints. ```APIDOC ## String() ### Description Returns the canonical string representation of the constraints. ### Method Signature ```go func (cs Constraints) String() string ``` ### Returns - **string** - String representation of the constraints. ### Example ```go c, _ := semver.NewConstraint(">= 1.2.3") fmt.Println(c.String()) // Output: >= 1.2.3 c, _ = semver.NewConstraint(">= 1.2.3, < 2.0.0 || >= 3.0.0") fmt.Println(c.String()) // Output: >= 1.2.3 < 2.0.0 || >= 3.0.0 ``` ``` -------------------------------- ### Unsafe Goroutine Configuration Source: https://github.com/masterminds/semver/blob/master/_autodocs/configuration.md Demonstrates an unsafe pattern where multiple goroutines concurrently modify global configuration variables. This can lead to unpredictable behavior and should be avoided. ```go // ✗ UNSAFE: Multiple goroutines changing global state go func() { semver.CoerceNewVersion = false v, _ := semver.NewVersion(input1) }() go func() { semver.CoerceNewVersion = true v, _ := semver.NewVersion(input2) }() ``` -------------------------------- ### Value() Source: https://github.com/masterminds/semver/blob/master/_autodocs/api-reference/version.md Implements the `driver.Valuer` interface, returning the string representation of the version suitable for database storage. ```APIDOC ## Value() ### Description Implements the `driver.Valuer` interface. Returns the string representation for database storage. ### Method `func (v Version) Value() (driver.Value, error)` ### Returns - **driver.Value** - String value suitable for database storage. - **error** - Error during value retrieval. ### Example ```go v := semver.MustParse("1.2.3") val, _ := v.Value() fmt.Println(val) // Output: 1.2.3 (as driver.Value) ``` ``` -------------------------------- ### Value for Database Storage Source: https://github.com/masterminds/semver/blob/master/_autodocs/api-reference/version.md Implement the driver.Valuer interface to return the string representation of a Version, suitable for storing in databases. Ensures consistent data format. ```go v := semver.MustParse("1.2.3") val, _ := v.Value() fmt.Println(val) // Output: 1.2.3 (as driver.Value) ``` -------------------------------- ### Marshal to JSON Source: https://github.com/masterminds/semver/blob/master/_autodocs/api-reference/version.md Implement the json.Marshaler interface to encode a Version as a JSON string. This is useful when storing or transmitting version data. ```go v := semver.MustParse("1.2.3") data, _ := json.Marshal(v) fmt.Println(string(data)) // Output: "1.2.3" ``` -------------------------------- ### Parse Semantic Version Source: https://github.com/masterminds/semver/blob/master/README.md Use `NewVersion` to parse a semantic version string. It attempts to coerce non-compliant versions into a valid semantic version. An error is returned if parsing fails. ```go v, err := semver.NewVersion("1.2.3-beta.1+build345") ``` -------------------------------- ### Marshal Constraints to Text Source: https://github.com/masterminds/semver/blob/master/_autodocs/api-reference/constraints.md Implements the encoding.TextMarshaler interface to encode constraints as text. Useful for serializing constraints to text-based formats. ```Go func (cs Constraints) MarshalText() ([]byte, error) ``` ```Go c, _ := semver.NewConstraint(">= 1.2.3") data, _ := c.MarshalText() fmt.Println(string(data)) // Output: >= 1.2.3 ``` -------------------------------- ### Marshal to Text Source: https://github.com/masterminds/semver/blob/master/_autodocs/api-reference/version.md Implement the encoding.TextMarshaler interface to encode a Version as plain text. This is suitable for simple text-based storage or output. ```go v := semver.MustParse("1.2.3") data, _ := v.MarshalText() fmt.Println(string(data)) // Output: 1.2.3 ``` -------------------------------- ### Validate Version Against Constraint in Go Source: https://github.com/masterminds/semver/blob/master/README.md Checks if a version satisfies a defined constraint and retrieves specific error messages if validation fails. ```go 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 parseable. } // 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" } ``` -------------------------------- ### Prerelease() Source: https://github.com/masterminds/semver/blob/master/_autodocs/api-reference/version.md Returns the prerelease identifier without the hyphen prefix. Returns empty string if no prerelease is set. ```APIDOC ## Prerelease() Returns the prerelease identifier without the hyphen prefix. Returns empty string if no prerelease is set. ### Method Signature ```go func (v Version) Prerelease() string ``` ### Returns - **`string`** — Prerelease identifier, or empty string. ### Example ```go v := semver.MustParse("1.2.3-beta.1") fmt.Println(v.Prerelease()) // Output: beta.1 v = semver.MustParse("1.2.3") fmt.Println(v.Prerelease()) // Output: (empty) ``` ``` -------------------------------- ### MarshalText() Source: https://github.com/masterminds/semver/blob/master/_autodocs/api-reference/constraints.md Implements the encoding.TextMarshaler interface. Encodes the constraints as text using the string representation. ```APIDOC ## MarshalText() ### Description Implements the `encoding.TextMarshaler` interface. Encodes the constraints as text using the string representation. ### Method Signature ```go func (cs Constraints) MarshalText() ([]byte, error) ``` ### Returns - **[]byte** - Text representation of the constraints. - **error** - Error if encoding fails. ### Example ```go c, _ := semver.NewConstraint(">= 1.2.3") data, _ := c.MarshalText() fmt.Println(string(data)) // Output: >= 1.2.3 ``` ``` -------------------------------- ### Scan() Source: https://github.com/masterminds/semver/blob/master/_autodocs/api-reference/version.md Implements the `sql.Scanner` interface, decoding a database value (string, byte slice, or nil) into a Version. ```APIDOC ## Scan() ### Description Implements the `sql.Scanner` interface. Decodes a database value into a Version. Accepts strings, byte slices, or nil. ### Method `func (v *Version) Scan(value interface{}) error` ### Parameters #### Path Parameters - **value** (interface{}) - Required - Database value (string, []byte, or nil) ### Returns - **error** - Error if value is nil or unsupported type, or version cannot be parsed. ### Example ```go var v semver.Version v.Scan("1.2.3") fmt.Println(v.String()) // Output: 1.2.3 ``` ``` -------------------------------- ### Check for Specific Parsing Errors Source: https://github.com/masterminds/semver/blob/master/_autodocs/errors.md Handles specific known parsing errors like empty strings or overly long versions during version creation. Use direct error comparison for precise error handling. ```Go v, err := semver.NewVersion(input) if err == semver.ErrEmptyString { // Handle empty input } else if err == semver.ErrVersionTooLong { // Handle oversized input } else if err != nil { // Handle other parsing errors } ``` -------------------------------- ### MarshalText() Source: https://github.com/masterminds/semver/blob/master/_autodocs/api-reference/version.md Implements the `encoding.TextMarshaler` interface, encoding the version as plain text. ```APIDOC ## MarshalText() ### Description Implements the `encoding.TextMarshaler` interface. Encodes the version as text. ### Method `func (v Version) MarshalText() ([]byte, error)` ### Returns - **[]byte** - Text representation of the version. - **error** - Error during marshaling. ### Example ```go v := semver.MustParse("1.2.3") data, _ := v.MarshalText() fmt.Println(string(data)) // Output: 1.2.3 ``` ``` -------------------------------- ### Compare Versions: GreaterThanEqual Source: https://github.com/masterminds/semver/blob/master/_autodocs/api-reference/version.md Use GreaterThanEqual to check if one version is greater than or equal to another. This is useful for compatibility checks. ```go v1 := semver.MustParse("1.2.3") v2 := semver.MustParse("1.2.3") fmt.Println(v1.GreaterThanEqual(v2)) // Output: true ``` -------------------------------- ### Handle Empty String Version Error Source: https://github.com/masterminds/semver/blob/master/_autodocs/errors.md Use this snippet to catch errors when an empty string is provided to version parsing functions. ```go v, err := semver.NewVersion("") if err == semver.ErrEmptyString { fmt.Println("Version string is empty") } ``` -------------------------------- ### Find Latest Stable Version in Collection Source: https://github.com/masterminds/semver/blob/master/_autodocs/api-reference/collection.md Finds the latest stable version from a collection by sorting in reverse and iterating to find the first non-prerelease version. ```go versions := semver.Collection{ semver.MustParse("1.2.3"), semver.MustParse("1.0.0"), semver.MustParse("1.3.0-beta"), semver.MustParse("2.0.0"), } sort.Sort(sort.Reverse(versions)) // Latest version (first in reverse-sorted collection) latest := versions[0] fmt.Println(latest.String()) // Output: 2.0.0 // Latest non-prerelease for _, v := range versions { if v.Prerelease() == "" { fmt.Println(v.String()) // Output: 2.0.0 break } } ```