Skip to content

Commit

Permalink
Add ExUnit.Callbacks.tmp_dir!/0
Browse files Browse the repository at this point in the history
  • Loading branch information
wojtekmach committed Jun 27, 2020
1 parent fb4474d commit 4c39954
Showing 1 changed file with 29 additions and 0 deletions.
29 changes: 29 additions & 0 deletions lib/ex_unit/lib/ex_unit/callbacks.ex
Expand Up @@ -598,4 +598,33 @@ defmodule ExUnit.Callbacks do
end
end
end

@doc """
Lazily creates a temporary directory for the current process.
Returns path to the temporary directory.
"""
def tmp_dir!() do
key = __MODULE__

if path = Process.get(key) do
path
else
{:current_stacktrace, stacktrace} = Process.info(self(), :current_stacktrace)
{module, function, _, _} = Enum.at(stacktrace, 2)
path = Path.join(["tmp", escape_path(inspect(module)), escape_path(to_string(function))])
File.rm_rf!(path)
File.mkdir_p!(path)
Process.put(key, path)
path
end
end

defp escape_path(path) do
case :os.type() do
{:win32, _} -> String.replace(path, ~R'[~#%&*{}\\:<>?/+|"]', "_")
_ -> path
end
|> String.replace("/", "_")
end
end

0 comments on commit 4c39954

Please sign in to comment.