Skip to content

Commit

Permalink
refactor(context): replace io.popen with vim.system
Browse files Browse the repository at this point in the history
Replace synchronous io.popen git diff call with asynchronous vim.system in
context.lua. Add async scheduler to token fetching and introduce a new utils
helper for system calls.

This change improves overall plugin performance by making git operations
asynchronous and following Neovim's best practices for system calls.
  • Loading branch information
deathbeam committed Nov 27, 2024
1 parent ebd40d1 commit 40eb801
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 13 deletions.
24 changes: 11 additions & 13 deletions lua/CopilotChat/context.lua
Original file line number Diff line number Diff line change
Expand Up @@ -353,25 +353,23 @@ end
function M.gitdiff(type, winnr)
type = type or 'unstaged'
local cwd = utils.win_cwd(winnr)
local cmd = 'git -C ' .. cwd .. ' diff --no-color --no-ext-diff'
local cmd = {
'git',
'-C',
cwd,
'diff',
'--no-color',
'--no-ext-diff',
}

if type == 'staged' then
cmd = cmd .. ' --staged'
end

local handle = io.popen(cmd)
if not handle then
return nil
table.insert(cmd, '--staged')
end

local result = handle:read('*a')
handle:close()
if not result or result == '' then
return nil
end
local out = utils.system(cmd)

return {
content = result,
content = out.stdout,
filename = 'git_diff_' .. type,
filetype = 'diff',
}
Expand Down
3 changes: 3 additions & 0 deletions lua/CopilotChat/copilot.lua
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
---@field model string?
---@field chunk_size number?

local async = require('plenary.async')
local log = require('plenary.log')
local prompts = require('CopilotChat.prompts')
local tiktoken = require('CopilotChat.tiktoken')
Expand Down Expand Up @@ -50,6 +51,8 @@ local VERSION_HEADERS = {
--- Get the github oauth cached token
---@return string|nil
local function get_cached_token()
async.util.scheduler()

-- loading token from the environment only in GitHub Codespaces
local token = os.getenv('GITHUB_TOKEN')
local codespaces = os.getenv('CODESPACES')
Expand Down
6 changes: 6 additions & 0 deletions lua/CopilotChat/utils.lua
Original file line number Diff line number Diff line change
Expand Up @@ -305,4 +305,10 @@ M.read_file = function(path)
return data
end

--- Call a system command
---@param cmd table The command
M.system = async.wrap(function(cmd, callback)
vim.system(cmd, { text = true }, callback)
end, 2)

return M

0 comments on commit 40eb801

Please sign in to comment.