github.com/Heebron/moby@v0.0.0-20221111184709-6eab4f55faf7/api/types/versions/compare.go (about)

     1  package versions // import "github.com/docker/docker/api/types/versions"
     2  
     3  import (
     4  	"strconv"
     5  	"strings"
     6  )
     7  
     8  // compare compares two version strings
     9  // returns -1 if v1 < v2, 1 if v1 > v2, 0 otherwise.
    10  func compare(v1, v2 string) int {
    11  	if v1 == v2 {
    12  		return 0
    13  	}
    14  	var (
    15  		currTab  = strings.Split(v1, ".")
    16  		otherTab = strings.Split(v2, ".")
    17  	)
    18  
    19  	max := len(currTab)
    20  	if len(otherTab) > max {
    21  		max = len(otherTab)
    22  	}
    23  	for i := 0; i < max; i++ {
    24  		var currInt, otherInt int
    25  
    26  		if len(currTab) > i {
    27  			currInt, _ = strconv.Atoi(currTab[i])
    28  		}
    29  		if len(otherTab) > i {
    30  			otherInt, _ = strconv.Atoi(otherTab[i])
    31  		}
    32  		if currInt > otherInt {
    33  			return 1
    34  		}
    35  		if otherInt > currInt {
    36  			return -1
    37  		}
    38  	}
    39  	return 0
    40  }
    41  
    42  // LessThan checks if a version is less than another
    43  func LessThan(v, other string) bool {
    44  	return compare(v, other) == -1
    45  }
    46  
    47  // LessThanOrEqualTo checks if a version is less than or equal to another
    48  func LessThanOrEqualTo(v, other string) bool {
    49  	return compare(v, other) <= 0
    50  }
    51  
    52  // GreaterThan checks if a version is greater than another
    53  func GreaterThan(v, other string) bool {
    54  	return compare(v, other) == 1
    55  }
    56  
    57  // GreaterThanOrEqualTo checks if a version is greater than or equal to another
    58  func GreaterThanOrEqualTo(v, other string) bool {
    59  	return compare(v, other) >= 0
    60  }
    61  
    62  // Equal checks if a version is equal to another
    63  func Equal(v, other string) bool {
    64  	return compare(v, other) == 0
    65  }