]> git.lizzy.rs Git - micro.git/blob - runtime/plugins/linter/linter.lua
Use shell to parse command when using JobStart
[micro.git] / runtime / plugins / linter / linter.lua
1 if GetOption("linter") == nil then
2     AddOption("linter", true)
3 end
4
5 MakeCommand("lint", "linter.lintCommand", 0)
6
7 function lintCommand()
8     CurView():Save(false)
9     runLinter()
10 end
11
12 function runLinter()
13     local ft = CurView().Buf:FileType()
14     local file = CurView().Buf.Path
15     local devnull = "/dev/null"
16     local temp = os.getenv("TMPDIR")
17     if OS == "windows" then
18         devnull = "NUL"
19         temp = os.getenv("TEMP")
20     end
21     if ft == "go" then
22         lint("gobuild", "go", {"build", "-o", devnull}, "%f:%l: %m")
23         lint("golint", "golint", {CurView().Buf.Path}, "%f:%l:%d+: %m")
24     elseif ft == "lua" then
25         lint("luacheck", "luacheck", {"--no-color", file}, "%f:%l:%d+: %m")
26     elseif ft == "python" then
27         lint("pyflakes", "pyflakes", {file}, "%f:%l:.-:? %m")
28     elseif ft == "c" then
29         lint("gcc", "gcc", {"-fsyntax-only", "-Wall", "-Wextra", file}, "%f:%l:%d+:.+: %m")
30     elseif ft == "d" then
31         lint("dmd", "dmd", {"-color=off", "-o-", "-w", "-wi", "-c", file}, "%f%(%l%):.+: %m")
32     elseif ft == "java" then
33         lint("javac", "javac", {"-d", temp, file}, "%f:%l: error: %m")
34     elseif ft == "javascript" then
35         lint("jshint", "jshint", {file}, "%f: line %l,.+, %m")
36     end
37 end
38
39 function onSave(view)
40     if GetOption("linter") then
41         runLinter()
42     else
43         CurView():ClearAllGutterMessages()
44     end
45 end
46
47 function lint(linter, cmd, args, errorformat)
48     CurView():ClearGutterMessages(linter)
49
50     JobSpawn(cmd, args, "", "", "linter.onExit", linter, errorformat)
51 end
52
53 function onExit(output, linter, errorformat)
54     local lines = split(output, "\n")
55
56     local regex = errorformat:gsub("%%f", "(..-)"):gsub("%%l", "(%d+)"):gsub("%%m", "(.+)")
57     for _,line in ipairs(lines) do
58         -- Trim whitespace
59         line = line:match("^%s*(.+)%s*$")
60         if string.find(line, regex) then
61             local file, line, msg = string.match(line, regex)
62             if basename(CurView().Buf.Path) == basename(file) then
63                 CurView():GutterMessage(linter, tonumber(line), msg, 2)
64             end
65         end
66     end
67 end
68
69 function split(str, sep)
70     local result = {}
71     local regex = ("([^%s]+)"):format(sep)
72     for each in str:gmatch(regex) do
73         table.insert(result, each)
74     end
75     return result
76 end
77
78 function basename(file)
79     local name = string.gsub(file, "(.*/)(.*)", "%2")
80     return name
81 end