trpc.group/trpc-go/trpc-cmdline@v1.0.9/util/semver/semver.go (about)

     1  // Tencent is pleased to support the open source community by making tRPC available.
     2  //
     3  // Copyright (C) 2023 THL A29 Limited, a Tencent company.
     4  // All rights reserved.
     5  //
     6  // If you have downloaded a copy of the tRPC source code from Tencent,
     7  // please note that tRPC source code is licensed under the  Apache 2.0 License,
     8  // A copy of the Apache 2.0 License is included in this file.
     9  
    10  // Package semver is a library for parsing tool versions.
    11  package semver
    12  
    13  import (
    14  	"regexp"
    15  	"strconv"
    16  )
    17  
    18  const versionPattern = "(0|(?:[1-9]\\d*))(?:\\.(0|(?:[1-9]\\d*))(?:\\.(0|(?:[1-9]\\d*)))?(?:\\-([\\w][\\w\\.\\-_]*))?)?"
    19  
    20  var versionRE = regexp.MustCompile(versionPattern)
    21  
    22  // Versions extract the major, minor and revision (patching) version
    23  func Versions(ver string) (major, minor, revision int) {
    24  	var err error
    25  	matches := versionRE.FindStringSubmatch(ver)
    26  
    27  	if len(matches) >= 2 {
    28  		major, err = strconv.Atoi(matches[1])
    29  		if err != nil {
    30  			return
    31  		}
    32  	}
    33  
    34  	if len(matches) >= 3 {
    35  		minor, err = strconv.Atoi(matches[2])
    36  		if err != nil {
    37  			return
    38  		}
    39  	}
    40  
    41  	if len(matches) >= 4 {
    42  		revision, err = strconv.Atoi(matches[3])
    43  		if err != nil {
    44  			return
    45  		}
    46  	}
    47  	return
    48  }
    49  
    50  // NewerThan check whether semver `v1` is newer than `v2` or not.
    51  func NewerThan(v1 string, v2 string) bool {
    52  	m1, n1, r1 := Versions(v1)
    53  	m2, n2, r2 := Versions(v2)
    54  
    55  	return (m1 > m2) || (m1 == m2 && n1 > n2) || (m1 == m2 && n1 == n2 && r1 > r2)
    56  }