refactor: less code for cache

This commit is contained in:
Folke Lemaitre 2022-11-25 22:49:21 +01:00
parent cfc39330dc
commit 80a2b71a09
No known key found for this signature in database
GPG Key ID: 41F8B1FBACAE2040
1 changed files with 8 additions and 22 deletions

View File

@ -1,14 +1,13 @@
-- Simple string cache with fast saving and loading from file -- Simple string cache with fast saving and loading from file
local M = {} local M = {}
local cache_path = vim.fn.stdpath("state") .. "/lazy/plugins.state" M.dirty = false
---@type string
local cache_hash = nil
local dirty = false
local cache_path = vim.fn.stdpath("state") .. "/lazy.state"
---@type string
local cache_hash = ""
---@type table<string,boolean> ---@type table<string,boolean>
local used = {} local used = {}
---@type table<string,string> ---@type table<string,string>
local cache = {} local cache = {}
@ -23,24 +22,12 @@ end
function M.set(key, value) function M.set(key, value)
cache[key] = value cache[key] = value
used[key] = true used[key] = true
dirty = true M.dirty = true
end end
function M.del(key) function M.del(key)
cache[key] = nil cache[key] = nil
dirty = true M.dirty = true
end
function M.dirty()
dirty = true
end
function M.use(pattern)
for key, _ in pairs(cache) do
if key:find(pattern) then
used[key] = true
end
end
end end
function M.hash(file) function M.hash(file)
@ -56,7 +43,7 @@ function M.setup()
callback = function() callback = function()
vim.api.nvim_create_autocmd("VimLeavePre", { vim.api.nvim_create_autocmd("VimLeavePre", {
callback = function() callback = function()
if dirty then if M.dirty then
local hash = M.hash(cache_path) local hash = M.hash(cache_path)
-- abort when the file was changed in the meantime -- abort when the file was changed in the meantime
if hash == nil or cache_hash == hash then if hash == nil or cache_hash == hash then
@ -70,10 +57,9 @@ function M.setup()
end end
function M.save() function M.save()
require("lazy.core.state").save() require("lazy.core.plugin").save()
require("lazy.core.module").save() require("lazy.core.module").save()
vim.fn.mkdir(vim.fn.fnamemodify(cache_path, ":p:h"), "p")
local f = assert(io.open(cache_path, "wb")) local f = assert(io.open(cache_path, "wb"))
for key, value in pairs(cache) do for key, value in pairs(cache) do
if used[key] then if used[key] then