semver

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Sep 12, 2026 License: MPL-2.0 Imports: 4 Imported by: 0

README

semver

A small version parser supporting SemVer syntax and partial versions.

Supported formats

1
1.2
1.2.3
v1.2.3
1.2.3-alpha.1
1.2.3+build.2026
1.2.3-rc.1+build.2026

Leading and trailing whitespace is trimmed. Numeric components are limited to uint16 and cannot contain leading zeros.

Partial versions, the v prefix and Unicode suffix identifiers are extensions to SemVer 2.0.0.

Usage

version, err := ParseSemVer("v1.2.3-rc.1", true)
if err != nil {
	log.Fatal(err)
}

fmt.Println(version.Major)      // 1
fmt.Println(version.Minor)      // 2
fmt.Println(version.Patch)      // 3
fmt.Println(version.Suffix)     // -rc.1
fmt.Println(version.String())   // v1.2.3-rc.1

Set allowSuffix to false to reject prerelease and build metadata:

_, err := ParseSemVer("1.2.3-alpha", false)
if errors.Is(err, ErrDisallowedSuffix) {
	// Suffixes are not allowed.
}

Comparison

stable, _ := ParseSemVer("1.0.0", true)
candidate, _ := ParseSemVer("1.0.0-rc.1", true)

stable.HigherThan(candidate) // true
stable.Compare(candidate)    // 1

Compare follows SemVer precedence:

  • Missing components compare as zero.
  • Prerelease versions have lower precedence than releases.
  • Build metadata and the v prefix do not affect precedence.

Equal compares the parsed components, component presence and complete suffix. It ignores the optional v prefix.

Performance

Successful parsing is designed to perform no heap allocations. String allocates the returned string.

Run the tests and benchmarks with:

go test ./...
go test -race ./...
go test -bench=. -benchmem ./...

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrEmptyVersion     = errors.New("empty version")
	ErrInvalidVersion   = errors.New("invalid version")
	ErrInvalidSuffix    = errors.New("invalid version suffix")
	ErrDisallowedSuffix = errors.New("disallowed version suffix")
)

Functions

This section is empty.

Types

type SemVer

type SemVer struct {
	Major uint16
	Minor uint16
	Patch uint16

	HasMinor bool
	HasPatch bool

	Prefix byte
	Suffix string
}

func NewEmptySemVer

func NewEmptySemVer() SemVer

func ParseSemVer

func ParseSemVer(input string, allowSuffix bool) (SemVer, error)

func (SemVer) Compare

func (s SemVer) Compare(b SemVer) int

Compare compares semantic-version precedence. Prefixes, missing zero components and build metadata do not affect precedence.

func (SemVer) Equal

func (s SemVer) Equal(b SemVer) bool

Equal compares parsed identity, ignoring the optional v prefix.

func (SemVer) HigherThan

func (s SemVer) HigherThan(b SemVer) bool

func (SemVer) String

func (s SemVer) String() string

Jump to

Keyboard shortcuts

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