├── .github ├── dependabot.yml └── workflows │ └── go.yml ├── DCO ├── LICENSE ├── NOTICE ├── README.md ├── code-of-conduct.md ├── example.go ├── go.mod ├── go.sum └── semver ├── semver.go ├── semver_test.go └── sort.go /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | # Maintained in https://github.com/coreos/repo-templates 2 | # Do not edit downstream. 3 | 4 | version: 2 5 | updates: 6 | - package-ecosystem: gomod 7 | directory: / 8 | schedule: 9 | interval: weekly 10 | open-pull-requests-limit: 10 11 | labels: 12 | - dependency 13 | -------------------------------------------------------------------------------- /.github/workflows/go.yml: -------------------------------------------------------------------------------- 1 | # Maintained in https://github.com/coreos/repo-templates 2 | # Do not edit downstream. 3 | 4 | name: Go 5 | on: 6 | push: 7 | branches: [main] 8 | pull_request: 9 | branches: [main] 10 | permissions: 11 | contents: read 12 | 13 | # don't waste job slots on superseded code 14 | concurrency: 15 | group: ${{ github.workflow }}-${{ github.ref }} 16 | cancel-in-progress: true 17 | 18 | jobs: 19 | test: 20 | name: Test 21 | strategy: 22 | matrix: 23 | go-version: [1.14.x, 1.15.x, 1.16.x, 1.17.x, 1.18.x, 1.19.x, 1.20.x] 24 | runs-on: ubuntu-latest 25 | steps: 26 | - name: Set up Go 1.x 27 | uses: actions/setup-go@v4 28 | with: 29 | go-version: ${{ matrix.go-version }} 30 | - name: Check out repository 31 | uses: actions/checkout@v3 32 | - name: Check modules 33 | run: go mod verify 34 | - name: Build 35 | run: go build 36 | - name: Test 37 | run: go test -v ./... 38 | - name: Run linter 39 | uses: golangci/golangci-lint-action@v3 40 | with: 41 | version: v1.52.2 42 | args: -E=gofmt --timeout=30m0s 43 | -------------------------------------------------------------------------------- /DCO: -------------------------------------------------------------------------------- 1 | Developer Certificate of Origin 2 | Version 1.1 3 | 4 | Copyright (C) 2004, 2006 The Linux Foundation and its contributors. 5 | 660 York Street, Suite 102, 6 | San Francisco, CA 94110 USA 7 | 8 | Everyone is permitted to copy and distribute verbatim copies of this 9 | license document, but changing it is not allowed. 10 | 11 | 12 | Developer's Certificate of Origin 1.1 13 | 14 | By making a contribution to this project, I certify that: 15 | 16 | (a) The contribution was created in whole or in part by me and I 17 | have the right to submit it under the open source license 18 | indicated in the file; or 19 | 20 | (b) The contribution is based upon previous work that, to the best 21 | of my knowledge, is covered under an appropriate open source 22 | license and I have the right under that license to submit that 23 | work with modifications, whether created in whole or in part 24 | by me, under the same open source license (unless I am 25 | permitted to submit under a different license), as indicated 26 | in the file; or 27 | 28 | (c) The contribution was provided directly to me by some other 29 | person who certified (a), (b) or (c) and I have not modified 30 | it. 31 | 32 | (d) I understand and agree that this project and the contribution 33 | are public and that a record of the contribution (including all 34 | personal information I submit with it, including my sign-off) is 35 | maintained indefinitely and may be redistributed consistent with 36 | this project or the open source license(s) involved. 37 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | -------------------------------------------------------------------------------- /NOTICE: -------------------------------------------------------------------------------- 1 | CoreOS Project 2 | Copyright 2018 CoreOS, Inc 3 | 4 | This product includes software developed at CoreOS, Inc. 5 | (http://www.coreos.com/). 6 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # go-semver - Semantic Versioning Library 2 | 3 | [![GoDoc](https://godoc.org/github.com/coreos/go-semver/semver?status.svg)](https://godoc.org/github.com/coreos/go-semver/semver) 4 | 5 | go-semver is a [semantic versioning][semver] library for Go. It lets you parse 6 | and compare two semantic version strings. 7 | 8 | [semver]: http://semver.org/ 9 | 10 | ## Usage 11 | 12 | ```go 13 | vA := semver.New("1.2.3") 14 | vB := semver.New("3.2.1") 15 | 16 | fmt.Printf("%s < %s == %t\n", vA, vB, vA.LessThan(*vB)) 17 | ``` 18 | 19 | ## Example Application 20 | 21 | ``` 22 | $ go run example.go 1.2.3 3.2.1 23 | 1.2.3 < 3.2.1 == true 24 | 25 | $ go run example.go 5.2.3 3.2.1 26 | 5.2.3 < 3.2.1 == false 27 | ``` 28 | -------------------------------------------------------------------------------- /code-of-conduct.md: -------------------------------------------------------------------------------- 1 | ## CoreOS Community Code of Conduct 2 | 3 | ### Contributor Code of Conduct 4 | 5 | As contributors and maintainers of this project, and in the interest of 6 | fostering an open and welcoming community, we pledge to respect all people who 7 | contribute through reporting issues, posting feature requests, updating 8 | documentation, submitting pull requests or patches, and other activities. 9 | 10 | We are committed to making participation in this project a harassment-free 11 | experience for everyone, regardless of level of experience, gender, gender 12 | identity and expression, sexual orientation, disability, personal appearance, 13 | body size, race, ethnicity, age, religion, or nationality. 14 | 15 | Examples of unacceptable behavior by participants include: 16 | 17 | * The use of sexualized language or imagery 18 | * Personal attacks 19 | * Trolling or insulting/derogatory comments 20 | * Public or private harassment 21 | * Publishing others' private information, such as physical or electronic addresses, without explicit permission 22 | * Other unethical or unprofessional conduct. 23 | 24 | Project maintainers have the right and responsibility to remove, edit, or 25 | reject comments, commits, code, wiki edits, issues, and other contributions 26 | that are not aligned to this Code of Conduct. By adopting this Code of Conduct, 27 | project maintainers commit themselves to fairly and consistently applying these 28 | principles to every aspect of managing this project. Project maintainers who do 29 | not follow or enforce the Code of Conduct may be permanently removed from the 30 | project team. 31 | 32 | This code of conduct applies both within project spaces and in public spaces 33 | when an individual is representing the project or its community. 34 | 35 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 36 | reported by contacting a project maintainer, Brandon Philips 37 | , and/or Rithu John . 38 | 39 | This Code of Conduct is adapted from the Contributor Covenant 40 | (http://contributor-covenant.org), version 1.2.0, available at 41 | http://contributor-covenant.org/version/1/2/0/ 42 | 43 | ### CoreOS Events Code of Conduct 44 | 45 | CoreOS events are working conferences intended for professional networking and 46 | collaboration in the CoreOS community. Attendees are expected to behave 47 | according to professional standards and in accordance with their employer’s 48 | policies on appropriate workplace behavior. 49 | 50 | While at CoreOS events or related social networking opportunities, attendees 51 | should not engage in discriminatory or offensive speech or actions including 52 | but not limited to gender, sexuality, race, age, disability, or religion. 53 | Speakers should be especially aware of these concerns. 54 | 55 | CoreOS does not condone any statements by speakers contrary to these standards. 56 | CoreOS reserves the right to deny entrance and/or eject from an event (without 57 | refund) any individual found to be engaging in discriminatory or offensive 58 | speech or actions. 59 | 60 | Please bring any concerns to the immediate attention of designated on-site 61 | staff, Brandon Philips , and/or Rithu John . 62 | -------------------------------------------------------------------------------- /example.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "github.com/coreos/go-semver/semver" 6 | "os" 7 | ) 8 | 9 | func main() { 10 | vA, err := semver.NewVersion(os.Args[1]) 11 | if err != nil { 12 | fmt.Println(err.Error()) 13 | } 14 | vB, err := semver.NewVersion(os.Args[2]) 15 | if err != nil { 16 | fmt.Println(err.Error()) 17 | } 18 | 19 | fmt.Printf("%s < %s == %t\n", vA, vB, vA.LessThan(*vB)) 20 | } 21 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/coreos/go-semver 2 | 3 | go 1.8 4 | 5 | require gopkg.in/yaml.v3 v3.0.1 6 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= 2 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= 3 | gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= 4 | gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= 5 | -------------------------------------------------------------------------------- /semver/semver.go: -------------------------------------------------------------------------------- 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 | 15 | // Semantic Versions http://semver.org 16 | package semver 17 | 18 | import ( 19 | "bytes" 20 | "errors" 21 | "fmt" 22 | "regexp" 23 | "strconv" 24 | "strings" 25 | ) 26 | 27 | type Version struct { 28 | Major int64 29 | Minor int64 30 | Patch int64 31 | PreRelease PreRelease 32 | Metadata string 33 | } 34 | 35 | type PreRelease string 36 | 37 | func splitOff(input *string, delim string) (val string) { 38 | parts := strings.SplitN(*input, delim, 2) 39 | 40 | if len(parts) == 2 { 41 | *input = parts[0] 42 | val = parts[1] 43 | } 44 | 45 | return val 46 | } 47 | 48 | func New(version string) *Version { 49 | return Must(NewVersion(version)) 50 | } 51 | 52 | func NewVersion(version string) (*Version, error) { 53 | v := Version{} 54 | 55 | if err := v.Set(version); err != nil { 56 | return nil, err 57 | } 58 | 59 | return &v, nil 60 | } 61 | 62 | // Must is a helper for wrapping NewVersion and will panic if err is not nil. 63 | func Must(v *Version, err error) *Version { 64 | if err != nil { 65 | panic(err) 66 | } 67 | return v 68 | } 69 | 70 | // Set parses and updates v from the given version string. Implements flag.Value 71 | func (v *Version) Set(version string) error { 72 | metadata := splitOff(&version, "+") 73 | preRelease := PreRelease(splitOff(&version, "-")) 74 | dotParts := strings.SplitN(version, ".", 3) 75 | 76 | if len(dotParts) != 3 { 77 | return fmt.Errorf("%s is not in dotted-tri format", version) 78 | } 79 | 80 | if err := validateIdentifier(string(preRelease)); err != nil { 81 | return fmt.Errorf("failed to validate pre-release: %v", err) 82 | } 83 | 84 | if err := validateIdentifier(metadata); err != nil { 85 | return fmt.Errorf("failed to validate metadata: %v", err) 86 | } 87 | 88 | parsed := make([]int64, 3) 89 | 90 | for i, v := range dotParts[:3] { 91 | val, err := strconv.ParseInt(v, 10, 64) 92 | parsed[i] = val 93 | if err != nil { 94 | return err 95 | } 96 | } 97 | 98 | v.Metadata = metadata 99 | v.PreRelease = preRelease 100 | v.Major = parsed[0] 101 | v.Minor = parsed[1] 102 | v.Patch = parsed[2] 103 | return nil 104 | } 105 | 106 | func (v Version) String() string { 107 | var buffer bytes.Buffer 108 | 109 | fmt.Fprintf(&buffer, "%d.%d.%d", v.Major, v.Minor, v.Patch) 110 | 111 | if v.PreRelease != "" { 112 | fmt.Fprintf(&buffer, "-%s", v.PreRelease) 113 | } 114 | 115 | if v.Metadata != "" { 116 | fmt.Fprintf(&buffer, "+%s", v.Metadata) 117 | } 118 | 119 | return buffer.String() 120 | } 121 | 122 | func (v *Version) UnmarshalYAML(unmarshal func(interface{}) error) error { 123 | var data string 124 | if err := unmarshal(&data); err != nil { 125 | return err 126 | } 127 | return v.Set(data) 128 | } 129 | 130 | func (v Version) MarshalJSON() ([]byte, error) { 131 | return []byte(`"` + v.String() + `"`), nil 132 | } 133 | 134 | func (v *Version) UnmarshalJSON(data []byte) error { 135 | l := len(data) 136 | if l == 0 || string(data) == `""` { 137 | return nil 138 | } 139 | if l < 2 || data[0] != '"' || data[l-1] != '"' { 140 | return errors.New("invalid semver string") 141 | } 142 | return v.Set(string(data[1 : l-1])) 143 | } 144 | 145 | // Compare tests if v is less than, equal to, or greater than versionB, 146 | // returning -1, 0, or +1 respectively. 147 | func (v Version) Compare(versionB Version) int { 148 | if cmp := recursiveCompare(v.Slice(), versionB.Slice()); cmp != 0 { 149 | return cmp 150 | } 151 | return preReleaseCompare(v, versionB) 152 | } 153 | 154 | // Equal tests if v is equal to versionB. 155 | func (v Version) Equal(versionB Version) bool { 156 | return v.Compare(versionB) == 0 157 | } 158 | 159 | // LessThan tests if v is less than versionB. 160 | func (v Version) LessThan(versionB Version) bool { 161 | return v.Compare(versionB) < 0 162 | } 163 | 164 | // Slice converts the comparable parts of the semver into a slice of integers. 165 | func (v Version) Slice() []int64 { 166 | return []int64{v.Major, v.Minor, v.Patch} 167 | } 168 | 169 | func (p PreRelease) Slice() []string { 170 | preRelease := string(p) 171 | return strings.Split(preRelease, ".") 172 | } 173 | 174 | func preReleaseCompare(versionA Version, versionB Version) int { 175 | a := versionA.PreRelease 176 | b := versionB.PreRelease 177 | 178 | /* Handle the case where if two versions are otherwise equal it is the 179 | * one without a PreRelease that is greater */ 180 | if len(a) == 0 && (len(b) > 0) { 181 | return 1 182 | } else if len(b) == 0 && (len(a) > 0) { 183 | return -1 184 | } 185 | 186 | // If there is a prerelease, check and compare each part. 187 | return recursivePreReleaseCompare(a.Slice(), b.Slice()) 188 | } 189 | 190 | func recursiveCompare(versionA []int64, versionB []int64) int { 191 | if len(versionA) == 0 { 192 | return 0 193 | } 194 | 195 | a := versionA[0] 196 | b := versionB[0] 197 | 198 | if a > b { 199 | return 1 200 | } else if a < b { 201 | return -1 202 | } 203 | 204 | return recursiveCompare(versionA[1:], versionB[1:]) 205 | } 206 | 207 | func recursivePreReleaseCompare(versionA []string, versionB []string) int { 208 | // A larger set of pre-release fields has a higher precedence than a smaller set, 209 | // if all of the preceding identifiers are equal. 210 | if len(versionA) == 0 { 211 | if len(versionB) > 0 { 212 | return -1 213 | } 214 | return 0 215 | } else if len(versionB) == 0 { 216 | // We're longer than versionB so return 1. 217 | return 1 218 | } 219 | 220 | a := versionA[0] 221 | b := versionB[0] 222 | 223 | aInt := false 224 | bInt := false 225 | 226 | aI, err := strconv.Atoi(versionA[0]) 227 | if err == nil { 228 | aInt = true 229 | } 230 | 231 | bI, err := strconv.Atoi(versionB[0]) 232 | if err == nil { 233 | bInt = true 234 | } 235 | 236 | // Numeric identifiers always have lower precedence than non-numeric identifiers. 237 | if aInt && !bInt { 238 | return -1 239 | } else if !aInt && bInt { 240 | return 1 241 | } 242 | 243 | // Handle Integer Comparison 244 | if aInt && bInt { 245 | if aI > bI { 246 | return 1 247 | } else if aI < bI { 248 | return -1 249 | } 250 | } 251 | 252 | // Handle String Comparison 253 | if a > b { 254 | return 1 255 | } else if a < b { 256 | return -1 257 | } 258 | 259 | return recursivePreReleaseCompare(versionA[1:], versionB[1:]) 260 | } 261 | 262 | // BumpMajor increments the Major field by 1 and resets all other fields to their default values 263 | func (v *Version) BumpMajor() { 264 | v.Major += 1 265 | v.Minor = 0 266 | v.Patch = 0 267 | v.PreRelease = PreRelease("") 268 | v.Metadata = "" 269 | } 270 | 271 | // BumpMinor increments the Minor field by 1 and resets all other fields to their default values 272 | func (v *Version) BumpMinor() { 273 | v.Minor += 1 274 | v.Patch = 0 275 | v.PreRelease = PreRelease("") 276 | v.Metadata = "" 277 | } 278 | 279 | // BumpPatch increments the Patch field by 1 and resets all other fields to their default values 280 | func (v *Version) BumpPatch() { 281 | v.Patch += 1 282 | v.PreRelease = PreRelease("") 283 | v.Metadata = "" 284 | } 285 | 286 | // validateIdentifier makes sure the provided identifier satisfies semver spec 287 | func validateIdentifier(id string) error { 288 | if id != "" && !reIdentifier.MatchString(id) { 289 | return fmt.Errorf("%s is not a valid semver identifier", id) 290 | } 291 | return nil 292 | } 293 | 294 | // reIdentifier is a regular expression used to check that pre-release and metadata 295 | // identifiers satisfy the spec requirements 296 | var reIdentifier = regexp.MustCompile(`^[0-9A-Za-z-]+(\.[0-9A-Za-z-]+)*$`) 297 | -------------------------------------------------------------------------------- /semver/semver_test.go: -------------------------------------------------------------------------------- 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 | 15 | package semver 16 | 17 | import ( 18 | "bytes" 19 | "encoding/json" 20 | "errors" 21 | "flag" 22 | "fmt" 23 | "math/rand" 24 | "reflect" 25 | "testing" 26 | "time" 27 | 28 | "gopkg.in/yaml.v3" 29 | ) 30 | 31 | type fixture struct { 32 | GreaterVersion string 33 | LesserVersion string 34 | } 35 | 36 | var fixtures = []fixture{ 37 | {"0.0.0", "0.0.0-foo"}, 38 | {"0.0.1", "0.0.0"}, 39 | {"1.0.0", "0.9.9"}, 40 | {"0.10.0", "0.9.0"}, 41 | {"0.99.0", "0.10.0"}, 42 | {"2.0.0", "1.2.3"}, 43 | {"0.0.0", "0.0.0-foo"}, 44 | {"0.0.1", "0.0.0"}, 45 | {"1.0.0", "0.9.9"}, 46 | {"0.10.0", "0.9.0"}, 47 | {"0.99.0", "0.10.0"}, 48 | {"2.0.0", "1.2.3"}, 49 | {"0.0.0", "0.0.0-foo"}, 50 | {"0.0.1", "0.0.0"}, 51 | {"1.0.0", "0.9.9"}, 52 | {"0.10.0", "0.9.0"}, 53 | {"0.99.0", "0.10.0"}, 54 | {"2.0.0", "1.2.3"}, 55 | {"1.2.3", "1.2.3-asdf"}, 56 | {"1.2.3", "1.2.3-4"}, 57 | {"1.2.3", "1.2.3-4-foo"}, 58 | {"1.2.3-5-foo", "1.2.3-5"}, 59 | {"1.2.3-5", "1.2.3-4"}, 60 | {"1.2.3-5-foo", "1.2.3-5-Foo"}, 61 | {"3.0.0", "2.7.2+asdf"}, 62 | {"3.0.0+foobar", "2.7.2"}, 63 | {"1.2.3-a.10", "1.2.3-a.5"}, 64 | {"1.2.3-a.b", "1.2.3-a.5"}, 65 | {"1.2.3-a.b", "1.2.3-a"}, 66 | {"1.2.3-a.b.c.10.d.5", "1.2.3-a.b.c.5.d.100"}, 67 | {"1.0.0", "1.0.0-rc.1"}, 68 | {"1.0.0-rc.2", "1.0.0-rc.1"}, 69 | {"1.0.0-rc.1", "1.0.0-beta.11"}, 70 | {"1.0.0-beta.11", "1.0.0-beta.2"}, 71 | {"1.0.0-beta.2", "1.0.0-beta"}, 72 | {"1.0.0-beta", "1.0.0-alpha.beta"}, 73 | {"1.0.0-alpha.beta", "1.0.0-alpha.1"}, 74 | {"1.0.0-alpha.1", "1.0.0-alpha"}, 75 | {"1.2.3-rc.1-1-1hash", "1.2.3-rc.2"}, 76 | } 77 | 78 | func TestCompare(t *testing.T) { 79 | for _, v := range fixtures { 80 | gt, err := NewVersion(v.GreaterVersion) 81 | if err != nil { 82 | t.Error(err) 83 | } 84 | 85 | lt, err := NewVersion(v.LesserVersion) 86 | if err != nil { 87 | t.Error(err) 88 | } 89 | 90 | if gt.LessThan(*lt) { 91 | t.Errorf("%s should not be less than %s", gt, lt) 92 | } 93 | if gt.Equal(*lt) { 94 | t.Errorf("%s should not be equal to %s", gt, lt) 95 | } 96 | if gt.Compare(*lt) <= 0 { 97 | t.Errorf("%s should be greater than %s", gt, lt) 98 | } 99 | if !lt.LessThan(*gt) { 100 | t.Errorf("%s should be less than %s", lt, gt) 101 | } 102 | if !lt.Equal(*lt) { 103 | t.Errorf("%s should be equal to %s", lt, lt) 104 | } 105 | if lt.Compare(*gt) > 0 { 106 | t.Errorf("%s should not be greater than %s", lt, gt) 107 | } 108 | } 109 | } 110 | 111 | func testString(t *testing.T, orig string, version *Version) { 112 | if orig != version.String() { 113 | t.Errorf("%s != %s", orig, version) 114 | } 115 | } 116 | 117 | func TestString(t *testing.T) { 118 | for _, v := range fixtures { 119 | gt, err := NewVersion(v.GreaterVersion) 120 | if err != nil { 121 | t.Error(err) 122 | } 123 | testString(t, v.GreaterVersion, gt) 124 | 125 | lt, err := NewVersion(v.LesserVersion) 126 | if err != nil { 127 | t.Error(err) 128 | } 129 | testString(t, v.LesserVersion, lt) 130 | } 131 | } 132 | 133 | func shuffleStringSlice(src []string) []string { 134 | dest := make([]string, len(src)) 135 | perm := rand.New(rand.NewSource(time.Now().Unix())).Perm(len(src)) 136 | for i, v := range perm { 137 | dest[v] = src[i] 138 | } 139 | return dest 140 | } 141 | 142 | func TestSort(t *testing.T) { 143 | sortedVersions := []string{"1.0.0", "1.0.2", "1.2.0", "3.1.1"} 144 | unsortedVersions := shuffleStringSlice(sortedVersions) 145 | 146 | semvers := []*Version{} 147 | for _, v := range unsortedVersions { 148 | sv, err := NewVersion(v) 149 | if err != nil { 150 | t.Fatal(err) 151 | } 152 | semvers = append(semvers, sv) 153 | } 154 | 155 | Sort(semvers) 156 | 157 | for idx, sv := range semvers { 158 | if sv.String() != sortedVersions[idx] { 159 | t.Fatalf("incorrect sort at index %v", idx) 160 | } 161 | } 162 | } 163 | 164 | func TestBumpMajor(t *testing.T) { 165 | version, _ := NewVersion("1.0.0") 166 | version.BumpMajor() 167 | if version.Major != 2 { 168 | t.Fatalf("bumping major on 1.0.0 resulted in %v", version) 169 | } 170 | 171 | version, _ = NewVersion("1.5.2") 172 | version.BumpMajor() 173 | if version.Minor != 0 && version.Patch != 0 { 174 | t.Fatalf("bumping major on 1.5.2 resulted in %v", version) 175 | } 176 | 177 | version, _ = NewVersion("1.0.0+build.1-alpha.1") 178 | version.BumpMajor() 179 | if version.PreRelease != "" && version.Metadata != "" { 180 | t.Fatalf("bumping major on 1.0.0+build.1-alpha.1 resulted in %v", version) 181 | } 182 | } 183 | 184 | func TestBumpMinor(t *testing.T) { 185 | version, _ := NewVersion("1.0.0") 186 | version.BumpMinor() 187 | 188 | if version.Major != 1 { 189 | t.Fatalf("bumping minor on 1.0.0 resulted in %v", version) 190 | } 191 | 192 | if version.Minor != 1 { 193 | t.Fatalf("bumping major on 1.0.0 resulted in %v", version) 194 | } 195 | 196 | version, _ = NewVersion("1.0.0+build.1-alpha.1") 197 | version.BumpMinor() 198 | if version.PreRelease != "" && version.Metadata != "" { 199 | t.Fatalf("bumping major on 1.0.0+build.1-alpha.1 resulted in %v", version) 200 | } 201 | } 202 | 203 | func TestBumpPatch(t *testing.T) { 204 | version, _ := NewVersion("1.0.0") 205 | version.BumpPatch() 206 | 207 | if version.Major != 1 { 208 | t.Fatalf("bumping minor on 1.0.0 resulted in %v", version) 209 | } 210 | 211 | if version.Minor != 0 { 212 | t.Fatalf("bumping major on 1.0.0 resulted in %v", version) 213 | } 214 | 215 | if version.Patch != 1 { 216 | t.Fatalf("bumping major on 1.0.0 resulted in %v", version) 217 | } 218 | 219 | version, _ = NewVersion("1.0.0+build.1-alpha.1") 220 | version.BumpPatch() 221 | if version.PreRelease != "" && version.Metadata != "" { 222 | t.Fatalf("bumping major on 1.0.0+build.1-alpha.1 resulted in %v", version) 223 | } 224 | } 225 | 226 | func TestMust(t *testing.T) { 227 | tests := []struct { 228 | versionStr string 229 | 230 | version *Version 231 | recov interface{} 232 | }{ 233 | { 234 | versionStr: "1.0.0", 235 | version: &Version{Major: 1}, 236 | }, 237 | { 238 | versionStr: "version number", 239 | recov: errors.New("version number is not in dotted-tri format"), 240 | }, 241 | } 242 | 243 | for _, tt := range tests { 244 | func() { 245 | defer func() { 246 | recov := recover() 247 | if !reflect.DeepEqual(tt.recov, recov) { 248 | t.Fatalf("incorrect panic for %q: want %v, got %v", tt.versionStr, tt.recov, recov) 249 | } 250 | }() 251 | 252 | version := Must(NewVersion(tt.versionStr)) 253 | if !reflect.DeepEqual(tt.version, version) { 254 | t.Fatalf("incorrect version for %q: want %+v, got %+v", tt.versionStr, tt.version, version) 255 | } 256 | }() 257 | } 258 | } 259 | 260 | type fixtureJSON struct { 261 | GreaterVersion *Version 262 | LesserVersion *Version 263 | } 264 | 265 | func TestJSON(t *testing.T) { 266 | fj := make([]fixtureJSON, len(fixtures)) 267 | for i, v := range fixtures { 268 | var err error 269 | fj[i].GreaterVersion, err = NewVersion(v.GreaterVersion) 270 | if err != nil { 271 | t.Fatal(err) 272 | } 273 | fj[i].LesserVersion, err = NewVersion(v.LesserVersion) 274 | if err != nil { 275 | t.Fatal(err) 276 | } 277 | } 278 | 279 | fromStrings, err := json.Marshal(fixtures) 280 | if err != nil { 281 | t.Fatal(err) 282 | } 283 | fromVersions, err := json.Marshal(fj) 284 | if err != nil { 285 | t.Fatal(err) 286 | } 287 | if !bytes.Equal(fromStrings, fromVersions) { 288 | t.Errorf("Expected: %s", fromStrings) 289 | t.Errorf("Unexpected: %s", fromVersions) 290 | } 291 | 292 | fromJson := make([]fixtureJSON, 0, len(fj)) 293 | err = json.Unmarshal(fromStrings, &fromJson) 294 | if err != nil { 295 | t.Fatal(err) 296 | } 297 | if !reflect.DeepEqual(fromJson, fj) { 298 | t.Error("Expected: ", fj) 299 | t.Error("Unexpected: ", fromJson) 300 | } 301 | } 302 | 303 | func TestYAML(t *testing.T) { 304 | document, err := yaml.Marshal(fixtures) 305 | if err != nil { 306 | t.Fatal(err) 307 | } 308 | 309 | expected := make([]fixtureJSON, len(fixtures)) 310 | for i, v := range fixtures { 311 | var err error 312 | expected[i].GreaterVersion, err = NewVersion(v.GreaterVersion) 313 | if err != nil { 314 | t.Fatal(err) 315 | } 316 | expected[i].LesserVersion, err = NewVersion(v.LesserVersion) 317 | if err != nil { 318 | t.Fatal(err) 319 | } 320 | } 321 | 322 | fromYAML := make([]fixtureJSON, 0, len(fixtures)) 323 | err = yaml.Unmarshal(document, &fromYAML) 324 | if err != nil { 325 | t.Fatal(err) 326 | } 327 | 328 | if !reflect.DeepEqual(fromYAML, expected) { 329 | t.Error("Expected: ", expected) 330 | t.Error("Unexpected: ", fromYAML) 331 | } 332 | } 333 | 334 | func TestBadInput(t *testing.T) { 335 | bad := []string{ 336 | "1.2", 337 | "1.2.3x", 338 | "0x1.3.4", 339 | "-1.2.3", 340 | "1.2.3.4", 341 | "0.88.0-11_e4e5dcabb", 342 | "0.88.0+11_e4e5dcabb", 343 | } 344 | for _, b := range bad { 345 | if _, err := NewVersion(b); err == nil { 346 | t.Error("Improperly accepted value: ", b) 347 | } 348 | } 349 | } 350 | 351 | func TestFlag(t *testing.T) { 352 | v := Version{} 353 | f := flag.NewFlagSet("version", flag.ContinueOnError) 354 | f.Var(&v, "version", "set version") 355 | 356 | if err := f.Set("version", "1.2.3"); err != nil { 357 | t.Fatal(err) 358 | } 359 | 360 | if v.String() != "1.2.3" { 361 | t.Errorf("Set wrong value %q", v) 362 | } 363 | } 364 | 365 | func ExampleVersion_LessThan() { 366 | vA := New("1.2.3") 367 | vB := New("3.2.1") 368 | 369 | fmt.Printf("%s < %s == %t\n", vA, vB, vA.LessThan(*vB)) 370 | // Output: 371 | // 1.2.3 < 3.2.1 == true 372 | } 373 | -------------------------------------------------------------------------------- /semver/sort.go: -------------------------------------------------------------------------------- 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 | 15 | package semver 16 | 17 | import ( 18 | "sort" 19 | ) 20 | 21 | type Versions []*Version 22 | 23 | func (s Versions) Len() int { 24 | return len(s) 25 | } 26 | 27 | func (s Versions) Swap(i, j int) { 28 | s[i], s[j] = s[j], s[i] 29 | } 30 | 31 | func (s Versions) Less(i, j int) bool { 32 | return s[i].LessThan(*s[j]) 33 | } 34 | 35 | // Sort sorts the given slice of Version 36 | func Sort(versions []*Version) { 37 | sort.Sort(Versions(versions)) 38 | } 39 | --------------------------------------------------------------------------------