Skip to content

Commit 36618cd

Browse files
committed
feat: support nested directory for tmpfile_format
1 parent 6208aef commit 36618cd

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

lua/conform/runner.lua

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -370,13 +370,48 @@ local function run_formatter(bufnr, formatter, config, ctx, input_lines, opts, c
370370

371371
if not config.stdin then
372372
log.debug("Creating temp file %s", ctx.filename)
373+
-- ctx.filename can contain directories relative to ctx.dirname
374+
-- Thus, we check which directories relative to ctx.dirname exist and remove
375+
-- the first one that does not exist.
376+
local res = vim
377+
.iter(
378+
vim.split(
379+
assert(
380+
vim.fs.relpath(ctx.dirname, ctx.filename),
381+
"filename " .. ctx.filename .. " is not a child of dirname " .. ctx.dirname
382+
),
383+
"/",
384+
{ plain = true }
385+
)
386+
)
387+
:rskip(1)
388+
:fold(
389+
{ path = ctx.dirname, found_not_exists = false },
390+
---@param path_part string
391+
function(acc, path_part)
392+
local new_path = vim.fs.joinpath(acc.path, path_part)
393+
if not acc.found_not_exists then
394+
acc.path = new_path
395+
end
396+
acc.found_not_exists = vim.fn.isdirectory(new_path) == 0
397+
return acc
398+
end
399+
)
400+
local dir_to_remove = res.path
401+
local can_remove = res.found_not_exists
402+
373403
vim.fn.mkdir(vim.fs.dirname(ctx.filename), "p")
374404
local fd = assert(uv.fs_open(ctx.filename, "w", 448)) -- 0700
375405
uv.fs_write(fd, buffer_text)
376406
uv.fs_close(fd)
377407
callback = util.wrap_callback(callback, function()
378408
log.debug("Cleaning up temp file %s", ctx.filename)
379409
uv.fs_unlink(ctx.filename)
410+
-- If all directories relative to ctx.dirname exist, there are no directories to remove.
411+
if can_remove then
412+
log.debug("Cleaning up temp dir %s", dir_to_remove)
413+
vim.fs.rm(dir_to_remove, { recursive = true })
414+
end
380415
end)
381416
end
382417

0 commit comments

Comments
 (0)