Debian Codegraph @

git/version.go

raw symbols SCIP
1 package git
2
3 import (
4 "regexp"
5 "strconv"
6 "sync"
7
8 "github.com/git-lfs/git-lfs/v3/subprocess"
9 "github.com/rubyist/tracerx"
10 )
11
12 var (
13 gitVersionOnce sync.Once
14 gitVersion string
15 gitVersionErr error
16 )
17
18 func Version() (string, error) {
19 gitVersionOnce.Do(func() {
20 gitVersion, gitVersionErr =
21 subprocess.SimpleExec("git", "version")
22 })
23 return gitVersion, gitVersionErr
24 }
25
26 // IsVersionAtLeast returns whether the git version is the one specified or higher
27 // argument is plain version string separated by '.' e.g. "2.3.1" but can omit minor/patch
28 func IsGitVersionAtLeast(ver string) bool {
29 gitver, err := Version()
30 if err != nil {
31 tracerx.Printf("Error getting git version: %v", err)
32 return false
33 }
34 return IsVersionAtLeast(gitver, ver)
35 }
36
37 // IsVersionAtLeast compares 2 version strings (ok to be prefixed with 'git version', ignores)
38 func IsVersionAtLeast(actualVersion, desiredVersion string) bool {
39 // Capture 1-3 version digits, optionally prefixed with 'git version' and possibly
40 // with suffixes which we'll ignore (e.g. unstable builds, MinGW versions)
41 verregex := regexp.MustCompile(`(?:git version\s+)?(\d+)(?:.(\d+))?(?:.(\d+))?.*`)
42
43 var atleast uint64
44 // Support up to 1000 in major/minor/patch digits
45 const majorscale = 1000 * 1000
46 const minorscale = 1000
47
48 if match := verregex.FindStringSubmatch(desiredVersion); match != nil {
49 // Ignore errors as regex won't match anything other than digits
50 major, _ := strconv.Atoi(match[1])
51 atleast += uint64(major * majorscale)
52 if len(match) > 2 {
53 minor, _ := strconv.Atoi(match[2])
54 atleast += uint64(minor * minorscale)
55 }
56 if len(match) > 3 {
57 patch, _ := strconv.Atoi(match[3])
58 atleast += uint64(patch)
59 }
60 }
61
62 var actual uint64
63 if match := verregex.FindStringSubmatch(actualVersion); match != nil {
64 major, _ := strconv.Atoi(match[1])
65 actual += uint64(major * majorscale)
66 if len(match) > 2 {
67 minor, _ := strconv.Atoi(match[2])
68 actual += uint64(minor * minorscale)
69 }
70 if len(match) > 3 {
71 patch, _ := strconv.Atoi(match[3])
72 actual += uint64(patch)
73 }
74 }
75
76 return actual >= atleast
77 }