fix(util): ensure unique cache keys in LazyVim.memoize (#3576)

## What is this PR for?

This PR fixes a bug in the `LazyVim.memoize` function that was causing
unexpected behavior in my configuration. The issue was discovered when
setting `vim.g.lazyvim_prettier_needs_config = true` in my
`lua/config/options.lua`, which did not work as expected.

The root cause was an issue with `LazyVim.memoize` cache key generation,
which led to `M.has_config(ctx)` always returning the same result as
`M.has_parser(ctx)`. This happened because `LazyVim.memoize` generates
cache keys based on the function parameters, and both functions were
being called with identical parameters:


7d30360df2/lua/lazyvim/plugins/extras/formatting/prettier.lua (L77-L81)

By improving the cache key generation to include function information,
we can ensure unique keys for different functions even if their
parameters are identical, thereby fixing the issue.

## Does this PR fix an existing issue?

N/A

## Checklist

- [x] I've read the
[CONTRIBUTING](https://github.com/LazyVim/LazyVim/blob/main/CONTRIBUTING.md)
guidelines.
This commit is contained in:
Aofei Sheng
2024-06-11 12:41:37 +08:00
committed by GitHub
parent 7d30360df2
commit 335487282a

View File

@ -274,8 +274,10 @@ local cache = {} ---@type table<string, any>
---@param fn T
---@return T
function M.memoize(fn)
local info = debug.getinfo(fn, "S")
local keyprefix = info.source .. ":" .. info.linedefined .. ":"
return function(...)
local key = vim.inspect({ ... })
local key = keyprefix .. vim.inspect({ ... })
if cache[key] == nil then
cache[key] = fn(...)
end