let bracket_tmpdir ?(prefix="ounit-") ?(suffix=".dir") test_ctxt =
let max_attempt = 10 in
let rec try_hard_mkdir attempt =
if max_attempt = attempt then begin
OUnitUtils.failwithf
"Unable to create temporary directory after %d attempts."
attempt
end else begin
try
let suffix = "-"^(OUnitTest.get_shard_id test_ctxt)^suffix in
let tmpdn = Filename.temp_file prefix suffix in
Sys.remove tmpdn;
Unix.mkdir tmpdn 0o755;
tmpdn
with Unix.Unix_error (Unix.EEXIST, "mkdir", _) ->
try_hard_mkdir (max_attempt + 1)
end
in
create
(fun test_ctxt ->
let tmpdn = try_hard_mkdir 0 in
logf test_ctxt.test_logger `Info
"Create a temporary directory: %S." tmpdn;
tmpdn)
(fun tmpdn test_ctxt ->
let log_delete fn =
logf test_ctxt.test_logger `Info
"Delete in a temporary directory: %S." fn
in
let safe_run f a = try f a with _ -> () in
let rec rmdir fn =
Array.iter
(fun bn ->
let fn' = Filename.concat fn bn in
let is_dir = try Sys.is_directory fn' with _ -> false in
if is_dir then begin
rmdir fn';
safe_run Unix.rmdir fn';
log_delete fn'
end else begin
safe_run Sys.remove fn';
log_delete fn'
end)
(try Sys.readdir fn with _ -> [||])
in
rmdir tmpdn;
safe_run Unix.rmdir tmpdn;
log_delete tmpdn)
test_ctxt