Skip to content

Instantly share code, notes, and snippets.

@bronze1man
Last active January 18, 2023 02:46
Show Gist options
  • Save bronze1man/90aad9f41692c16895be3e499021dc73 to your computer and use it in GitHub Desktop.
Save bronze1man/90aad9f41692c16895be3e499021dc73 to your computer and use it in GitHub Desktop.
Semantic Versioning 2.0.0 compare , valid , invalid example

base on https://pkg.go.dev/golang.org/x/mod/semver which base on https://semver.org/

  • I think smallest version is v0.0.0-0. No biggest version when string length is unlimited.

  • valid (sort by smallest to biggest)

v0.0.0-0
v0.0.0-0+0
v0.0.0-2
v0.0.0-12
v0.0.0--0
v0.0.0-12alpha
v0.0.0-alpha
v0.0.0-alpha12
v0.0.0+0
v0.0.0
v0.0
v0
v0.0.1-0
v0.0.1-0.0
v0.0.1-0.0.0.0.0.0.0.0.0.1
v0.0.1-0.0.0.1
v0.0.1-0.0.1
v0.0.1-0.1
v0.0.1-1
v0.0.1-a
v0.0.1-alpha
v0.0.1
v0.0.2
v0.0.12
v1.0.0-0
v1
v1.0
v1.0.0
v2.0.0
v12.0.0
v99999999999999999999999999999999.0.0
  • invalid
v0.0.0.1
v0.0.0-000
v0.0.0-002
v0.0.0+
v0.0.0-
v0-0
v1-0
package main
import (
"golang.org/x/mod/semver"
"sort"
"fmt"
)
func main(){
list:=[]string{
`v0.0.0--0`,
`v0.0.0-0`,
`v0.0.0-0+0`,
`v0.0.0-2`,
`v0.0.0-12`,
`v0.0.0-alpha`,
`v0.0.0-alpha12`,
`v0.0.0-12alpha`,
`v0.0.0+0`,
`v0.0.0`,
`v0.0`,
`v0`,
`v0.0.1-0.1`,
`v0.0.1-0.0.0.0.0.0.0.0.0.1`,
`v0.0.1-0.0.0.1`,
`v0.0.1-0.0.1`,
`v0.0.1-0.0`,
`v0.0.1-0`,
`v0.0.1-1`,
`v0.0.1-a`,
`v0.0.1-alpha`,
`v0.0.1`,
`v0.0.2`,
`v0.0.12`,
`v1.0.0-0`,
`v1`,
`v1.0`,
`v1.0.0`,
`v2.0.0`,
`v12.0.0`,
`v99999999999999999999999999999999.0.0`,
`v0.0.0.1`, // invalid
`v0.0.0-000`,
`v0.0.0-002`,
`v0.0.0+`,
`v0.0.0-`,
`v0-0`,
`v1-0`,
}
validList,inValidList:=sortValid(list)
fmt.Println(`* valid (sort by smallest to biggest)`)
fmt.Println("```")
for _,v:=range validList{
fmt.Println(v)
}
fmt.Println("```")
fmt.Println(`* invalid`)
fmt.Println("```")
for _,v:=range inValidList{
fmt.Println(v)
}
fmt.Println("```")
}
func sortValid(vList []string) (validList []string,invalidList []string){
for _,v:=range vList{
if semver.IsValid(v){
validList = append(validList,v)
}else{
invalidList = append(invalidList,v)
}
}
sort.Slice(validList, func(i int, j int) bool {
return semver.Compare(validList[i], validList[j])==-1
})
return validList,invalidList
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment