Skip to content

Commit c3dca4a

Browse files
committed
feat(utils): expose a escape function to encode strings, meant to be used by extensions to encode URLs in case their clients does not provide an encode utility
1 parent 16284ba commit c3dca4a

File tree

1 file changed

+19
-4
lines changed

1 file changed

+19
-4
lines changed

lua/rest-nvim/utils.lua

Lines changed: 19 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -11,12 +11,26 @@ local utils = {}
1111
-- NOTE: vim.loop has been renamed to vim.uv in Neovim >= 0.10 and will be removed later
1212
local uv = vim.uv or vim.loop
1313

14+
---Encodes a string into its escaped hexadecimal representation
15+
---taken from Lua Socket and added underscore to ignore
16+
---@param str string Binary string to be encoded
17+
---@return string
18+
function utils.escape(str)
19+
local encoded = string.gsub(str, "([^A-Za-z0-9_])", function(c)
20+
return string.format("%%%02x", string.byte(c))
21+
end)
22+
23+
return encoded
24+
end
25+
1426
---Check if a file exists in the given `path`
1527
---@param path string file path
1628
---@return boolean
1729
function utils.file_exists(path)
30+
---@diagnostic disable-next-line undefined-field
1831
local fd = uv.fs_open(path, "r", 438)
1932
if fd then
33+
---@diagnostic disable-next-line undefined-field
2034
uv.fs_close(fd)
2135
return true
2236
end
@@ -30,15 +44,16 @@ end
3044
function utils.read_file(path)
3145
local logger = _G._rest_nvim.logger
3246

33-
---@type string|uv_fs_t|nil
47+
---@type string|nil
3448
local content
3549
if utils.file_exists(path) then
50+
---@diagnostic disable-next-line undefined-field
3651
local file = uv.fs_open(path, "r", 438)
37-
---@cast file number
52+
---@diagnostic disable-next-line undefined-field
3853
local stat = uv.fs_fstat(file)
39-
---@cast stat uv.aliases.fs_stat_table
54+
---@diagnostic disable-next-line undefined-field
4055
content = uv.fs_read(file, stat.size, 0)
41-
---@cast content string
56+
---@diagnostic disable-next-line undefined-field
4257
uv.fs_close(file)
4358
else
4459
---@diagnostic disable-next-line need-check-nil

0 commit comments

Comments
 (0)