semver.go 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  1. // Copyright 2013-2015 CoreOS, Inc.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. // Semantic Versions http://semver.org
  15. package semver
  16. import (
  17. "bytes"
  18. "errors"
  19. "fmt"
  20. "regexp"
  21. "strconv"
  22. "strings"
  23. )
  24. type Version struct {
  25. Major int64
  26. Minor int64
  27. Patch int64
  28. PreRelease PreRelease
  29. Metadata string
  30. }
  31. type PreRelease string
  32. func splitOff(input *string, delim string) (val string) {
  33. parts := strings.SplitN(*input, delim, 2)
  34. if len(parts) == 2 {
  35. *input = parts[0]
  36. val = parts[1]
  37. }
  38. return val
  39. }
  40. func New(version string) *Version {
  41. return Must(NewVersion(version))
  42. }
  43. func NewVersion(version string) (*Version, error) {
  44. v := Version{}
  45. if err := v.Set(version); err != nil {
  46. return nil, err
  47. }
  48. return &v, nil
  49. }
  50. // Must is a helper for wrapping NewVersion and will panic if err is not nil.
  51. func Must(v *Version, err error) *Version {
  52. if err != nil {
  53. panic(err)
  54. }
  55. return v
  56. }
  57. // Set parses and updates v from the given version string. Implements flag.Value
  58. func (v *Version) Set(version string) error {
  59. metadata := splitOff(&version, "+")
  60. preRelease := PreRelease(splitOff(&version, "-"))
  61. dotParts := strings.SplitN(version, ".", 3)
  62. if len(dotParts) != 3 {
  63. return fmt.Errorf("%s is not in dotted-tri format", version)
  64. }
  65. if err := validateIdentifier(string(preRelease)); err != nil {
  66. return fmt.Errorf("failed to validate pre-release: %v", err)
  67. }
  68. if err := validateIdentifier(metadata); err != nil {
  69. return fmt.Errorf("failed to validate metadata: %v", err)
  70. }
  71. parsed := make([]int64, 3, 3)
  72. for i, v := range dotParts[:3] {
  73. val, err := strconv.ParseInt(v, 10, 64)
  74. parsed[i] = val
  75. if err != nil {
  76. return err
  77. }
  78. }
  79. v.Metadata = metadata
  80. v.PreRelease = preRelease
  81. v.Major = parsed[0]
  82. v.Minor = parsed[1]
  83. v.Patch = parsed[2]
  84. return nil
  85. }
  86. func (v Version) String() string {
  87. var buffer bytes.Buffer
  88. fmt.Fprintf(&buffer, "%d.%d.%d", v.Major, v.Minor, v.Patch)
  89. if v.PreRelease != "" {
  90. fmt.Fprintf(&buffer, "-%s", v.PreRelease)
  91. }
  92. if v.Metadata != "" {
  93. fmt.Fprintf(&buffer, "+%s", v.Metadata)
  94. }
  95. return buffer.String()
  96. }
  97. func (v *Version) UnmarshalYAML(unmarshal func(interface{}) error) error {
  98. var data string
  99. if err := unmarshal(&data); err != nil {
  100. return err
  101. }
  102. return v.Set(data)
  103. }
  104. func (v Version) MarshalJSON() ([]byte, error) {
  105. return []byte(`"` + v.String() + `"`), nil
  106. }
  107. func (v *Version) UnmarshalJSON(data []byte) error {
  108. l := len(data)
  109. if l == 0 || string(data) == `""` {
  110. return nil
  111. }
  112. if l < 2 || data[0] != '"' || data[l-1] != '"' {
  113. return errors.New("invalid semver string")
  114. }
  115. return v.Set(string(data[1 : l-1]))
  116. }
  117. // Compare tests if v is less than, equal to, or greater than versionB,
  118. // returning -1, 0, or +1 respectively.
  119. func (v Version) Compare(versionB Version) int {
  120. if cmp := recursiveCompare(v.Slice(), versionB.Slice()); cmp != 0 {
  121. return cmp
  122. }
  123. return preReleaseCompare(v, versionB)
  124. }
  125. // Equal tests if v is equal to versionB.
  126. func (v Version) Equal(versionB Version) bool {
  127. return v.Compare(versionB) == 0
  128. }
  129. // LessThan tests if v is less than versionB.
  130. func (v Version) LessThan(versionB Version) bool {
  131. return v.Compare(versionB) < 0
  132. }
  133. // Slice converts the comparable parts of the semver into a slice of integers.
  134. func (v Version) Slice() []int64 {
  135. return []int64{v.Major, v.Minor, v.Patch}
  136. }
  137. func (p PreRelease) Slice() []string {
  138. preRelease := string(p)
  139. return strings.Split(preRelease, ".")
  140. }
  141. func preReleaseCompare(versionA Version, versionB Version) int {
  142. a := versionA.PreRelease
  143. b := versionB.PreRelease
  144. /* Handle the case where if two versions are otherwise equal it is the
  145. * one without a PreRelease that is greater */
  146. if len(a) == 0 && (len(b) > 0) {
  147. return 1
  148. } else if len(b) == 0 && (len(a) > 0) {
  149. return -1
  150. }
  151. // If there is a prerelease, check and compare each part.
  152. return recursivePreReleaseCompare(a.Slice(), b.Slice())
  153. }
  154. func recursiveCompare(versionA []int64, versionB []int64) int {
  155. if len(versionA) == 0 {
  156. return 0
  157. }
  158. a := versionA[0]
  159. b := versionB[0]
  160. if a > b {
  161. return 1
  162. } else if a < b {
  163. return -1
  164. }
  165. return recursiveCompare(versionA[1:], versionB[1:])
  166. }
  167. func recursivePreReleaseCompare(versionA []string, versionB []string) int {
  168. // A larger set of pre-release fields has a higher precedence than a smaller set,
  169. // if all of the preceding identifiers are equal.
  170. if len(versionA) == 0 {
  171. if len(versionB) > 0 {
  172. return -1
  173. }
  174. return 0
  175. } else if len(versionB) == 0 {
  176. // We're longer than versionB so return 1.
  177. return 1
  178. }
  179. a := versionA[0]
  180. b := versionB[0]
  181. aInt := false
  182. bInt := false
  183. aI, err := strconv.Atoi(versionA[0])
  184. if err == nil {
  185. aInt = true
  186. }
  187. bI, err := strconv.Atoi(versionB[0])
  188. if err == nil {
  189. bInt = true
  190. }
  191. // Numeric identifiers always have lower precedence than non-numeric identifiers.
  192. if aInt && !bInt {
  193. return -1
  194. } else if !aInt && bInt {
  195. return 1
  196. }
  197. // Handle Integer Comparison
  198. if aInt && bInt {
  199. if aI > bI {
  200. return 1
  201. } else if aI < bI {
  202. return -1
  203. }
  204. }
  205. // Handle String Comparison
  206. if a > b {
  207. return 1
  208. } else if a < b {
  209. return -1
  210. }
  211. return recursivePreReleaseCompare(versionA[1:], versionB[1:])
  212. }
  213. // BumpMajor increments the Major field by 1 and resets all other fields to their default values
  214. func (v *Version) BumpMajor() {
  215. v.Major += 1
  216. v.Minor = 0
  217. v.Patch = 0
  218. v.PreRelease = PreRelease("")
  219. v.Metadata = ""
  220. }
  221. // BumpMinor increments the Minor field by 1 and resets all other fields to their default values
  222. func (v *Version) BumpMinor() {
  223. v.Minor += 1
  224. v.Patch = 0
  225. v.PreRelease = PreRelease("")
  226. v.Metadata = ""
  227. }
  228. // BumpPatch increments the Patch field by 1 and resets all other fields to their default values
  229. func (v *Version) BumpPatch() {
  230. v.Patch += 1
  231. v.PreRelease = PreRelease("")
  232. v.Metadata = ""
  233. }
  234. // validateIdentifier makes sure the provided identifier satisfies semver spec
  235. func validateIdentifier(id string) error {
  236. if id != "" && !reIdentifier.MatchString(id) {
  237. return fmt.Errorf("%s is not a valid semver identifier", id)
  238. }
  239. return nil
  240. }
  241. // reIdentifier is a regular expression used to check that pre-release and metadata
  242. // identifiers satisfy the spec requirements
  243. var reIdentifier = regexp.MustCompile(`^[0-9A-Za-z-]+(\.[0-9A-Za-z-]+)*$`)