# This file is a part of Julia. License is MIT: https://julialang.org/license

# This includes the `mkdepottempdir` and `rmdepot` functions, used to
# respectively create and remove temporary depots to use in tests.
# `mktempdir` and `rm` cannot be used because, on Windows, the DLLs generated by
# precompilation in the depots cannot be removed by the program that uses them.
# This file can be included multiple times in the same module if necessary,
# which can happen with unisolated test runs.

if Sys.iswindows() && !@isdefined(DEPOTS_TOREMOVE)
    const DEPOTS_TOREMOVE = String[]
    atexit(() -> Base.Filesystem.temp_cleanup_postprocess(DEPOTS_TOREMOVE))
end

function rmdepot(depot)
    try
        @static if Sys.iswindows() # on Windows, delay the rm
            push!(DEPOTS_TOREMOVE, depot)
        else # on the other systems, do it immediately
            rm(depot, force=true, recursive=true)
        end
    catch err
        @show err
    end
end

function mkdepottempdir(f::Function, parent=tempdir(); prefix="jltestdepot_")
    tmpdir = mktempdir(parent; prefix, cleanup=false)
    try
        f(tmpdir)
    finally
        rmdepot(tmpdir)
    end
end
function mkdepottempdir(parent=tempdir(); prefix="jltestdepot_", cleanup=true)
    @static if Sys.iswindows()
        tmpdir = mktempdir(parent; prefix, cleanup=false)
        cleanup && push!(DEPOTS_TOREMOVE, tmpdir)
        tmpdir
    else
        mktempdir(parent; prefix, cleanup)
    end
end
