1
0
Fork 0
mirror of https://codeberg.org/forgejo/forgejo.git synced 2024-11-22 08:42:32 -05:00
forgejo/modules/git/version.go

105 lines
1.9 KiB
Go
Raw Normal View History

2014-07-26 00:24:27 -04:00
// Copyright 2014 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package git
import (
"errors"
2015-10-13 16:01:57 -04:00
"fmt"
2014-07-26 00:24:27 -04:00
"strings"
"github.com/Unknwon/com"
)
2014-09-16 10:10:33 -04:00
var (
// Cached Git version.
gitVer *Version
)
2014-07-26 00:24:27 -04:00
// Version represents version of Git.
type Version struct {
Major, Minor, Patch int
}
2014-09-16 10:10:33 -04:00
func ParseVersion(verStr string) (*Version, error) {
infos := strings.Split(verStr, ".")
2014-07-26 00:24:27 -04:00
if len(infos) < 3 {
2014-09-16 10:10:33 -04:00
return nil, errors.New("incorrect version input")
2014-07-26 00:24:27 -04:00
}
2014-09-16 10:10:33 -04:00
v := &Version{}
for i, s := range infos {
2014-07-26 00:24:27 -04:00
switch i {
case 0:
v.Major, _ = com.StrTo(s).Int()
case 1:
v.Minor, _ = com.StrTo(s).Int()
case 2:
2014-09-16 20:58:06 -04:00
v.Patch, _ = com.StrTo(strings.TrimSpace(s)).Int()
2014-07-26 00:24:27 -04:00
}
}
return v, nil
}
2014-09-16 10:10:33 -04:00
func MustParseVersion(verStr string) *Version {
v, _ := ParseVersion(verStr)
return v
}
// Compare compares two versions,
2014-09-16 11:29:53 -04:00
// it returns 1 if original is greater, -1 if original is smaller, 0 if equal.
2014-09-16 10:10:33 -04:00
func (v *Version) Compare(that *Version) int {
if v.Major > that.Major {
return 1
} else if v.Major < that.Major {
return -1
}
if v.Minor > that.Minor {
return 1
} else if v.Minor < that.Minor {
return -1
}
if v.Patch > that.Patch {
return 1
} else if v.Patch < that.Patch {
return -1
}
return 0
}
2014-09-16 11:29:53 -04:00
func (v *Version) LessThan(that *Version) bool {
return v.Compare(that) < 0
}
func (v *Version) AtLeast(that *Version) bool {
return v.Compare(that) >= 0
}
2015-10-13 16:01:57 -04:00
func (v *Version) String() string {
return fmt.Sprintf("%d.%d.%d", v.Major, v.Minor, v.Patch)
}
2014-09-16 10:10:33 -04:00
// GetVersion returns current Git version installed.
func GetVersion() (*Version, error) {
if gitVer != nil {
return gitVer, nil
}
stdout, stderr, err := com.ExecCmd("git", "version")
if err != nil {
return nil, errors.New(stderr)
}
infos := strings.Split(stdout, " ")
if len(infos) < 3 {
return nil, errors.New("not enough output")
}
gitVer, err = ParseVersion(infos[2])
return gitVer, err
}