Skip to content

Commit

Permalink
feat: notify user on json parsing error for snippets
Browse files Browse the repository at this point in the history
closes #132
  • Loading branch information
Saghen committed Oct 21, 2024
1 parent ffc4282 commit c5146a5
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 4 deletions.
4 changes: 2 additions & 2 deletions lua/blink/cmp/sources/snippets/registry.lua
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ function registry:get_snippets_for_ft(filetype)
for _, f in ipairs(files) do
local contents = utils.read_file(f)
if contents then
local snippets = vim.json.decode(contents)
local snippets = utils.parse_json_with_error_msg(f, contents)
for _, key in ipairs(vim.tbl_keys(snippets)) do
local snippet = utils.read_snippet(snippets[key], key)
for snippet_name, snippet_def in pairs(snippet) do
Expand All @@ -58,7 +58,7 @@ function registry:get_snippets_for_ft(filetype)
else
local contents = utils.read_file(files)
if contents then
local snippets = vim.json.decode(contents)
local snippets = utils.parse_json_with_error_msg(files, contents)
for _, key in ipairs(vim.tbl_keys(snippets)) do
local snippet = utils.read_snippet(snippets[key], key)
for key, snippet in pairs(snippet) do
Expand Down
4 changes: 2 additions & 2 deletions lua/blink/cmp/sources/snippets/scan.lua
Original file line number Diff line number Diff line change
Expand Up @@ -72,10 +72,10 @@ function scan.load_package_json(path)
local data = utils.read_file(file)
if not data then return end

local pkg = vim.json.decode(data)
local pkg = require('blink.cmp.sources.snippets.utils').parse_json_with_error_msg(file, data)

---@type {path: string, language: string|string[]}[]
local snippets = vim.tbl_get(pkg, 'contributes', 'snippets')

if not snippets then return end

local ret = {} ---@type table<string, string[]>
Expand Down
15 changes: 15 additions & 0 deletions lua/blink/cmp/sources/snippets/utils.lua
Original file line number Diff line number Diff line change
@@ -1,5 +1,20 @@
local utils = {}

--- Parses the json file and notifies the user if there's an error
---@param path string
---@param json string
function utils.parse_json_with_error_msg(path, json)
local ok, parsed = pcall(vim.json.decode, json)
if not ok then
vim.notify(
'Failed to parse json file "' .. path .. '" for blink.cmp snippets. Error: ' .. parsed,
vim.log.levels.ERROR
)
return {}
end
return parsed
end

---@type fun(path: string): string|nil
function utils.read_file(path)
local file = io.open(path, 'r')
Expand Down

0 comments on commit c5146a5

Please sign in to comment.