From 52209c5930a8c8971b9486cbcbda40e29b0747fb Mon Sep 17 00:00:00 2001 From: Kohei Watanabe <31376689+nabekou29@users.noreply.github.com> Date: Mon, 16 Sep 2024 23:21:56 +0900 Subject: [PATCH] fix: Occur error when can't detect language (#27) --- lua/js-i18n/config.lua | 2 +- lua/js-i18n/utils.lua | 7 +++++-- tests/js-i18n/config_spec.lua | 4 ++-- 3 files changed, 8 insertions(+), 5 deletions(-) diff --git a/lua/js-i18n/config.lua b/lua/js-i18n/config.lua index 143ef1b..091dc98 100644 --- a/lua/js-i18n/config.lua +++ b/lua/js-i18n/config.lua @@ -18,7 +18,7 @@ function M.default_detect_language(path) local abs_path = vim.fn.fnamemodify(path, ":p") local split = vim.split(abs_path, "[/.]") - local lang = nil + local lang = "unknown" for _, part in ipairs(vim.fn.reverse(split)) do if LangSet[normalize_lang(part)] then diff --git a/lua/js-i18n/utils.lua b/lua/js-i18n/utils.lua index ed9a4da..6dbee9f 100644 --- a/lua/js-i18n/utils.lua +++ b/lua/js-i18n/utils.lua @@ -23,10 +23,13 @@ end --- @return string|nil ライブラリの識別子 function M.detect_library(bufnr) local root = M.get_workspace_root(bufnr) - local package_json = root .. "/package.json" - local package = vim.fn.json_decode(vim.fn.readfile(package_json)) + local ok, package_json = pcall(vim.fn.readfile, root .. "/package.json") + if not ok then + return nil + end + local package = vim.fn.json_decode(package_json) if package == nil then return nil end diff --git a/tests/js-i18n/config_spec.lua b/tests/js-i18n/config_spec.lua index a444d86..01559a8 100644 --- a/tests/js-i18n/config_spec.lua +++ b/tests/js-i18n/config_spec.lua @@ -5,12 +5,12 @@ describe("js-i18n.config", function() local tests = { { path = "/path/to/locals/en/trans.json", expected = "en" }, { path = "/path/to/locals/ja/trans.json", expected = "ja" }, - { path = "/path/to/locals/hoge/trans.json", expected = nil }, + { path = "/path/to/locals/hoge/trans.json", expected = "unknown" }, -- Test cases to verify that it is sufficient for the languagee name to be included somewhere. { path = "/path/to/locals/sub/en.json", expected = "en" }, { path = "/path/to/en/locals/trans.json", expected = "en" }, - { path = "/path/to/locals/en-trans.json", expected = nil }, + { path = "/path/to/locals/en-trans.json", expected = "unknown" }, -- Test cases for language names with any case and separating characters. { path = "/path/to/locals/en-us/trans.json", expected = "en-us" },