github.com/haalcala/mattermost-server-change-repo@v0.0.0-20210713015153-16753fbeee5f/plugin/checker/internal/version/version.go (about)

     1  // Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
     2  // See LICENSE.txt for license information.
     3  
     4  package version
     5  
     6  import (
     7  	"regexp"
     8  	"strconv"
     9  	"strings"
    10  )
    11  
    12  type V string
    13  
    14  func (v V) GreaterThanOrEqualTo(other V) bool {
    15  	return !v.LessThan(other)
    16  }
    17  
    18  func (v V) LessThan(other V) bool {
    19  	leftParts, leftCount := split(v)
    20  	rightParts, rightCount := split(other)
    21  
    22  	var length int
    23  	if leftCount < rightCount {
    24  		length = rightCount
    25  	} else {
    26  		length = leftCount
    27  	}
    28  
    29  	for i := 0; i < length; i++ {
    30  		var left, right string
    31  
    32  		if i < leftCount {
    33  			left = leftParts[i]
    34  		}
    35  
    36  		if i < rightCount {
    37  			right = rightParts[i]
    38  		}
    39  
    40  		if left == right {
    41  			continue
    42  		}
    43  
    44  		leftInt := parseInt(left)
    45  		rightInt := parseInt(right)
    46  
    47  		isNumericalComparison := leftInt != nil && rightInt != nil
    48  
    49  		if isNumericalComparison {
    50  			return *leftInt < *rightInt
    51  		}
    52  
    53  		return left < right
    54  	}
    55  
    56  	return false
    57  }
    58  
    59  func split(v V) ([]string, int) {
    60  	var chunks []string
    61  
    62  	for _, part := range strings.Split(string(v), ".") {
    63  		chunks = append(chunks, splitNumericalChunks(part)...)
    64  	}
    65  
    66  	return chunks, len(chunks)
    67  }
    68  
    69  var numericalOrAlphaRE = regexp.MustCompile(`(\d+|\D+)`)
    70  
    71  func splitNumericalChunks(s string) []string {
    72  	return numericalOrAlphaRE.FindAllString(s, -1)
    73  }
    74  
    75  func parseInt(s string) *int64 {
    76  	if n, err := strconv.ParseInt(s, 10, 64); err == nil {
    77  		return &n
    78  	}
    79  	return nil
    80  }