feat: support cmd: loading api keys for google search APIs (#1532)
refactor environment loading logic into Utils and use it for existing provider loading, and web search where appropriate.
This commit is contained in:
64
lua/avante/utils/environment.lua
Normal file
64
lua/avante/utils/environment.lua
Normal file
@@ -0,0 +1,64 @@
|
||||
local Utils = require("avante.utils")
|
||||
|
||||
---@class avante.utils.environment
|
||||
local M = {}
|
||||
|
||||
---@private
|
||||
---@type table<string, string>
|
||||
M.cache = {}
|
||||
|
||||
---Parse environment variable using optional cmd: feature with an override fallback
|
||||
---@param key_name string
|
||||
---@param override? string
|
||||
---@return string | nil
|
||||
function M.parse(key_name, override)
|
||||
if key_name == nil then error("Requires key_name") end
|
||||
|
||||
local cache_key = type(key_name) == "table" and table.concat(key_name, "__") or key_name
|
||||
|
||||
if M.cache[cache_key] ~= nil then return M.cache[cache_key] end
|
||||
|
||||
local cmd = type(key_name) == "table" and key_name or key_name:match("^cmd:(.*)")
|
||||
|
||||
local value = nil
|
||||
|
||||
if cmd ~= nil then
|
||||
if override ~= nil and override ~= "" then
|
||||
value = os.getenv(override)
|
||||
if value ~= nil then
|
||||
M.cache[cache_key] = value
|
||||
return value
|
||||
end
|
||||
end
|
||||
|
||||
if type(cmd) == "string" then cmd = vim.split(cmd, " ", { trimempty = true }) end
|
||||
|
||||
Utils.debug("running command:", cmd)
|
||||
local exit_codes = { 0 }
|
||||
local ok, job_or_err = pcall(vim.system, cmd, { text = true }, function(result)
|
||||
Utils.debug("command result:", result)
|
||||
local code = result.code
|
||||
local stderr = result.stderr or ""
|
||||
local stdout = result.stdout and vim.split(result.stdout, "\n") or {}
|
||||
if vim.tbl_contains(exit_codes, code) then
|
||||
value = stdout[1]
|
||||
M.cache[cache_key] = value
|
||||
else
|
||||
Utils.error("failed to get key: (error code" .. code .. ")\n" .. stderr, { once = true, title = "Avante" })
|
||||
end
|
||||
end)
|
||||
|
||||
if not ok then
|
||||
Utils.error("failed to run command: " .. cmd .. "\n" .. job_or_err)
|
||||
return
|
||||
end
|
||||
else
|
||||
value = os.getenv(key_name)
|
||||
end
|
||||
|
||||
if value ~= nil then M.cache[cache_key] = value end
|
||||
|
||||
return value
|
||||
end
|
||||
|
||||
return M
|
||||
@@ -9,6 +9,7 @@ local lsp = vim.lsp
|
||||
---@field root avante.utils.root
|
||||
---@field file avante.utils.file
|
||||
---@field history avante.utils.history
|
||||
---@field environment avante.utils.environment
|
||||
local M = {}
|
||||
|
||||
setmetatable(M, {
|
||||
|
||||
Reference in New Issue
Block a user