robin/laufey

git clone https://git.robinwobin.dev/robin/laufey

robinmerge: 1dc9728daa1d8a2702

master
15.2 KiB522 linesraw
1--- @brief
2--- The `vim.version` module provides functions for comparing versions and ranges
3--- conforming to the https://semver.org spec. Plugins, and plugin managers, can use this to check
4--- available tools and dependencies on the current system.
5---
6--- Example:
7---
8--- ```lua
9--- local v = vim.version.parse(vim.system({'tmux', '-V'}):wait().stdout, {strict=false})
10--- if vim.version.gt(v, {3, 2, 0}) then
11---   -- ...
12--- end
13--- ```
14---
15--- [vim.version()] returns the version of the current Nvim process.
16---
17--- VERSION RANGE SPEC [version-range]()
18---
19--- A version "range spec" defines a semantic version range which can be tested against a version,
20--- using |vim.version.range()|.
21---
22--- Supported range specs are shown in the following table.
23--- Note: suffixed versions (1.2.3-rc1) are not matched.
24---
25--- ```
26--- 1.2.3             is 1.2.3
27--- =1.2.3            is 1.2.3
28--- >1.2.3            greater than 1.2.3
29--- <1.2.3            before 1.2.3
30--- >=1.2.3           at least 1.2.3
31--- <=1.2.3           at most 1.2.3
32--- ~1.2.3            is >=1.2.3 <1.3.0       "reasonably close to 1.2.3"
33--- ^1.2.3            is >=1.2.3 <2.0.0       "compatible with 1.2.3"
34--- ^0.2.3            is >=0.2.3 <0.3.0       (0.x.x is special)
35--- ^0.0.1            is =0.0.1               (0.0.x is special)
36--- ^1.2              is >=1.2.0 <2.0.0       (like ^1.2.0)
37--- ~1.2              is >=1.2.0 <1.3.0       (like ~1.2.0)
38--- ^1                is >=1.0.0 <2.0.0       "compatible with 1"
39--- ~1                same                    "reasonably close to 1"
40--- 1.x               same
41--- 1.*               same
42--- 1                 same
43--- *                 any version
44--- x                 same
45---
46--- 1.2.3 - 2.3.4     is >=1.2.3 <2.3.4
47---
48--- Partial right: missing pieces treated as x (2.3 => 2.3.x).
49--- 1.2.3 - 2.3       is >=1.2.3 <2.4.0
50--- 1.2.3 - 2         is >=1.2.3 <3.0.0
51---
52--- Partial left: missing pieces treated as 0 (1.2 => 1.2.0).
53--- 1.2 - 2.3.0       is 1.2.0 - 2.3.0
54--- ```
55
56---@class (internal) vim.VersionModule
57---@operator call: vim.Version
58local M = {}
59
60---@nodoc
61---@class vim.Version
62---@field [1] number
63---@field [2] number
64---@field [3] number
65---@field major number
66---@field minor number
67---@field patch number
68---@field prerelease? string
69---@field build? string
70local Version = {}
71
72--- Compares prerelease strings: per semver, number parts must be must be treated as numbers:
73--- "pre1.10" is greater than "pre1.2". https://semver.org/#spec-item-11
74---@param prerel1 string?
75---@param prerel2 string?
76local function cmp_prerel(prerel1, prerel2)
77  if not prerel1 or not prerel2 then
78    return prerel1 and -1 or (prerel2 and 1 or 0)
79  end
80  -- TODO(justinmk): not fully spec-compliant; this treats non-dot-delimited digit sequences as
81  -- numbers. Maybe better: "(.-)(%.%d*)".
82  local iter1 = prerel1:gmatch('([^0-9]*)(%d*)')
83  local iter2 = prerel2:gmatch('([^0-9]*)(%d*)')
84  while true do
85    local word1, n1 = iter1() --- @type string?, string|number|nil
86    local word2, n2 = iter2() --- @type string?, string|number|nil
87    if word1 == nil and word2 == nil then -- Done iterating.
88      return 0
89    end
90
91    word1 = word1 or ''
92    n1 = vim._tointeger(n1) or 0
93    word2 = word2 or ''
94    n2 = vim._tointeger(n2) or 0
95
96    if word1 ~= word2 then
97      return word1 < word2 and -1 or 1
98    end
99    if n1 ~= n2 then
100      return n1 < n2 and -1 or 1
101    end
102  end
103end
104
105---@param key string|integer
106function Version:__index(key)
107  return type(key) == 'number' and ({ self.major, self.minor, self.patch })[key] or Version[key]
108end
109
110---@param key string|integer
111---@param value integer|string|nil
112function Version:__newindex(key, value)
113  if key == 1 then
114    self.major = value
115  elseif key == 2 then
116    self.minor = value
117  elseif key == 3 then
118    self.patch = value
119  else
120    rawset(self, key, value)
121  end
122end
123
124---@param other vim.Version
125function Version:__eq(other)
126  for i = 1, 3 do
127    if self[i] ~= other[i] then
128      return false
129    end
130  end
131  return 0 == cmp_prerel(self.prerelease, other.prerelease)
132end
133
134function Version:__tostring()
135  local ret = table.concat({ self.major, self.minor, self.patch }, '.')
136  if self.prerelease then
137    ret = ret .. '-' .. self.prerelease
138  end
139  if self.build and self.build ~= vim.NIL then
140    ret = ret .. '+' .. self.build
141  end
142  return ret
143end
144
145---@param other vim.Version
146function Version:__lt(other)
147  for i = 1, 3 do
148    if self[i] > other[i] then
149      return false
150    elseif self[i] < other[i] then
151      return true
152    end
153  end
154  return -1 == cmp_prerel(self.prerelease, other.prerelease)
155end
156
157---@param other vim.Version
158function Version:__le(other)
159  return self < other or self == other
160end
161
162--- @private
163---
164--- Creates a new Version object, or returns `nil` if `version` is invalid.
165---
166--- @param version string|number[]|vim.Version
167--- @param strict? boolean Reject "1.0", "0-x", "3.2a" or other non-conforming version strings
168--- @return vim.Version?
169function M._version(version, strict) -- Adapted from https://github.com/folke/lazy.nvim
170  if type(version) == 'table' then
171    if version.major then
172      return setmetatable(vim.deepcopy(version, true), Version)
173    end
174    return setmetatable({
175      major = version[1] or 0,
176      minor = version[2] or 0,
177      patch = version[3] or 0,
178    }, Version)
179  end
180
181  if not strict then -- TODO: add more "scrubbing".
182    local scrubbed = version:match('%d[^ ]*')
183    if not scrubbed then
184      return nil
185    end
186    version = scrubbed
187  end
188
189  local prerel = version:match('%-([^+]*)')
190  local prerel_strict = version:match('%-([0-9A-Za-z-]*)')
191  if
192    strict
193    and prerel
194    and (prerel_strict == nil or prerel_strict == '' or not vim.startswith(prerel, prerel_strict))
195  then
196    return nil -- Invalid prerelease.
197  end
198  local build = prerel and version:match('%-[^+]*%+(.*)$') or version:match('%+(.*)$')
199  local major, minor, patch =
200    version:match('^v?(%d+)%.?(%d*)%.?(%d*)' .. (strict and (prerel and '%-' or '$') or ''))
201
202  if
203    (not strict and major)
204    or (major and minor and patch and major ~= '' and minor ~= '' and patch ~= '')
205  then
206    return setmetatable({
207      major = vim._assert_integer(major),
208      minor = minor == '' and 0 or vim._assert_integer(minor),
209      patch = patch == '' and 0 or vim._assert_integer(patch),
210      prerelease = prerel ~= '' and prerel or nil,
211      build = build ~= '' and build or nil,
212    }, Version)
213  end
214  return nil -- Invalid version string.
215end
216
217---TODO: generalize this, move to func.lua
218---
219---@generic T: vim.Version
220---@param versions T[]
221---@return T?
222function M.last(versions)
223  local last = versions[1]
224  for i = 2, #versions do
225    if versions[i] > last then
226      last = versions[i]
227    end
228  end
229  return last
230end
231
232---@class vim.VersionRange
233---@field from vim.Version
234---@field to? vim.Version
235local VersionRange = {}
236
237--- Check if a version is in the range (inclusive `from`, exclusive `to`).
238---
239--- Example:
240---
241--- ```lua
242--- local r = vim.version.range('1.0.0 - 2.0.0')
243--- print(r:has('1.9.9'))       -- true
244--- print(r:has('2.0.0'))       -- false
245--- print(r:has(vim.version())) -- check against current Nvim version
246--- ```
247---
248--- Or use cmp(), le(), lt(), ge(), gt(), and/or eq() to compare a version
249--- against `.to` and `.from` directly:
250---
251--- ```lua
252--- local r = vim.version.range('1.0.0 - 2.0.0') -- >=1.0, <2.0
253--- print(vim.version.ge({1,0,3}, r.from) and vim.version.lt({1,0,3}, r.to))
254--- ```
255---
256--- @see # https://github.com/npm/node-semver#ranges
257--- @since 11
258--- @param version string|vim.Version
259--- @return boolean
260function VersionRange:has(version)
261  if type(version) == 'string' then
262    local parsed = M.parse(version)
263    if not parsed then
264      return false
265    end
266    version = parsed
267  elseif getmetatable(version) ~= Version then
268    -- Need metatable to compare versions.
269    version = setmetatable(vim.deepcopy(version, true), Version)
270  end
271  if self.from == self.to then
272    return version == self.from
273  end
274  return version >= self.from and (self.to == nil or version < self.to)
275end
276
277local range_mt = {
278  __index = VersionRange,
279  __eq = function(self, other)
280    return self.to == other.to and self.from == other.from
281  end,
282  __tostring = function(self)
283    if not self.to then
284      return '>=' .. tostring(self.from)
285    end
286    return ('%s - %s'):format(tostring(self.from), tostring(self.to))
287  end,
288}
289
290--- Parses a semver |version-range| "spec" and returns |vim.VersionRange| object:
291--- @since 11
292--- @param spec string Version range "spec"
293--- @return vim.VersionRange?
294function M.range(spec) -- Adapted from https://github.com/folke/lazy.nvim
295  if spec == '*' or spec == '' then
296    return setmetatable({ from = M.parse('0.0.0') }, range_mt)
297  end
298
299  local hyphen = spec:find(' - ', 1, true)
300  if hyphen then
301    local a = spec:sub(1, hyphen - 1)
302    local b = spec:sub(hyphen + 3)
303    local parts = vim.split(b, '.', { plain = true })
304    local ra = M.range(a)
305    local rb = M.range(b)
306    return setmetatable({
307      from = ra and ra.from,
308      to = rb and (#parts == 3 and rb.from or rb.to),
309    }, range_mt)
310  end
311  local mods, version = spec:lower():match('^([%^=<>~]*)(.*)$')
312  assert(mods and version) -- The pattern matches every string.
313  version = version:gsub('%.[%*x]', '')
314  local parts = vim.split(version:gsub('%-.*', ''), '.', { plain = true })
315  if #parts < 3 and mods == '' then
316    mods = '~'
317  end
318
319  local semver = M.parse(version)
320  if semver then
321    local from = semver --- @type vim.Version?
322    local to = vim.deepcopy(semver, true) --- @type vim.Version?
323    ---@diagnostic disable: need-check-nil
324    if mods == '<' then
325      from = M._version({})
326    elseif mods == '<=' then
327      from = M._version({})
328      -- HACK: construct the smallest reasonable version bigger than `to`
329      -- to simulate `<=` while using exclusive right hand side
330      if to.prerelease then
331        to.prerelease = to.prerelease .. '.0'
332      else
333        to.patch = to.patch + 1
334        to.prerelease = '0'
335      end
336    elseif mods == '>' then
337      -- HACK: construct the smallest reasonable version bigger than `from`
338      -- to simulate `>` while using inclusive left hand side
339      if from.prerelease then
340        from.prerelease = from.prerelease .. '.0'
341      else
342        from.patch = from.patch + 1
343        from.prerelease = '0'
344      end
345      to = nil
346    elseif mods == '>=' then
347      to = nil
348    elseif mods == '~' then
349      if #parts >= 2 then
350        to[2] = to[2] + 1
351        to[3] = 0
352      else
353        to[1] = to[1] + 1
354        to[2] = 0
355        to[3] = 0
356      end
357    elseif mods == '^' then
358      for i = 1, 3 do
359        if to[i] ~= 0 then
360          to[i] = to[i] + 1
361          for j = i + 1, 3 do
362            to[j] = 0
363          end
364          break
365        end
366      end
367    end
368    ---@diagnostic enable: need-check-nil
369    return setmetatable({ from = from, to = to }, range_mt)
370  end
371end
372
373--- Computes the common range shared by the given ranges.
374---
375--- @since 14
376--- @param r1 vim.VersionRange First range to intersect.
377--- @param r2 vim.VersionRange Second range to intersect.
378--- @return vim.VersionRange? Maximal range that is present inside both `r1` and `r2`.
379---   `nil` if such range does not exist.
380function M.intersect(r1, r2)
381  assert(getmetatable(r1) == range_mt)
382  assert(getmetatable(r2) == range_mt)
383
384  local from = r1.from <= r2.from and r2.from or r1.from
385  local to = (r1.to == nil or (r2.to ~= nil and r2.to <= r1.to)) and r2.to or r1.to
386  if to == nil or from < to or (from == to and r1:has(from) and r2:has(from)) then
387    return setmetatable({ from = from, to = to }, range_mt)
388  end
389end
390
391---@param v any
392---@return string
393local function err_msg(v)
394  if type(v) == 'string' then
395    return ('invalid version: "%s"'):format(v)
396  elseif type(v) == 'table' and v.major then
397    return ('invalid version: %s'):format(vim.inspect(v))
398  end
399  return ('invalid version: %s (%s)'):format(tostring(v), type(v))
400end
401
402--- Parses and compares two version objects (the result of |vim.version.parse()|, or
403--- specified literally as a `{major, minor, patch}` tuple, e.g. `{1, 0, 3}`).
404---
405--- Example:
406---
407--- ```lua
408--- if vim.version.cmp({1,0,3}, {0,2,1}) == 0 then
409---   -- ...
410--- end
411--- local v1 = vim.version.parse('1.0.3-pre')
412--- local v2 = vim.version.parse('0.2.1')
413--- if vim.version.cmp(v1, v2) == 0 then
414---   -- ...
415--- end
416--- ```
417---
418--- @note Per semver, build metadata is ignored when comparing two otherwise-equivalent versions.
419--- @since 11
420---
421---@param v1 vim.Version|number[]|string Version object.
422---@param v2 vim.Version|number[]|string Version to compare with `v1`.
423---@return integer -1 if `v1 < v2`, 0 if `v1 == v2`, 1 if `v1 > v2`.
424function M.cmp(v1, v2)
425  local v1_parsed = M._version(v1) or error(err_msg(v1))
426  local v2_parsed = M._version(v2) or error(err_msg(v2))
427  if v1_parsed == v2_parsed then
428    return 0
429  end
430  if v1_parsed > v2_parsed then
431    return 1
432  end
433  return -1
434end
435
436---Returns `true` if the given versions are equal. See |vim.version.cmp()| for usage.
437---@since 11
438---@param v1 vim.Version|number[]|string
439---@param v2 vim.Version|number[]|string
440---@return boolean
441function M.eq(v1, v2)
442  return M.cmp(v1, v2) == 0
443end
444
445---Returns `true` if `v1 <= v2`. See |vim.version.cmp()| for usage.
446---@since 12
447---@param v1 vim.Version|number[]|string
448---@param v2 vim.Version|number[]|string
449---@return boolean
450function M.le(v1, v2)
451  return M.cmp(v1, v2) <= 0
452end
453
454---Returns `true` if `v1 < v2`. See |vim.version.cmp()| for usage.
455---@since 11
456---@param v1 vim.Version|number[]|string
457---@param v2 vim.Version|number[]|string
458---@return boolean
459function M.lt(v1, v2)
460  return M.cmp(v1, v2) == -1
461end
462
463---Returns `true` if `v1 >= v2`. See |vim.version.cmp()| for usage.
464---@since 12
465---@param v1 vim.Version|number[]|string
466---@param v2 vim.Version|number[]|string
467---@return boolean
468function M.ge(v1, v2)
469  return M.cmp(v1, v2) >= 0
470end
471
472---Returns `true` if `v1 > v2`. See |vim.version.cmp()| for usage.
473---@since 11
474---@param v1 vim.Version|number[]|string
475---@param v2 vim.Version|number[]|string
476---@return boolean
477function M.gt(v1, v2)
478  return M.cmp(v1, v2) == 1
479end
480
481---@class vim.version.parse.Opts
482---@inlinedoc
483---
484--- If `true`, no coercion is attempted on input not conforming to semver v2.0.0.
485--- If `false`, `parse()` attempts to coerce input such as "1.0", "0-x", "tmux 3.2a" into valid
486--- versions.
487--- (default: `false`)
488---@field strict? boolean
489
490--- Parses a semantic version string and returns a version object which can be used with other
491--- `vim.version` functions. For example "1.0.1-rc1+build.2" returns:
492---
493--- ```
494--- { major = 1, minor = 0, patch = 1, prerelease = "rc1", build = "build.2" }
495--- ```
496---
497---@see # https://semver.org/spec/v2.0.0.html
498---@since 11
499---
500---@param version string Version string to parse.
501---@param opts vim.version.parse.Opts? Options for parsing.
502---@return vim.Version? # `Version` object or `nil` if input is invalid.
503function M.parse(version, opts)
504  if type(version) ~= 'string' then
505    error(err_msg(version))
506  end
507  opts = opts or { strict = false }
508  return M._version(version, opts.strict)
509end
510
511setmetatable(M, {
512  --- Returns the current Nvim version.
513  ---@return vim.Version
514  __call = function()
515    local version = vim.fn.api_info().version ---@type vim.Version
516    -- Workaround: vim.fn.api_info().version reports "prerelease" as a boolean.
517    version.prerelease = version.prerelease and 'dev' or nil
518    return setmetatable(version, Version)
519  end,
520})
521
522return M