Debian Codegraph @

lua/gitsigns/git/version.lua

raw
1 local async = require('gitsigns.async')
2 local gs_config = require('gitsigns.config')
3
4 local log = require('gitsigns.debug.log')
5 local err = require('gitsigns.message').error
6 local system = require('gitsigns.system').system
7 local tointeger = require('gitsigns.util').tointeger
8
9 local M = {}
10
11 --- @type fun(cmd: string[], opts?: vim.SystemOpts): vim.SystemCompleted
12 local asystem = async.wrap(3, system)
13
14 --- @class (exact) Gitsigns.Version
15 --- @field major integer
16 --- @field minor integer
17 --- @field patch integer
18
19 --- @param version string
20 --- @return Gitsigns.Version
21 local function parse_version(version)
22 assert(version:match('%d+%.%d+%.%w+'), 'Invalid git version: ' .. version)
23 local parts = vim.split(version, '%.')
24 --- @cast parts [string, string, string]
25
26 local patch --- @type integer
27 if parts[3] == 'GIT' then
28 patch = 0
29 else
30 local patch_ver = vim.split(parts[3], '-')
31 patch = assert(tointeger(patch_ver[1]))
32 end
33
34 return {
35 patch = patch,
36 major = assert(tointeger(parts[1])),
37 minor = assert(tointeger(parts[2])),
38 }
39 end
40
41 --- @async
42 local function set_version()
43 local version = gs_config.config._git_version
44 if version ~= 'auto' then
45 local ok, ret = pcall(parse_version, version)
46 if ok then
47 M.version = ret
48 else
49 err(ret --[[@as string]])
50 end
51 return
52 end
53
54 --- @type vim.SystemCompleted
55 local obj = asystem({ 'git', '--version' })
56 async.schedule()
57
58 local line = vim.split(obj.stdout or '', '\n')[1]
59 if not line then
60 err("Unable to detect git version as 'git --version' failed to return anything")
61 log.eprint(obj.stderr)
62 return
63 end
64
65 -- Sometime 'git --version' returns an empty string (#948)
66 if log.assert(type(line) == 'string', 'Unexpected output: ' .. line) then
67 return
68 end
69
70 if log.assert(vim.startswith(line, 'git version'), 'Unexpected output: ' .. line) then
71 return
72 end
73
74 local parts = vim.split(line, '%s+')
75 M.version = parse_version(assert(parts[3]))
76 end
77
78 --- @async
79 --- Usage: check_version{2,3}
80 --- @param major? integer
81 --- @param minor? integer
82 --- @param patch? integer
83 --- @return boolean
84 function M.check(major, minor, patch)
85 if not M.version then
86 set_version()
87 end
88
89 if not M.version then
90 return false
91 elseif not major or not minor then
92 return false
93 elseif M.version.major < major then
94 return false
95 elseif minor and M.version.minor < minor then
96 return false
97 elseif patch and M.version.patch < patch then
98 return false
99 end
100 return true
101 end
102
103 return M