version.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425
  1. package semver
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "regexp"
  8. "strconv"
  9. "strings"
  10. )
  11. // The compiled version of the regex created at init() is cached here so it
  12. // only needs to be created once.
  13. var versionRegex *regexp.Regexp
  14. var validPrereleaseRegex *regexp.Regexp
  15. var (
  16. // ErrInvalidSemVer is returned a version is found to be invalid when
  17. // being parsed.
  18. ErrInvalidSemVer = errors.New("Invalid Semantic Version")
  19. // ErrInvalidMetadata is returned when the metadata is an invalid format
  20. ErrInvalidMetadata = errors.New("Invalid Metadata string")
  21. // ErrInvalidPrerelease is returned when the pre-release is an invalid format
  22. ErrInvalidPrerelease = errors.New("Invalid Prerelease string")
  23. )
  24. // SemVerRegex is the regular expression used to parse a semantic version.
  25. const SemVerRegex string = `v?([0-9]+)(\.[0-9]+)?(\.[0-9]+)?` +
  26. `(-([0-9A-Za-z\-]+(\.[0-9A-Za-z\-]+)*))?` +
  27. `(\+([0-9A-Za-z\-]+(\.[0-9A-Za-z\-]+)*))?`
  28. // ValidPrerelease is the regular expression which validates
  29. // both prerelease and metadata values.
  30. const ValidPrerelease string = `^([0-9A-Za-z\-]+(\.[0-9A-Za-z\-]+)*)$`
  31. // Version represents a single semantic version.
  32. type Version struct {
  33. major, minor, patch int64
  34. pre string
  35. metadata string
  36. original string
  37. }
  38. func init() {
  39. versionRegex = regexp.MustCompile("^" + SemVerRegex + "$")
  40. validPrereleaseRegex = regexp.MustCompile(ValidPrerelease)
  41. }
  42. // NewVersion parses a given version and returns an instance of Version or
  43. // an error if unable to parse the version.
  44. func NewVersion(v string) (*Version, error) {
  45. m := versionRegex.FindStringSubmatch(v)
  46. if m == nil {
  47. return nil, ErrInvalidSemVer
  48. }
  49. sv := &Version{
  50. metadata: m[8],
  51. pre: m[5],
  52. original: v,
  53. }
  54. var temp int64
  55. temp, err := strconv.ParseInt(m[1], 10, 64)
  56. if err != nil {
  57. return nil, fmt.Errorf("Error parsing version segment: %s", err)
  58. }
  59. sv.major = temp
  60. if m[2] != "" {
  61. temp, err = strconv.ParseInt(strings.TrimPrefix(m[2], "."), 10, 64)
  62. if err != nil {
  63. return nil, fmt.Errorf("Error parsing version segment: %s", err)
  64. }
  65. sv.minor = temp
  66. } else {
  67. sv.minor = 0
  68. }
  69. if m[3] != "" {
  70. temp, err = strconv.ParseInt(strings.TrimPrefix(m[3], "."), 10, 64)
  71. if err != nil {
  72. return nil, fmt.Errorf("Error parsing version segment: %s", err)
  73. }
  74. sv.patch = temp
  75. } else {
  76. sv.patch = 0
  77. }
  78. return sv, nil
  79. }
  80. // MustParse parses a given version and panics on error.
  81. func MustParse(v string) *Version {
  82. sv, err := NewVersion(v)
  83. if err != nil {
  84. panic(err)
  85. }
  86. return sv
  87. }
  88. // String converts a Version object to a string.
  89. // Note, if the original version contained a leading v this version will not.
  90. // See the Original() method to retrieve the original value. Semantic Versions
  91. // don't contain a leading v per the spec. Instead it's optional on
  92. // implementation.
  93. func (v *Version) String() string {
  94. var buf bytes.Buffer
  95. fmt.Fprintf(&buf, "%d.%d.%d", v.major, v.minor, v.patch)
  96. if v.pre != "" {
  97. fmt.Fprintf(&buf, "-%s", v.pre)
  98. }
  99. if v.metadata != "" {
  100. fmt.Fprintf(&buf, "+%s", v.metadata)
  101. }
  102. return buf.String()
  103. }
  104. // Original returns the original value passed in to be parsed.
  105. func (v *Version) Original() string {
  106. return v.original
  107. }
  108. // Major returns the major version.
  109. func (v *Version) Major() int64 {
  110. return v.major
  111. }
  112. // Minor returns the minor version.
  113. func (v *Version) Minor() int64 {
  114. return v.minor
  115. }
  116. // Patch returns the patch version.
  117. func (v *Version) Patch() int64 {
  118. return v.patch
  119. }
  120. // Prerelease returns the pre-release version.
  121. func (v *Version) Prerelease() string {
  122. return v.pre
  123. }
  124. // Metadata returns the metadata on the version.
  125. func (v *Version) Metadata() string {
  126. return v.metadata
  127. }
  128. // originalVPrefix returns the original 'v' prefix if any.
  129. func (v *Version) originalVPrefix() string {
  130. // Note, only lowercase v is supported as a prefix by the parser.
  131. if v.original != "" && v.original[:1] == "v" {
  132. return v.original[:1]
  133. }
  134. return ""
  135. }
  136. // IncPatch produces the next patch version.
  137. // If the current version does not have prerelease/metadata information,
  138. // it unsets metadata and prerelease values, increments patch number.
  139. // If the current version has any of prerelease or metadata information,
  140. // it unsets both values and keeps curent patch value
  141. func (v Version) IncPatch() Version {
  142. vNext := v
  143. // according to http://semver.org/#spec-item-9
  144. // Pre-release versions have a lower precedence than the associated normal version.
  145. // according to http://semver.org/#spec-item-10
  146. // Build metadata SHOULD be ignored when determining version precedence.
  147. if v.pre != "" {
  148. vNext.metadata = ""
  149. vNext.pre = ""
  150. } else {
  151. vNext.metadata = ""
  152. vNext.pre = ""
  153. vNext.patch = v.patch + 1
  154. }
  155. vNext.original = v.originalVPrefix() + "" + vNext.String()
  156. return vNext
  157. }
  158. // IncMinor produces the next minor version.
  159. // Sets patch to 0.
  160. // Increments minor number.
  161. // Unsets metadata.
  162. // Unsets prerelease status.
  163. func (v Version) IncMinor() Version {
  164. vNext := v
  165. vNext.metadata = ""
  166. vNext.pre = ""
  167. vNext.patch = 0
  168. vNext.minor = v.minor + 1
  169. vNext.original = v.originalVPrefix() + "" + vNext.String()
  170. return vNext
  171. }
  172. // IncMajor produces the next major version.
  173. // Sets patch to 0.
  174. // Sets minor to 0.
  175. // Increments major number.
  176. // Unsets metadata.
  177. // Unsets prerelease status.
  178. func (v Version) IncMajor() Version {
  179. vNext := v
  180. vNext.metadata = ""
  181. vNext.pre = ""
  182. vNext.patch = 0
  183. vNext.minor = 0
  184. vNext.major = v.major + 1
  185. vNext.original = v.originalVPrefix() + "" + vNext.String()
  186. return vNext
  187. }
  188. // SetPrerelease defines the prerelease value.
  189. // Value must not include the required 'hypen' prefix.
  190. func (v Version) SetPrerelease(prerelease string) (Version, error) {
  191. vNext := v
  192. if len(prerelease) > 0 && !validPrereleaseRegex.MatchString(prerelease) {
  193. return vNext, ErrInvalidPrerelease
  194. }
  195. vNext.pre = prerelease
  196. vNext.original = v.originalVPrefix() + "" + vNext.String()
  197. return vNext, nil
  198. }
  199. // SetMetadata defines metadata value.
  200. // Value must not include the required 'plus' prefix.
  201. func (v Version) SetMetadata(metadata string) (Version, error) {
  202. vNext := v
  203. if len(metadata) > 0 && !validPrereleaseRegex.MatchString(metadata) {
  204. return vNext, ErrInvalidMetadata
  205. }
  206. vNext.metadata = metadata
  207. vNext.original = v.originalVPrefix() + "" + vNext.String()
  208. return vNext, nil
  209. }
  210. // LessThan tests if one version is less than another one.
  211. func (v *Version) LessThan(o *Version) bool {
  212. return v.Compare(o) < 0
  213. }
  214. // GreaterThan tests if one version is greater than another one.
  215. func (v *Version) GreaterThan(o *Version) bool {
  216. return v.Compare(o) > 0
  217. }
  218. // Equal tests if two versions are equal to each other.
  219. // Note, versions can be equal with different metadata since metadata
  220. // is not considered part of the comparable version.
  221. func (v *Version) Equal(o *Version) bool {
  222. return v.Compare(o) == 0
  223. }
  224. // Compare compares this version to another one. It returns -1, 0, or 1 if
  225. // the version smaller, equal, or larger than the other version.
  226. //
  227. // Versions are compared by X.Y.Z. Build metadata is ignored. Prerelease is
  228. // lower than the version without a prerelease.
  229. func (v *Version) Compare(o *Version) int {
  230. // Compare the major, minor, and patch version for differences. If a
  231. // difference is found return the comparison.
  232. if d := compareSegment(v.Major(), o.Major()); d != 0 {
  233. return d
  234. }
  235. if d := compareSegment(v.Minor(), o.Minor()); d != 0 {
  236. return d
  237. }
  238. if d := compareSegment(v.Patch(), o.Patch()); d != 0 {
  239. return d
  240. }
  241. // At this point the major, minor, and patch versions are the same.
  242. ps := v.pre
  243. po := o.Prerelease()
  244. if ps == "" && po == "" {
  245. return 0
  246. }
  247. if ps == "" {
  248. return 1
  249. }
  250. if po == "" {
  251. return -1
  252. }
  253. return comparePrerelease(ps, po)
  254. }
  255. // UnmarshalJSON implements JSON.Unmarshaler interface.
  256. func (v *Version) UnmarshalJSON(b []byte) error {
  257. var s string
  258. if err := json.Unmarshal(b, &s); err != nil {
  259. return err
  260. }
  261. temp, err := NewVersion(s)
  262. if err != nil {
  263. return err
  264. }
  265. v.major = temp.major
  266. v.minor = temp.minor
  267. v.patch = temp.patch
  268. v.pre = temp.pre
  269. v.metadata = temp.metadata
  270. v.original = temp.original
  271. temp = nil
  272. return nil
  273. }
  274. // MarshalJSON implements JSON.Marshaler interface.
  275. func (v *Version) MarshalJSON() ([]byte, error) {
  276. return json.Marshal(v.String())
  277. }
  278. func compareSegment(v, o int64) int {
  279. if v < o {
  280. return -1
  281. }
  282. if v > o {
  283. return 1
  284. }
  285. return 0
  286. }
  287. func comparePrerelease(v, o string) int {
  288. // split the prelease versions by their part. The separator, per the spec,
  289. // is a .
  290. sparts := strings.Split(v, ".")
  291. oparts := strings.Split(o, ".")
  292. // Find the longer length of the parts to know how many loop iterations to
  293. // go through.
  294. slen := len(sparts)
  295. olen := len(oparts)
  296. l := slen
  297. if olen > slen {
  298. l = olen
  299. }
  300. // Iterate over each part of the prereleases to compare the differences.
  301. for i := 0; i < l; i++ {
  302. // Since the lentgh of the parts can be different we need to create
  303. // a placeholder. This is to avoid out of bounds issues.
  304. stemp := ""
  305. if i < slen {
  306. stemp = sparts[i]
  307. }
  308. otemp := ""
  309. if i < olen {
  310. otemp = oparts[i]
  311. }
  312. d := comparePrePart(stemp, otemp)
  313. if d != 0 {
  314. return d
  315. }
  316. }
  317. // Reaching here means two versions are of equal value but have different
  318. // metadata (the part following a +). They are not identical in string form
  319. // but the version comparison finds them to be equal.
  320. return 0
  321. }
  322. func comparePrePart(s, o string) int {
  323. // Fastpath if they are equal
  324. if s == o {
  325. return 0
  326. }
  327. // When s or o are empty we can use the other in an attempt to determine
  328. // the response.
  329. if s == "" {
  330. if o != "" {
  331. return -1
  332. }
  333. return 1
  334. }
  335. if o == "" {
  336. if s != "" {
  337. return 1
  338. }
  339. return -1
  340. }
  341. // When comparing strings "99" is greater than "103". To handle
  342. // cases like this we need to detect numbers and compare them. According
  343. // to the semver spec, numbers are always positive. If there is a - at the
  344. // start like -99 this is to be evaluated as an alphanum. numbers always
  345. // have precedence over alphanum. Parsing as Uints because negative numbers
  346. // are ignored.
  347. oi, n1 := strconv.ParseUint(o, 10, 64)
  348. si, n2 := strconv.ParseUint(s, 10, 64)
  349. // The case where both are strings compare the strings
  350. if n1 != nil && n2 != nil {
  351. if s > o {
  352. return 1
  353. }
  354. return -1
  355. } else if n1 != nil {
  356. // o is a string and s is a number
  357. return -1
  358. } else if n2 != nil {
  359. // s is a string and o is a number
  360. return 1
  361. }
  362. // Both are numbers
  363. if si > oi {
  364. return 1
  365. }
  366. return -1
  367. }