reload.lua 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. local M = {}
  2. -- revisit this
  3. -- function prequire(package)
  4. -- local status, lib = pcall(require, package)
  5. -- if status then
  6. -- return lib
  7. -- else
  8. -- vim.notify("Failed to require '" .. package .. "' from " .. debug.getinfo(2).source)
  9. -- return nil
  10. -- end
  11. -- end
  12. local function _assign(old, new, k)
  13. local otype = type(old[k])
  14. local ntype = type(new[k])
  15. -- print("hi")
  16. if (otype == "thread" or otype == "userdata") or (ntype == "thread" or ntype == "userdata") then
  17. vim.notify(string.format("warning: old or new attr %s type be thread or userdata", k))
  18. end
  19. old[k] = new[k]
  20. end
  21. local function _replace(old, new, repeat_tbl)
  22. if repeat_tbl[old] then
  23. return
  24. end
  25. repeat_tbl[old] = true
  26. local dellist = {}
  27. for k, _ in pairs(old) do
  28. if not new[k] then
  29. table.insert(dellist, k)
  30. end
  31. end
  32. for _, v in ipairs(dellist) do
  33. old[v] = nil
  34. end
  35. for k, _ in pairs(new) do
  36. if not old[k] then
  37. old[k] = new[k]
  38. else
  39. if type(old[k]) ~= type(new[k]) then
  40. vim.notify(string.format("warning: attr %s old type no equal new type!!!", k))
  41. _assign(old, new, k)
  42. else
  43. if type(old[k]) == "table" then
  44. _replace(old[k], new[k], repeat_tbl)
  45. else
  46. _assign(old, new, k)
  47. end
  48. end
  49. end
  50. end
  51. end
  52. M.reload = function(mod)
  53. if not package.loaded[mod] then
  54. local m = require(mod)
  55. return m
  56. end
  57. -- vim.notify "begin reload!!!"
  58. local old = package.loaded[mod]
  59. package.loaded[mod] = nil
  60. local new = require(mod)
  61. if type(old) == "table" and type(new) == "table" then
  62. -- vim.notify "pick object in new module to old module!!!"
  63. local repeat_tbl = {}
  64. _replace(old, new, repeat_tbl)
  65. end
  66. package.loaded[mod] = old
  67. -- vim.notify "finish reload!!!"
  68. return old
  69. end
  70. return M