Tmp - Temporary directories that are monitored and automatically removed

I wanted a simple library that creates, monitors and auto removes temporary directories if the calling process dies or if the function that required the temporary directory finishes.

I haven’t found an existing library that matches these how I wanted so I created this library:

Usage:

Tmp.dir(fn tmp_dir_path -> 
  File.touch(Path.join(tmp_dir_path, "my_file"))
  # do more work here in tmp_dir_path 
end, options)`

Options:

  • :base_dir defaults to System.tmp_dir()
  • :dirname defaults to a random uid
  • :timeout defaults to :infinity

Feedback is welcome!

8 Likes

Very good, thank you. I have been using “briefly” from a github but it does look like author gave up maintaining it.

1 Like

I have published v0.1.2. The function is now called with an optional second argument if you want to keep the directory for debugging:

tmp_dir_path = 
  Tmp.dir(fn tmp_dir_path, keep ->
    keep.() # calling this function will keep the temporary directory
  
    tmp_dir_path
  end) 
# ... debugging

Nice work :wink: don’t you think it would be cleaner to have :keep as another option for Tmp.dir/2?

You mean by using it like Tmp.dir(fn _ -> ... end, keep: true)?

If that is the case I don’t think because I believe the main use case is that we want the directory to disappear and keeping it is something that we might decide during the function call for example when an error happens.

Tmp.dir(fn tmp_dir_path, keep ->
  try do
    ... work
  rescue
    exception ->
      keep.() # This will keep the directory for debugging
      reraise exception, __STACKTRACE__
  end
end)
2 Likes

It kept bothering me that this anonymous function wasn’t idiomatic Elixir so I removed it.

Now with v0.2.0 if the temporary directory should be kept one can simply:

Tmp.dir(fn tmp_dir_path ->
  # ...
  Tmp.keep()
end)

Calling Tmp.keep() demonitors the process so the directory won’t go away when the function finishes running and the GenServer process that runs it shuts down.

I have used this library in prod and processed binary files with over 10 million directories so on the next refactor I think I will release v1.0.0 and my goal is to keep it very simple so if somebody needs temporary directories in Elixir this small library can be used without any configuration.

3 Likes