github.com/sealerio/sealer@v0.11.1-0.20240507115618-f4f89c5853ae/utils/version/version.go (about)

     1  // Copyright © 2022 Alibaba Group Holding Ltd.
     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 version
    16  
    17  import (
    18  	"fmt"
    19  	"strings"
    20  )
    21  
    22  // Version is a string that we used to normalize version string.
    23  type Version string
    24  
    25  // splitVersion takes version string, and encapsulates it in comparable []string.
    26  func splitVersion(version string) []string {
    27  	version = strings.Replace(version, "v", "", -1)
    28  	version = strings.Split(version, "-")[0]
    29  	return strings.Split(version, ".")
    30  }
    31  
    32  // GreaterThan if givenVersion >= oldVersion return true, else return false
    33  func (v Version) GreaterThan(oldVersion Version) (bool, error) {
    34  	givenVersion := splitVersion(string(v))
    35  	ov := splitVersion(string(oldVersion))
    36  
    37  	if len(givenVersion) != 3 || len(ov) != 3 {
    38  		return false, fmt.Errorf("error version format %s %s", v, ov)
    39  	}
    40  	//TODO check if necessary need v = version logic!
    41  	if givenVersion[0] > ov[0] {
    42  		return true, nil
    43  	} else if givenVersion[0] < ov[0] {
    44  		return false, nil
    45  	}
    46  	if givenVersion[1] > ov[1] {
    47  		return true, nil
    48  	} else if givenVersion[1] < ov[1] {
    49  		return false, nil
    50  	}
    51  	if givenVersion[2] > ov[2] {
    52  		return true, nil
    53  	}
    54  	return true, nil
    55  }