parser

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Apr 6, 2026 License: BSD-3-Clause Imports: 6 Imported by: 0

Documentation

Overview

Package parser provides a grammar-based version string parser using participle. The grammar supports SemVer 2.0.0, Go module versions, Microsoft assembly versions, and various extensions as documented in docs/grammar/version.ebnf.

Index

Constants

View Source
const (
	LogVersionParsed    = "version_parsed"
	LogVersionValidated = "version_validated"
	LogParseError       = "parse_error"
	LogValidationError  = "validation_error"
)

Log messages for structured logging.

View Source
const (
	ErrEmptyVersion         = "version string cannot be empty"
	ErrLeadingZero          = "numeric identifier cannot have leading zeros"
	ErrEmptyIdentifier      = "identifier cannot be empty"
	ErrMajorRequired        = "major version is required"
	ErrNegativeVersion      = "version component cannot be negative"
	ErrInvalidPreRelease    = "invalid pre-release identifier"
	ErrInvalidBuildMetadata = "invalid build metadata"
)

Error constants for parser validation.

Variables

Parser is the version string parser built from the grammar.

View Source
var VersionLexer = lexer.MustSimple([]lexer.SimpleRule{

	{Name: "Whitespace", Pattern: `[ \t]+`},

	{Name: "Dot", Pattern: `\.`},
	{Name: "Plus", Pattern: `\+`},

	{Name: "Dashes", Pattern: `--+`},

	{Name: "Dash", Pattern: `-`},

	{Name: "Prefix", Pattern: `[vV]`},

	{Name: "Mixed", Pattern: `[0-9]+[a-zA-Z][a-zA-Z0-9-]*`},

	{Name: "Ident", Pattern: `[a-zA-Z][a-zA-Z0-9-]*`},

	{Name: "Number", Pattern: `[0-9]+`},
})

VersionLexer defines the lexical tokens for version strings. Token order matters - more specific patterns must come before general ones.

The lexer uses several token types:

  • Number: pure digits (for version components)
  • Prefix: v or V (for version prefix)
  • Ident: alphanumeric with optional dashes (for pre-release/metadata)
  • Mixed: digit-starting alphanumeric (like "5114f85")
  • Dashes: two or more dashes (valid SemVer identifier like "--")

Per SemVer 2.0.0, identifiers can be purely dashes (e.g., "1.0.0-x-y-z.--")

Functions

func EBNF

func EBNF() string

EBNF returns the EBNF grammar string from the parser.

Types

type BuildMetadata

type BuildMetadata struct {
	Identifiers []*Identifier `parser:"Plus @@ ( Dot @@ )*"`
}

BuildMetadata represents the build metadata portion of a version. Grammar: build-metadata = "+", identifier, { ".", identifier } ;

type Builder

type Builder struct {
	// contains filtered or unexported fields
}

Builder provides a fluent API for constructing and mutating versions. It can be seeded from a parsed Version or created from scratch.

Example usage:

// From scratch
v, err := NewBuilder().
    Major(1).
    Minor(2).
    Patch(3).
    PreRelease("alpha.1").
    Build()

// From existing version
parsed, _ := Parse("v1.2.3-alpha")
v, err := FromVersion(parsed).
    IncrementMinor().
    PreRelease("beta.1").
    Build()

func FromString

func FromString(s string) *Builder

FromString parses a version string and creates a builder from it. If parsing fails, Build() will return the parse error.

func FromVersion

func FromVersion(v *Version) *Builder

FromVersion creates a builder seeded with values from an existing Version. The builder is a copy - modifications don't affect the original.

func NewBuilder

func NewBuilder() *Builder

NewBuilder creates a new version builder starting at 0.0.0.

func (*Builder) Alpha

func (b *Builder) Alpha(n ...int) *Builder

Alpha sets pre-release to "alpha" or "alpha.N".

func (*Builder) Beta

func (b *Builder) Beta(n ...int) *Builder

Beta sets pre-release to "beta" or "beta.N".

func (*Builder) Build

func (b *Builder) Build() (*Version, error)

Build constructs the version string, parses it back through the grammar, and validates the result. This round-trip ensures the built version is always grammatically correct and parseable.

Returns an error if:

  • Any setter recorded an error (e.g., negative version number)
  • The constructed string fails to parse (grammar violation)
  • The parsed version fails validation (e.g., leading zeros)

func (*Builder) BuildMetadata

func (b *Builder) BuildMetadata(m string) *Builder

BuildMetadata sets the build metadata (e.g., "build.123", "sha.abc123"). Pass empty string to clear the metadata.

func (*Builder) ClearBuildMetadata

func (b *Builder) ClearBuildMetadata() *Builder

ClearBuildMetadata is an alias for ClearMetadata.

func (*Builder) ClearMetadata

func (b *Builder) ClearMetadata() *Builder

ClearMetadata removes the build metadata.

func (*Builder) ClearPreRelease

func (b *Builder) ClearPreRelease() *Builder

ClearPreRelease removes the pre-release identifier.

func (*Builder) ClearRevision

func (b *Builder) ClearRevision() *Builder

ClearRevision removes the revision component, making this a 3-component version.

func (*Builder) CoreString

func (b *Builder) CoreString() string

CoreString returns just Major.Minor.Patch without prefix, pre-release, or metadata.

func (*Builder) DecrementMajor

func (b *Builder) DecrementMajor() *Builder

DecrementMajor decrements major, resets minor, patch, and revision. Sets error if major would go below 0.

func (*Builder) DecrementMinor

func (b *Builder) DecrementMinor() *Builder

DecrementMinor decrements minor, resets patch and revision. Sets error if minor would go below 0.

func (*Builder) DecrementPatch

func (b *Builder) DecrementPatch() *Builder

DecrementPatch decrements patch, resets revision. Sets error if patch would go below 0.

func (*Builder) Dev

func (b *Builder) Dev(n ...int) *Builder

Dev sets pre-release to "dev" or "dev.N".

func (*Builder) Error

func (b *Builder) Error() error

Error returns the first error encountered, or nil.

func (*Builder) GetBuildMetadata

func (b *Builder) GetBuildMetadata() string

GetBuildMetadata returns the current build metadata.

func (*Builder) GetMajor

func (b *Builder) GetMajor() int

GetMajor returns the current major version.

func (*Builder) GetMinor

func (b *Builder) GetMinor() int

GetMinor returns the current minor version.

func (*Builder) GetPatch

func (b *Builder) GetPatch() int

GetPatch returns the current patch version.

func (*Builder) GetPreRelease

func (b *Builder) GetPreRelease() string

GetPreRelease returns the current pre-release string.

func (*Builder) GetPrefix

func (b *Builder) GetPrefix() string

GetPrefix returns the current prefix.

func (*Builder) GetRevision

func (b *Builder) GetRevision() *int

GetRevision returns the current revision (nil if not set).

func (*Builder) HasError

func (b *Builder) HasError() bool

HasError returns true if any operation recorded an error.

func (*Builder) IncrementMajor

func (b *Builder) IncrementMajor() *Builder

IncrementMajor increments major, resets minor, patch, and revision to 0, clears pre-release.

func (*Builder) IncrementMinor

func (b *Builder) IncrementMinor() *Builder

IncrementMinor increments minor, resets patch and revision, clears pre-release.

func (*Builder) IncrementPatch

func (b *Builder) IncrementPatch() *Builder

IncrementPatch increments patch, resets revision, clears pre-release.

func (*Builder) Major

func (b *Builder) Major(n int) *Builder

Major sets the major version number.

func (*Builder) Metadata

func (b *Builder) Metadata(m string) *Builder

Metadata is an alias for BuildMetadata.

func (*Builder) Minor

func (b *Builder) Minor(n int) *Builder

Minor sets the minor version number.

func (*Builder) MustBuild

func (b *Builder) MustBuild() *Version

MustBuild calls Build and panics on error. Use only when you're certain the version is valid.

func (*Builder) NoPrefix

func (b *Builder) NoPrefix() *Builder

NoPrefix removes the version prefix.

func (*Builder) Patch

func (b *Builder) Patch(n int) *Builder

Patch sets the patch version number.

func (*Builder) PreRelease

func (b *Builder) PreRelease(pr string) *Builder

PreRelease sets the pre-release identifier (e.g., "alpha.1", "beta", "rc.2"). Pass empty string to clear the pre-release.

func (*Builder) Prefix

func (b *Builder) Prefix(p string) *Builder

Prefix sets the version prefix (e.g., "v", "V").

func (*Builder) RC

func (b *Builder) RC(n int) *Builder

RC sets pre-release to "rc.N".

func (*Builder) Release

func (b *Builder) Release() *Builder

Release clears pre-release and metadata, producing a clean release version.

func (*Builder) Revision

func (b *Builder) Revision(n int) *Builder

Revision sets the revision number (4th component for assembly versions). Use nil or call ClearRevision() to remove the revision component.

func (*Builder) Snapshot

func (b *Builder) Snapshot() *Builder

Snapshot sets pre-release to "SNAPSHOT" (common in Java/Maven).

func (*Builder) String

func (b *Builder) String() string

String returns the version string without building/validating. Useful for debugging or when you just need the string representation.

func (*Builder) WithBuildMetadata

func (b *Builder) WithBuildMetadata(m string) *Builder

WithBuildMetadata is an alias for BuildMetadata.

func (*Builder) WithPreRelease

func (b *Builder) WithPreRelease(pr string) *Builder

WithPreRelease is an alias for PreRelease.

func (*Builder) WithPrefix

func (b *Builder) WithPrefix(p string) *Builder

WithPrefix is an alias for Prefix.

type Identifier

type Identifier struct {
	Number *string `parser:"  @Number"`
	Ident  *string `parser:"| @Ident"`
	Mixed  *string `parser:"| @Mixed"`
	Dashes *string `parser:"| @Dashes"`
}

Identifier represents a single pre-release or build metadata identifier. Can be numeric, alphanumeric, mixed (like "5114f85"), or dashes only (like "--").

func (*Identifier) IsNumeric

func (id *Identifier) IsNumeric() bool

IsNumeric returns true if the identifier is purely numeric.

func (*Identifier) String

func (id *Identifier) String() string

String returns the identifier value as a string.

type PreRelease

type PreRelease struct {
	Identifiers []*Identifier `parser:"Dash @@ ( Dot @@ )*"`
}

PreRelease represents the pre-release portion of a version. Grammar: pre-release = "-", identifier, { ".", identifier } ; Identifiers can be pure numbers, pure letters, or mixed alphanumeric.

type Version

type Version struct {
	Prefix        string         `parser:"@Prefix?"`
	Core          *VersionCore   `parser:"@@"`
	PreRelease    *PreRelease    `parser:"@@?"`
	BuildMetadata *BuildMetadata `parser:"@@?"`
	Raw           string         // Original input string (set after parsing)
}

Version represents a parsed version string with all components. Grammar: version = [ prefix ], version-core ;

func FromVersionData

func FromVersionData(prefix string, major, minor, patch int, revision *int, preRelease, buildMetadata string) *Version

FromVersionData creates a parser.Version from version data components. This is used when constructing versions programmatically.

func Parse

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

Parse parses a version string and returns the parsed Version. Returns an error if the string is not a valid version. Only v/V prefixes are supported per SemVer convention.

func ParseLenient

func ParseLenient(input string) *Version

ParseLenient parses a version string, returning a best-effort Version. Unlike Parse, it does not return an error for minor validation issues. Use this for reading existing VERSION files that may have legacy formats.

func (*Version) AssemblyVersion

func (v *Version) AssemblyVersion() string

AssemblyVersion returns a 4-component assembly version. Format: Major.Minor.Patch.Revision (Revision defaults to 0)

func (*Version) BuildMetadataString

func (v *Version) BuildMetadataString() string

BuildMetadataString returns the build metadata as a string.

func (*Version) Clone

func (v *Version) Clone() *Version

Clone creates a deep copy of the Version.

func (*Version) CoreVersion

func (v *Version) CoreVersion() string

CoreVersion returns just Major.Minor.Patch[.Revision] without pre-release or metadata.

func (*Version) FullString

func (v *Version) FullString() string

FullString returns the version with prefix. Format: [Prefix]Major.Minor.Patch[-PreRelease][+BuildMetadata]

func (*Version) HasBuildMetadata

func (v *Version) HasBuildMetadata() bool

HasBuildMetadata returns true if the version has build metadata.

func (*Version) HasPrefix

func (v *Version) HasPrefix() bool

HasPrefix returns true if the version has a prefix (e.g., "v").

func (*Version) IncrementMajor

func (v *Version) IncrementMajor()

IncrementMajor increments the major version, resets minor, patch, and revision.

func (*Version) IncrementMinor

func (v *Version) IncrementMinor()

IncrementMinor increments the minor version, resets patch and revision.

func (*Version) IncrementPatch

func (v *Version) IncrementPatch()

IncrementPatch increments the patch version, resets revision.

func (*Version) IsAssemblyVersion

func (v *Version) IsAssemblyVersion() bool

IsAssemblyVersion returns true if this is a 4-component assembly version.

func (*Version) IsPartial

func (v *Version) IsPartial() bool

IsPartial returns true if the version is missing minor or patch components.

func (*Version) IsPreRelease

func (v *Version) IsPreRelease() bool

IsPreRelease returns true if the version has a pre-release tag.

func (*Version) Major

func (v *Version) Major() int

Major returns the major version number.

func (*Version) Minor

func (v *Version) Minor() int

Minor returns the minor version number (0 if not specified).

func (*Version) Patch

func (v *Version) Patch() int

Patch returns the patch version number (0 if not specified).

func (*Version) PreReleaseString

func (v *Version) PreReleaseString() string

PreReleaseString returns the pre-release portion as a string.

func (*Version) Revision

func (v *Version) Revision() int

Revision returns the revision number for assembly versions (0 if not specified).

func (*Version) SetBuildMetadata

func (v *Version) SetBuildMetadata(metadata string)

SetBuildMetadata updates the build metadata.

func (*Version) SetMajor

func (v *Version) SetMajor(major int)

SetMajor updates the major version and resets minor, patch, and pre-release.

func (*Version) SetMinor

func (v *Version) SetMinor(minor int)

SetMinor updates the minor version and resets patch and pre-release.

func (*Version) SetPatch

func (v *Version) SetPatch(patch int)

SetPatch updates the patch version and clears pre-release.

func (*Version) SetPreRelease

func (v *Version) SetPreRelease(preRelease string)

SetPreRelease updates the pre-release identifier.

func (*Version) SetPrefix

func (v *Version) SetPrefix(prefix string)

SetPrefix updates the version prefix.

func (*Version) String

func (v *Version) String() string

String returns the version string without prefix. Format: Major.Minor.Patch[.Revision][-PreRelease][+BuildMetadata]

func (*Version) ToVersionData

func (v *Version) ToVersionData() (prefix string, major, minor, patch int, revision *int, preRelease, buildMetadata, raw string)

ToVersionData converts a parser.Version to the data needed for the version package. Returns: prefix, major, minor, patch, revision, preRelease, buildMetadata, raw

func (*Version) Validate

func (v *Version) Validate() error

Validate checks if the parsed version is valid according to SemVer 2.0.0.

type VersionCore

type VersionCore struct {
	Major    int  `parser:"@Number"`
	Minor    *int `parser:"( Dot @Number"`
	Patch    *int `parser:"  ( Dot @Number"`
	Revision *int `parser:"    ( Dot @Number )? )? )?"`
}

VersionCore represents the numeric parts of a version. Grammar: version-core = major [ "." minor [ "." patch [ "." revision ] ] ] ;

type VersionFile

type VersionFile struct {
	Version *Version `parser:"@@"`
}

VersionFile represents the content of a VERSION file. Grammar: version-file = version, [ newline ] ;

Jump to

Keyboard shortcuts

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