make_add_to_json.lua 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. local h = require("cspell.helpers")
  2. ---@class AddToJSONAction
  3. ---@field diagnostic Diagnostic
  4. ---@field word string
  5. ---@field params GeneratorParams
  6. ---@field cspell CSpellConfigInfo|nil
  7. ---@param opts AddToJSONAction
  8. ---@return CodeAction
  9. return function(opts)
  10. ---@type CSpellSourceConfig
  11. local code_action_config = opts.params:get_config()
  12. local on_success = code_action_config.on_success
  13. local encode_json = code_action_config.encode_json or vim.json.encode
  14. return {
  15. title = 'Add "' .. opts.word .. '" to cspell json file',
  16. action = function()
  17. local cspell = opts.cspell or h.create_cspell_json(opts.params)
  18. if not cspell.config.words then
  19. cspell.config.words = {}
  20. end
  21. table.insert(cspell.config.words, opts.word)
  22. local encoded = encode_json(cspell.config) or ""
  23. local lines = {}
  24. for line in encoded:gmatch("[^\r\n]+") do
  25. table.insert(lines, line)
  26. end
  27. vim.fn.writefile(lines, cspell.path)
  28. local handle = io.popen("pwd")
  29. local pwd = handle:read("a*")
  30. handle:close()
  31. local cspell_dir = os.getenv("HOME") .. "/.config/cspell/"
  32. vim.notify("dir" .. cspell_dir, vim.log.levels.INFO)
  33. local cc = os.execute("cd " .. cspell_dir)
  34. vim.notify("Created a new cspell.json file at " .. cc, vim.log.levels.INFO)
  35. local cc = os.execute("git add .")
  36. vim.notify("add" .. cc, vim.log.levels.INFO)
  37. local cc = os.execute("git commit -m 'word added'")
  38. vim.notify("comm" .. cc, vim.log.levels.INFO)
  39. local cc = os.execute("git push")
  40. vim.notify("push " .. cc, vim.log.levels.INFO)
  41. os.execute("cd " .. pwd)
  42. -- replace word in buffer to trigger cspell to update diagnostics
  43. h.set_word(opts.diagnostic, opts.word)
  44. if on_success then
  45. on_success(cspell.path, opts.params, "add_to_json")
  46. end
  47. end,
  48. }
  49. end