github.com/aleksi/gonuts.io@v0.0.0-20130622121132-3b0f2d1999fb/gopath/src/gonuts.io/AlekSi/nut/version.go (about)

     1  package nut
     2  
     3  import (
     4  	"fmt"
     5  	"regexp"
     6  	"strconv"
     7  )
     8  
     9  // Current format for nut version.
    10  var VersionRegexp = regexp.MustCompile(`^(\d+).(\d+).(\d+)$`)
    11  
    12  // Describes nut version. See http://gonuts.io/-/doc/versioning for explanation of version specification.
    13  type Version struct {
    14  	Major int
    15  	Minor int
    16  	Patch int
    17  }
    18  
    19  // Parse and set version.
    20  func NewVersion(version string) (v *Version, err error) {
    21  	v = new(Version)
    22  	err = v.setVersion(version)
    23  	return
    24  }
    25  
    26  // Return version as string in current format.
    27  func (v Version) String() string {
    28  	res := fmt.Sprintf("%d.%d.%d", v.Major, v.Minor, v.Patch)
    29  	if !VersionRegexp.MatchString(res) { // sanity check
    30  		panic(fmt.Errorf("%s not matches %s", res, VersionRegexp))
    31  	}
    32  	return res
    33  }
    34  
    35  // Returns true if left < right, false otherwise.
    36  func (left *Version) Less(right *Version) bool {
    37  	if left.Major < right.Major {
    38  		return true
    39  	} else if left.Major > right.Major {
    40  		return false
    41  	}
    42  
    43  	if left.Minor < right.Minor {
    44  		return true
    45  	} else if left.Minor > right.Minor {
    46  		return false
    47  	}
    48  
    49  	if left.Patch < right.Patch {
    50  		return true
    51  	} else if left.Patch > right.Patch {
    52  		return false
    53  	}
    54  
    55  	// left == right => "left < right" is false
    56  	return false
    57  }
    58  
    59  // Marshal to JSON.
    60  func (v *Version) MarshalJSON() ([]byte, error) {
    61  	return []byte(fmt.Sprintf(`"%s"`, v)), nil
    62  }
    63  
    64  // Unmarshal from JSON.
    65  func (v *Version) UnmarshalJSON(b []byte) error {
    66  	return v.setVersion(string(b[1 : len(b)-1]))
    67  }
    68  
    69  func (v *Version) setVersion(version string) (err error) {
    70  	parsed := VersionRegexp.FindAllStringSubmatch(version, -1)
    71  	if (parsed == nil) || (len(parsed[0]) != 4) {
    72  		err = fmt.Errorf("Bad format for version %q. See http://gonuts.io/-/doc/versioning", version)
    73  		return
    74  	}
    75  
    76  	v.Major, _ = strconv.Atoi(parsed[0][1])
    77  	v.Minor, _ = strconv.Atoi(parsed[0][2])
    78  	v.Patch, _ = strconv.Atoi(parsed[0][3])
    79  	return
    80  }