1
0
Fork 0

sqlformat: fix text insertion and job handling

This commit is contained in:
Felipe 2023-11-21 11:39:42 -03:00
parent 4334999ca0
commit 8a6420bf92
Signed by: pitbuster
SSH key fingerprint: SHA256:HDYu2Pm4/TmSX8GBwV49UvFWr1Ljg8XlHxKeCpjJpOk

View file

@ -1,22 +1,23 @@
local run_formatter = function(text) local run_formatter = function(text)
vim.notify(text) local inner_text = string.sub(text, 4, -3)
vim.notify("----") local job_result = require("plenary.job"):new({
local result = {}
require("plenary.job"):new({
command = "sqlfluff", command = "sqlfluff",
cwd = "/usr/bin",
args = { "format", "-" }, args = { "format", "-" },
writer = text, writer = inner_text,
on_stdout = function(_, line)
table.insert(result, line)
end,
}):sync() }):sync()
if job_result == nil then
return nil
end
-- add the surrounding r#"..."# back -- add the surrounding r#"..."# back
for _, line in ipairs(result) do if #job_result == 1 then
vim.notify(line) return { "r#\"" .. job_result[1] .. "#\"" }
end end
-- table.insert(result, "\"#") local result = { "r#\"" }
for _, line in ipairs(job_result) do
table.insert(result, line)
end
table.insert(result, "\"#")
return result return result
end end
@ -28,9 +29,7 @@ local embedded_sql = vim.treesitter.query.parse(
path: (identifier) @path (#eq? @path "sqlx") path: (identifier) @path (#eq? @path "sqlx")
name: (identifier) @name (#any-of? @name "query" "query_scalar" "query_as")) name: (identifier) @name (#any-of? @name "query" "query_scalar" "query_as"))
(token_tree (token_tree (raw_string_literal) @sql)
(raw_string_literal) @sql)
(#offset! @sql 0 3 0 -2)
) )
]] ]]
) )
@ -60,21 +59,35 @@ local format = function(bufnr)
local indentation = string.rep(" ", range[2]) local indentation = string.rep(" ", range[2])
-- run the formatter on the node text -- run the formatter on the node text
local formatted = run_formatter(vim.treesitter.get_node_text(node, bufnr)) local formatted = run_formatter(vim.treesitter.get_node_text(node, bufnr))
if formatted == nil then
goto continue
end
-- add indentation -- add indentation
for idx, line in ipairs(formatted) do for idx, line in ipairs(formatted) do
formatted[idx] = indentation .. line if idx > 1 then
formatted[idx] = indentation .. line
end
end end
-- add changes in reverse order -- add changes in reverse order
table.insert(changes, 1, { table.insert(changes, 1, {
start = range[1], start_row = range[1],
final = range[3], start_col = range[2],
end_row = range[3],
end_col = range[4],
formatted = formatted, formatted = formatted,
}) })
::continue::
end end
end end
for _, change in ipairs(changes) do for _, change in ipairs(changes) do
vim.api.nvim_buf_set_lines(bufnr, change.start, change.final, false, change.formatted) vim.api.nvim_buf_set_text(
bufnr,
change.start_row,
change.start_col,
change.end_row,
change.end_col,
change.formatted)
end end
end end