modules.lua 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. local M = {}
  2. local Log = require "lvim.core.log"
  3. -- revisit this
  4. -- function prequire(package)
  5. -- local status, lib = pcall(require, package)
  6. -- if status then
  7. -- return lib
  8. -- else
  9. -- vim.notify("Failed to require '" .. package .. "' from " .. debug.getinfo(2).source)
  10. -- return nil
  11. -- end
  12. -- end
  13. local function _assign(old, new, k)
  14. local otype = type(old[k])
  15. local ntype = type(new[k])
  16. -- print("hi")
  17. if (otype == "thread" or otype == "userdata") or (ntype == "thread" or ntype == "userdata") then
  18. vim.notify(string.format("warning: old or new attr %s type be thread or userdata", k))
  19. end
  20. old[k] = new[k]
  21. end
  22. local function _replace(old, new, repeat_tbl)
  23. if repeat_tbl[old] then
  24. return
  25. end
  26. repeat_tbl[old] = true
  27. local dellist = {}
  28. for k, _ in pairs(old) do
  29. if not new[k] then
  30. table.insert(dellist, k)
  31. end
  32. end
  33. for _, v in ipairs(dellist) do
  34. old[v] = nil
  35. end
  36. for k, _ in pairs(new) do
  37. if not old[k] then
  38. old[k] = new[k]
  39. else
  40. if type(old[k]) ~= type(new[k]) then
  41. Log:debug(
  42. string.format("Reloader: mismatch between old [%s] and new [%s] type for [%s]", type(old[k]), type(new[k]), k)
  43. )
  44. _assign(old, new, k)
  45. else
  46. if type(old[k]) == "table" then
  47. _replace(old[k], new[k], repeat_tbl)
  48. else
  49. _assign(old, new, k)
  50. end
  51. end
  52. end
  53. end
  54. end
  55. M.require_clean = function(m)
  56. package.loaded[m] = nil
  57. _G[m] = nil
  58. local _, module = pcall(require, m)
  59. return module
  60. end
  61. M.require_safe = function(mod)
  62. local status_ok, module = pcall(require, mod)
  63. if not status_ok then
  64. local trace = debug.getinfo(2, "SL")
  65. local shorter_src = trace.short_src
  66. local lineinfo = shorter_src .. ":" .. (trace.currentline or trace.linedefined)
  67. local msg = string.format("%s : skipped loading [%s]", lineinfo, mod)
  68. Log:debug(msg)
  69. end
  70. return module
  71. end
  72. M.reload = function(mod)
  73. if not package.loaded[mod] then
  74. return M.require_safe(mod)
  75. end
  76. local old = package.loaded[mod]
  77. package.loaded[mod] = nil
  78. local new = M.require_safe(mod)
  79. if type(old) == "table" and type(new) == "table" then
  80. local repeat_tbl = {}
  81. _replace(old, new, repeat_tbl)
  82. end
  83. package.loaded[mod] = old
  84. return old
  85. end
  86. return M