Module: Philiprehberger::Semver::Parser

Defined in:
lib/philiprehberger/semver/parser.rb

Overview

Parses SemVer 2.0.0 strings into Version objects.

Constant Summary collapse

PRE_RELEASE_PART =
'(?:-(?<pre>[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))'
BUILD_PART =
'(?:\+(?<build>[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))'
CORE_PART =
'(?<major>0|[1-9]\d*)\.(?<minor>0|[1-9]\d*)\.(?<patch>0|[1-9]\d*)'
SEMVER_REGEX =
/\A#{CORE_PART}#{PRE_RELEASE_PART}?#{BUILD_PART}?\z/
IDENTIFIER_REGEX =
/\A[0-9A-Za-z-]+\z/

Class Method Summary collapse

Class Method Details

.parse(string) ⇒ Version

Parse a SemVer 2.0.0 string into a Version.

Validates each dot-separated pre-release and build-metadata identifier per SemVer 2.0.0 (identifiers must be non-empty and match [0-9A-Za-z-]).

Parameters:

  • string (String)

    the version string to parse

Returns:

  • (Version)

    the parsed immutable version

Raises:

  • (Error)

    if the string is not a valid SemVer 2.0.0 version or contains a malformed pre-release / build-metadata identifier



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/philiprehberger/semver/parser.rb', line 23

def self.parse(string)
  match = SEMVER_REGEX.match(string.to_s.strip)
  raise Error, "invalid semver: #{string}" unless match

  validate_identifiers(match[:pre], 'pre-release')
  validate_identifiers(match[:build], 'build-metadata')

  Version.new(
    match[:major],
    match[:minor],
    match[:patch],
    pre_release: match[:pre],
    build_metadata: match[:build]
  )
end