diff --git a/runtime/doc/news.txt b/runtime/doc/news.txt index 6db00883eb..80e6af2db3 100644 --- a/runtime/doc/news.txt +++ b/runtime/doc/news.txt @@ -199,6 +199,7 @@ LUA • |vim.hl.range()| now allows multiple timed highlights. • |vim.tbl_extend()| and |vim.tbl_deep_extend()| now accept a function behavior argument. • |vim.fs.root()| can define "equal priority" via nested lists. +• |vim.version.range()| output can be converted to human-readable string with |tostring()|. OPTIONS diff --git a/runtime/lua/vim/version.lua b/runtime/lua/vim/version.lua index e036cf946d..1aa7d4144d 100644 --- a/runtime/lua/vim/version.lua +++ b/runtime/lua/vim/version.lua @@ -266,13 +266,23 @@ function VersionRange:has(version) return version >= self.from and (self.to == nil or version < self.to) end +local range_mt = { + __index = VersionRange, + __tostring = function(self) + if not self.to then + return '>=' .. tostring(self.from) + end + return ('%s - %s'):format(tostring(self.from), tostring(self.to)) + end, +} + --- Parses a semver |version-range| "spec" and returns |vim.VersionRange| object: --- @since 11 --- @param spec string Version range "spec" --- @return vim.VersionRange? function M.range(spec) -- Adapted from https://github.com/folke/lazy.nvim if spec == '*' or spec == '' then - return setmetatable({ from = M.parse('0.0.0') }, { __index = VersionRange }) + return setmetatable({ from = M.parse('0.0.0') }, range_mt) end ---@type number? @@ -286,7 +296,7 @@ function M.range(spec) -- Adapted from https://github.com/folke/lazy.nvim return setmetatable({ from = ra and ra.from, to = rb and (#parts == 3 and rb.from or rb.to), - }, { __index = VersionRange }) + }, range_mt) end ---@type string, string local mods, version = spec:lower():match('^([%^=<>~]*)(.*)$') @@ -332,7 +342,7 @@ function M.range(spec) -- Adapted from https://github.com/folke/lazy.nvim end end ---@diagnostic enable: need-check-nil - return setmetatable({ from = from, to = to }, { __index = VersionRange }) + return setmetatable({ from = from, to = to }, range_mt) end end diff --git a/test/functional/lua/version_spec.lua b/test/functional/lua/version_spec.lua index eba3059c15..e681690e52 100644 --- a/test/functional/lua/version_spec.lua +++ b/test/functional/lua/version_spec.lua @@ -89,6 +89,11 @@ describe('version', function() eq(output, range) end) + it('tostring() ' .. input, function() + eq(type(tostring(range)), 'string') + eq(vim.version.range(tostring(range)), range) + end) + it('[from] in range ' .. input, function() assert(range:has(output.from)) end) @@ -119,6 +124,9 @@ describe('version', function() assert(not vim.version.range('1.2.3-alpha'):has('1.2.3-beta')) assert(vim.version.range('>0.10'):has('0.12.0-dev')) assert(not vim.version.range('>=0.12'):has('0.12.0-dev')) + + local range_alpha = vim.version.range('1.2.3-alpha') + eq(vim.version.range(tostring(range_alpha)), range_alpha) end) it('returns nil with empty version', function()