semver

package module
v1.0.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 1, 2025 License: MIT Imports: 7 Imported by: 1

README

Semantic Version Parser for Go

CI Godoc Go Report Card

The semver package provides utilities and a parser to work with version numbers that adhere to semantic versioning. The goal of this parser is to be reliable and performant. Reliability is ensured by using a wide range of tests and fuzzing. Performance is achieved by implementing a custom parser instead of the common alternative: regular expressions.

This package implements semantic versioning 2.0.0. Specifically, the current capabilities of this package include:

  • Parsing version strings.
  • Checking if a string is valid version string. This check doesn’t require full parsing of the version.
  • Comparing versions.
  • Sorting versions.

The version strings can optionally have a "v" prefix.

Future versions of this library will probably include the following planned features:

  • Version ranges and constraints.
  • Wildcard versions.
  • Database compatibility.
  • JSON compatibility.
  • TextMarshaler and TextUnmarshaler compatibility.
  • See how the parser could be made faster.

Install

go get github.com/anttikivi/semver

Usage

The functions accept version strings that adhere to the semantic versioning. The version strings may start with a v prefix.

Parsing versions

The package includes two types of functions for parsing versions. There are the Parse and ParseLax functions. Parse parses only full valid version strings like "1.2.3", "1.2.3-beta.1", or "1.2.3-beta.1+darwin.amd64". ParseLax works otherwise like Parse but it tries to coerse incomplete core version into a full version. For example, it parses "v1" as 1.0.0 and "1.2-beta" as 1.2.0-beta. Both functions return a pointer to the Version object and an error.

They can be used as follows:

v, err := semver.Parse("1.2.3-beta.1")

The package also offers MustParse and MustParseLax variants of these functions. They are otherwise the same but only return the pointer to Version. They panic on errors.

Validating version strings

The package includes two functions, similar to the parsing functions, for checking if a string is a valid version string. The functions are IsValid and IsValidLax and they return a single boolean value. The return value is analogous to whether the matching parsing function would parse the given string.

Example usage:

ok := semver.IsValid("1.2.3-beta.1")
Sorting versions

The package contains the Versions type that supports sorting using the Go standard library sort package. Versions is defined as []*Version.

Example usage:

a := []string{"1.2.3", "1.0", "1.3", "2", "0.4.2"}
slice := make(Versions, len(a))

for i, s := range {
  slice[i] = semver.MustParseLax(s)
}

sort.Sort(slice)

for _, v := range slice {
  fmt.Println(v.String())
}

The above code would print:

0.4.2
1.0.0
1.2.3
1.3.0
2.0.0

Security

This code should be safe to use in a project and to ensure that, security is an important consideration for the project. It includes tooling to help with securing the code, like fuzz testing, the CodeQL, and strict Golangci-lint ruleset.

If you think you have found a security vulnerability, please disclose it privately according to the security policy.

Development

The included Makefile has the most common tasks you need to do in the project. Run make audit for the tests and linters. To only run the tests, use make test. make lint only runs the linters. Additionally, make bench runs the benchmarks and make fuzz runs the fuzz tests. To customize the test runs, you can pass in additional flags using the GOFLAGS variable. The code can be formatted using make tidy. The Makefile automatically installs all of the required tools.

License

Copyright (c) 2024 Antti Kivi

This project is licensed under the MIT License. For more information, see LICENSE.

Documentation

Overview

Package semver provides utilities and a parser to work with version numbers that adhere to semantic versioning. The goal of this parser is to be reliable and performant. Reliability is ensured by using a wide range of tests and fuzzing. Performance is achieved by implementing a custom parser instead of the common alternative: regular expressions.

This package implements semantic versioning 2.0.0. Specifically, the current capabilities of this package include:

  • Parsing version strings.
  • Checking if a string is valid version string. This check doesn’t require full parsing of the version.
  • Comparing versions.
  • Sorting versions.

The version strings can optionally have a "v" prefix.

Parsing versions

The package includes two types of functions for parsing versions. There are the Parse and ParseLax functions. Parse parses only full valid version strings like "1.2.3", "1.2.3-beta.1", or "1.2.3-beta.1+darwin.amd64". ParseLax works otherwise like Parse but it tries to coerse incomplete core version into a full version. For example, it parses "v1" as "1.0.0" and "1.2-beta" as "1.2.0-beta". Both functions return a pointer to the Version object and an error.

They can be used as follows:

v, err := semver.Parse("1.2.3-beta.1")

The package also offers MustParse and MustParseLax variants of these functions. They are otherwise the same but only return the pointer to Version. They panic on errors.

Validating version strings

The package includes two functions, similar to the parsing functions, for checking if a string is a valid version string. The functions are IsValid and IsValidLax and they return a single boolean value. The return value is analogous to whether the matching parsing function would parse the given string.

Example usage:

ok := semver.IsValid("1.2.3-beta.1")

Sorting versions

The package contains the Versions type that supports sorting using the Go standard library sort package. Versions is defined as []*Version.

Example usage:

a := []string{"1.2.3", "1.0", "1.3", "2", "0.4.2"}
slice := make(Versions, len(a))

for i, s := range {
	slice[i] = semver.MustParseLax(s)
}

sort.Sort(slice)

for _, v := range slice {
	fmt.Println(v.String())
}

The above code would print:

0.4.2
1.0.0
1.2.3
1.3.0
2.0.0

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrInvalidVersion is the error returned by the version parsing functions when
	// they encounter invalid version string.
	ErrInvalidVersion = errors.New("invalid semantic version")

	// ErrParser is returned when there is a problem with the parsing that is not
	// directly related to the caller giving an invalid string.
	ErrParser = errors.New("parsing failed")
)

Common errors returned by the version parser.

Functions

func Compare added in v1.0.0

func Compare(v, w *Version) int

Compare returns

-1 if v is less than w,
 0 if v equals w,
+1 if v is greater than w.

The comparison is done according to the semantic versioning specification.

func IsValid

func IsValid(s string) bool

IsValid reports whether s is a valid semantic version string. The version may have a 'v' prefix.

func IsValidLax added in v1.0.0

func IsValidLax(s string) bool

IsValidLax reports whether s is a valid semantic version string even if it is only a partial version. In other words, this function reads `v1` and `v1.2` as valid versions. The version may have a 'v' prefix.

Types

type Build added in v1.0.0

type Build []string

Build is a list of build identifiers in the Version.

func (Build) String added in v1.0.0

func (b Build) String() string

String returns the string representation of b.

type Prerelease

type Prerelease []PrereleaseIdentifier

A Prerelease holds the pre-release identifiers of a version.

func (Prerelease) String

func (p Prerelease) String() string

String returns the string representation of p.

type PrereleaseIdentifier added in v1.0.0

type PrereleaseIdentifier interface {
	// String returns the string representation of the identifier.
	String() string
	// contains filtered or unexported methods
}

A PrereleaseIdentifier is a single pre-release identifier separated by dots.

type Version

type Version struct {
	Major      uint64
	Minor      uint64
	Patch      uint64
	Prerelease Prerelease
	Build      Build
}

A Version is a parsed instance of a version number that adheres to the semantic versioning 2.0.0.

func MustParse

func MustParse(s string) *Version

MustParse parses the given string into a Version and panics if it encounters an error. The version string may have a 'v' prefix.

func MustParseLax added in v1.0.0

func MustParseLax(s string) *Version

MustParseLax parses the given string into a Version and panics if it encounters an error. The version string number may be partial, i.e. it parses 'v1' into '1.0.0' and 'v1.2' into '1.2.0'. The version may have a 'v' prefix.

func Parse

func Parse(s string) (*Version, error)

Parse parses the given string into a Version. The version string may have a 'v' prefix.

func ParseLax added in v1.0.0

func ParseLax(s string) (*Version, error)

ParseLax parses the given string into a Version. The version number may be partial, i.e. it parses 'v1' into '1.0.0' and 'v1.2' into '1.2.0'. The version string may have a 'v' prefix.

func (*Version) ComparableString added in v1.0.0

func (v *Version) ComparableString() string

ComparableString returns the comparable string representation of the version. It doesn't include the build metadata.

func (*Version) Compare added in v1.0.0

func (v *Version) Compare(w *Version) int

Compare returns

-1 if v is less than w,
 0 if v equals w,
+1 if v is greater than w.

The comparison is done according to the semantic versioning specification.

func (*Version) CoreString added in v1.0.0

func (v *Version) CoreString() string

CoreString returns the core version string representation of the version. It doesn't include the pre-release nor the build metadata.

func (*Version) Equal

func (v *Version) Equal(w *Version) bool

Equal reports whether Version w is equal to v. The two Versions are equal according to this function if all of their parts that are comparable in the semantic versioning specification are equal; this does not include the build metadata.

func (*Version) StrictEqual added in v1.0.0

func (v *Version) StrictEqual(w *Version) bool

StrictEqual reports whether Version w is equal to v. The two Versions are equal if all of their parts are; this includes the build metadata.

func (*Version) String

func (v *Version) String() string

String returns the string representation of v.

type Versions added in v1.0.0

type Versions []*Version

Versions attaches the methods of sort.Interface to a version slice, sorting in increasing order.

func (Versions) Len added in v1.0.0

func (x Versions) Len() int

Len is the number of elements in Versions.

func (Versions) Less added in v1.0.0

func (x Versions) Less(i, j int) bool

Less reports whether the element with index i must sort before the element with index j.

If both Less(i, j) and Less(j, i) are false, then the elements at index i and j are considered equal. Sort may place equal elements in any order in the final result, while Stable preserves the original input order of equal elements.

Less describes a transitive ordering:

  • if both Less(i, j) and Less(j, k) are true, then Less(i, k) must be true as well.
  • if both Less(i, j) and Less(j, k) are false, then Less(i, k) must be false as well.

func (Versions) Swap added in v1.0.0

func (x Versions) Swap(i, j int)

Swap swaps the elements with indexes i and j.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL