Skip to content

Commit

Permalink
xapi-storage-script: create directories tail-recursively
Browse files Browse the repository at this point in the history
Avoid blowing up the stack when creating directories recursively

Signed-off-by: Pau Ruiz Safont <[email protected]>
  • Loading branch information
psafont committed Dec 18, 2023
1 parent fdbeb0b commit f661804
Showing 1 changed file with 18 additions and 14 deletions.
32 changes: 18 additions & 14 deletions ocaml/xapi-storage-script/main.ml
Original file line number Diff line number Diff line change
Expand Up @@ -112,20 +112,24 @@ module Sys = struct
List.filter (function "." | ".." -> false | _ -> true) listing
|> Lwt.return

let rec mkdir_p ?(perm = 0o755) path =
file_kind ~follow_symlinks:false path >>= function
| Directory ->
Lwt.return_unit
| Regular | Other | Unknown ->
let msg =
Printf.sprintf
{|Could not create directory "%s": already exists and it's not a directory|}
path
in
Lwt.fail (Failure msg)
| Missing ->
let parent = Filename.dirname path in
mkdir_p ~perm parent >>= fun () -> Lwt_unix.mkdir path perm
let mkdir_p ?(perm = 0o755) path =
let rec loop acc path =
file_kind ~follow_symlinks:false path >>= function
| Directory ->
(* create directories, parents first *)
Lwt_list.iter_s (fun f -> f ()) acc
| Regular | Other | Unknown ->
let msg =
Printf.sprintf
{|Could not create directory "%s": already exists and it's not a directory|}
path
in
Lwt.fail (Failure msg)
| Missing ->
let parent = Filename.dirname path in
loop ((fun () -> Lwt_unix.mkdir path perm) :: acc) parent
in
loop [] path
end

module Signal = struct
Expand Down

0 comments on commit f661804

Please sign in to comment.