irongit

A Neovim plugin enabling you to solve LeetCode problems.

80 lines1.9 KBLua
1---@module 'plenary'
2
3local log = require("leetcode.logger")
4local interpreter = require("leetcode.api.interpreter")
5local config = require("leetcode.config")
6local Judge = require("leetcode.logger.spinner.judge")
7
8---@type Path
9local leetbody = config.storage.cache:joinpath("body")
10leetbody:touch()
11
12---@class lc.Runner
13---@field question lc.ui.Question
14local Runner = {}
15Runner.__index = Runner
16
17Runner.running = false
18
19---@param self lc.Runner
20---@param submit boolean
21Runner.run = vim.schedule_wrap(function(self, submit)
22 if Runner.running then
23 return log.warn("Runner is busy")
24 end
25
26 local ok, err = pcall(Runner.handle, self, submit)
27 if not ok then
28 self:stop()
29 log.error(err)
30 end
31end)
32
33Runner.stop = function()
34 Runner.running = false
35end
36
37function Runner:handle(submit)
38 Runner.running = true
39 local question = self.question
40
41 local body = {
42 lang = question.lang,
43 typed_code = self.question:editor_submit_lines(submit),
44 question_id = question.q.id,
45 data_input = not submit and question.console.testcase:content(),
46 }
47
48 local judge = Judge:init()
49 local function callback(item, state, err)
50 if err or item then
51 self:stop()
52 end
53
54 if item then
55 if item._.success then
56 judge:success(item.status_msg)
57 else
58 judge:error(item.status_msg)
59 end
60 elseif state then
61 judge:from_state(state)
62 elseif err then
63 judge:error(err.msg or "Something went wrong")
64 end
65
66 if item then
67 question.console.result:handle(item)
68 end
69 end
70
71 leetbody:write(vim.json.encode(body), "w")
72 interpreter.run(submit, question, leetbody:absolute(), callback)
73end
74
75---@param question lc.ui.Question
76function Runner:init(question)
77 return setmetatable({ question = question }, self)
78end
79
80return Runner