---@module 'snacks' local log = require("javelin.log") local Data = {} ---@type JavelinConfig local options local data_dir local data_cache = {} ---@param path string ---@return string local function hash_path(path) return vim.fn.sha256(vim.fn.resolve(path)) end ---@param root_path string local function get_data_file(root_path) return vim.fn.resolve(data_dir .. "/" .. hash_path(root_path)) end ---@param root_path string ---@param path string ---@return string local function normalize_path(root_path, path) root_path = root_path .. "/" if vim.startswith(path, root_path) then return path:sub(#root_path + 1) end return path end ---@param root_path string ---@param list string[] ---@return string[] local function normalize_list(root_path, list) local new_list = {} for _, path in ipairs(list) do if path ~= "" then table.insert(new_list, path) end end for i, path in ipairs(new_list) do new_list[i] = normalize_path(root_path, path) end return new_list end ---@param root_path string local function load(root_path) local data_file = get_data_file(root_path) if not vim.uv.fs_stat(data_file) then return {} end return normalize_list(root_path, vim.fn.readfile(data_file)) end ---@param root_path string local function write(root_path) vim.fn.writefile(Data.get_list(root_path), get_data_file(root_path)) end ---@param root_path string ---@param path string local function add_path(root_path, path) local list = Data.get_list(root_path) path = normalize_path(root_path, vim.fn.fnamemodify(path, ":~")) if vim.tbl_contains(list, path) then log.warn("File already in list: " .. path) return end table.insert(list, path) write(root_path) end ---@param root_path string ---@return string[] function Data.get_list(root_path) local hash = hash_path(root_path) if data_cache[hash] == nil then data_cache[hash] = load(root_path) end return data_cache[hash] end ---@return string[] function Data.get_current() return Data.get_list(Data.get_root()) end function Data.add_current() local filename = vim.api.nvim_buf_get_name(0) local buftype = vim.api.nvim_get_option_value("buftype", { buf = 0 }) if filename ~= "" and buftype == "" then add_path(Data.get_root(), filename) else log.warn("Cannot add this buffer") end end ---@param root_path string ---@param lines string[] function Data.update(root_path, lines) data_cache[hash_path(root_path)] = normalize_list(root_path, lines) write(root_path) end ---@return string function Data.get_root() local root = vim.fn.getcwd() if options.use_git_root then local git_root = Snacks.git.get_root(root) if git_root then root = git_root end end return vim.fn.fnamemodify(root, ":~") end function Data.setup(opt) options = opt data_dir = vim.fn.resolve(vim.fn.stdpath("data") .. "/javelin") if not vim.uv.fs_stat(data_dir) then vim.uv.fs_mkdir(data_dir, tonumber("755", 8)) end end return Data