From b2ecb15d7fd01b0a54f64896964f577f4c0d59e7 Mon Sep 17 00:00:00 2001 From: Dominik Polakovics Date: Thu, 12 Dec 2024 22:13:04 +0100 Subject: [PATCH] fix: check if file is text file before reading it --- lua/chatgpt_nvim/context.lua | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/lua/chatgpt_nvim/context.lua b/lua/chatgpt_nvim/context.lua index f26df99..7e750eb 100644 --- a/lua/chatgpt_nvim/context.lua +++ b/lua/chatgpt_nvim/context.lua @@ -31,6 +31,20 @@ local function should_ignore_file(file, ignore_patterns) return false end +local function is_text_file(file) + local fd = uv.fs_open(file, "r", 438) + if not fd then + return false + end + local chunk = uv.fs_read(fd, 1024, 0) or "" + uv.fs_close(fd) + -- Check for null bytes as a heuristic for binary files + if chunk:find("\0") then + return false + end + return true +end + local function scandir(dir, ignore_patterns, files) files = files or {} local fd = uv.fs_opendir(dir, nil, 50) @@ -41,7 +55,7 @@ local function scandir(dir, ignore_patterns, files) for _, ent in ipairs(ents) do local fullpath = dir .. "/" .. ent.name if not should_ignore_file(fullpath, ignore_patterns) then - if ent.type == "file" then + if ent.type == "file" and is_text_file(fullpath) then table.insert(files, fullpath) elseif ent.type == "directory" and ent.name ~= ".git" then scandir(fullpath, ignore_patterns, files)