File: version.go

package info (click to toggle)
lazygit 0.50.0%2Bds1-1
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 6,808 kB
  • sloc: sh: 128; makefile: 76
file content (79 lines) | stat: -rw-r--r-- 1,900 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
package git_commands

import (
	"errors"
	"regexp"
	"strconv"
	"strings"

	"github.com/jesseduffield/lazygit/pkg/commands/oscommands"
)

type GitVersion struct {
	Major, Minor, Patch int
	Additional          string
}

func GetGitVersion(osCommand *oscommands.OSCommand) (*GitVersion, error) {
	versionStr, _, err := osCommand.Cmd.New(NewGitCmd("--version").ToArgv()).RunWithOutputs()
	if err != nil {
		return nil, err
	}

	version, err := ParseGitVersion(versionStr)
	if err != nil {
		return nil, err
	}

	return version, nil
}

func ParseGitVersion(versionStr string) (*GitVersion, error) {
	// versionStr should be something like:
	// git version 2.39.0
	// git version 2.37.1 (Apple Git-137.1)
	re := regexp.MustCompile(`[^\d]*(\d+)(\.\d+)?(\.\d+)?(.*)`)
	matches := re.FindStringSubmatch(versionStr)

	if len(matches) < 5 {
		return nil, errors.New("unexpected git version format: " + versionStr)
	}

	v := &GitVersion{}
	var err error

	if v.Major, err = strconv.Atoi(matches[1]); err != nil {
		return nil, err
	}
	if len(matches[2]) > 1 {
		if v.Minor, err = strconv.Atoi(matches[2][1:]); err != nil {
			return nil, err
		}
	}
	if len(matches[3]) > 1 {
		if v.Patch, err = strconv.Atoi(matches[3][1:]); err != nil {
			return nil, err
		}
	}
	v.Additional = strings.Trim(matches[4], " \r\n")

	return v, nil
}

func (v *GitVersion) IsOlderThan(major, minor, patch int) bool {
	actual := v.Major*1000*1000 + v.Minor*1000 + v.Patch
	required := major*1000*1000 + minor*1000 + patch
	return actual < required
}

func (v *GitVersion) IsOlderThanVersion(version *GitVersion) bool {
	return v.IsOlderThan(version.Major, version.Minor, version.Patch)
}

func (v *GitVersion) IsAtLeast(major, minor, patch int) bool {
	return !v.IsOlderThan(major, minor, patch)
}

func (v *GitVersion) IsAtLeastVersion(version *GitVersion) bool {
	return v.IsAtLeast(version.Major, version.Minor, version.Patch)
}