293293--- @type table<string , boolean>
294294local last_run_errored = {}
295295
296+ --- Set of temporary directories to remove after formatting
297+ --- @type string[]
298+ local temp_dirs = {}
299+
296300--- @param bufnr integer
297301--- @param formatter conform.FormatterInfo
298302--- @param config conform.FormatterConfig
@@ -370,6 +374,16 @@ local function run_formatter(bufnr, formatter, config, ctx, input_lines, opts, c
370374
371375 if not config .stdin then
372376 log .debug (" Creating temp file %s" , ctx .filename )
377+ local current_parent_dir = vim .fs .dirname (ctx .filename )
378+ -- Keep track of the current parent directories created, so we can delete them later
379+ while
380+ current_parent_dir
381+ and current_parent_dir ~= ctx .dirname
382+ and vim .fn .isdirectory (current_parent_dir ) == 0
383+ do
384+ temp_dirs [# temp_dirs + 1 ] = current_parent_dir
385+ current_parent_dir = vim .fs .dirname (current_parent_dir )
386+ end
373387
374388 vim .fn .mkdir (vim .fs .dirname (ctx .filename ), " p" )
375389 local fd = assert (uv .fs_open (ctx .filename , " w" , 448 )) -- 0700
@@ -378,15 +392,22 @@ local function run_formatter(bufnr, formatter, config, ctx, input_lines, opts, c
378392 callback = util .wrap_callback (callback , function ()
379393 log .debug (" Cleaning up temp file %s" , ctx .filename )
380394 uv .fs_unlink (ctx .filename )
381- local current = vim . fs . dirname ( ctx . filename )
382- -- Remove empty directories from filename to dirname
383- while current and vim . startswith ( current , ctx . dirname ) and current ~= ctx . dirname do
384- log .debug (" Cleaning up temp dir %s" , current )
385- local success , err_name , err_msg = uv .fs_rmdir (current )
395+ local temp_dir_idx = 1
396+ while temp_dir_idx <= # temp_dirs do
397+ local temp_dir_to_remove = temp_dirs [ temp_dir_idx ]
398+ log .debug (" Cleaning up temp dir %s" , temp_dir_to_remove )
399+ local success , err_name , err_msg = uv .fs_rmdir (temp_dir_to_remove )
386400 if not success then
387- log .trace (" Failed to remove directory %s: %s: %s" , current , err_name , err_msg )
401+ log .debug (
402+ " Failed to remove temp directory %s: %s: %s" ,
403+ temp_dir_to_remove ,
404+ err_name ,
405+ err_msg
406+ )
407+ temp_dir_idx = temp_dir_idx + 1
408+ else
409+ table.remove (temp_dirs , temp_dir_idx )
388410 end
389- current = vim .fs .dirname (current )
390411 end
391412 end )
392413 end
0 commit comments