refactor & fix: improve libraries initialization (#921)

* refactor(libs): extract libraries initialization

Extract initialization logic into separate functions
for better error handling and reusability.

* fix(libs): improve core libraries init

This change helps prevent runtime errors from uninitialized libraries.
This commit is contained in:
Alexander Muratov
2024-12-13 20:00:43 +05:00
committed by GitHub
parent b102f673c4
commit eb1bc657a1
3 changed files with 67 additions and 31 deletions

View File

@@ -15,16 +15,23 @@ local repo_map_lib = nil
---@class avante.utils.repo_map
local RepoMap = {}
function RepoMap.setup()
vim.defer_fn(function()
local ok, core = pcall(require, "avante_repo_map")
if not ok then
error("Failed to load avante_repo_map")
return
end
---@return AvanteRepoMap|nil
function RepoMap._init_repo_map_lib()
if repo_map_lib ~= nil then
return repo_map_lib
end
if repo_map_lib == nil then repo_map_lib = core end
end, 1000)
local ok, core = pcall(require, "avante_repo_map")
if not ok then
return nil
end
repo_map_lib = core
return repo_map_lib
end
function RepoMap.setup()
vim.defer_fn(RepoMap._init_repo_map_lib, 1000)
end
function RepoMap.get_ts_lang(filepath)
@@ -51,12 +58,13 @@ function RepoMap._build_repo_map(project_root, file_ext)
local negate_patterns = vim.list_extend(gitignore_negate_patterns, Config.repo_map.negate_patterns)
local filepaths = Utils.scan_directory(project_root, ignore_patterns, negate_patterns)
if filepaths and not RepoMap._init_repo_map_lib() then
-- or just throw an error if we don't want to execute request without codebase
Utils.error("Failed to load avante_repo_map")
return
end
vim.iter(filepaths):each(function(filepath)
if not Utils.is_same_file_ext(file_ext, filepath) then return end
if not repo_map_lib then
Utils.error("Failed to load avante_repo_map")
return
end
local filetype = RepoMap.get_ts_lang(filepath)
local definitions = filetype
and repo_map_lib.stringify_definitions(filetype, Utils.file.read_content(filepath) or "")