temporary

Types

pub opaque type TempFile

Functions

pub fn create(
  temp_file: TempFile,
  run fun: fn(String) -> a,
) -> Result(a, FileError)

Creates a temporary file and runs the given function passing it the full path to that file.

Returns the result of the function wrapped in Ok, or Error wrapping a simplifile.FileError if the file could not be created.

In any case, any temporary file will automatically be deleted!

Examples

To create a default temporary file:

pub fn main() {
  use file <- temporary.create(temporary.file())
  let assert Ok(_) = simplifile.write("Hello!", to: file)
}

You can even create more complex temporary directories with temporary files inside:

pub fn main() {
  use dir <- temporary.create(temporary.directory())
  let file = temporary.file() |> temporary.in_directory(dir)
  use file <- temporary.create(file)
  //  ^^^^ `file` will be under the `dir` temporary directory!

  let assert Ok(_) = simplifile.write("Hello!", to: file)
}
pub fn directory() -> TempFile

The description of a new default temporary directory.

It can be customised using the set_prefix, set_suffix or in_directory functions.

pub fn file() -> TempFile

The description of a new default temporary file.

It can be customised using the set_prefix, set_suffix or in_directory functions.

pub fn in_directory(
  temp_file: TempFile,
  directory: String,
) -> TempFile

Set the directory the random file is going to be placed into. If this value is not set, the system’s default temp directory is picked, searching in the following order:

  1. The value of the TMPDIR environment variable, if it is set
  2. The value of the TEMP environment variable, if it is set
  3. The value of the TMP environment variable, if it is set
  4. C:\TMP on Windows or /tmp on Unix-like operating systems

Examples

If you don’t want to put the temporary file under the system’s default temp directory you can set your own:

temporary.file()
|> temporary.in_directory("/Users/me/custom_temp_dir")
pub fn with_prefix(
  temp_file: TempFile,
  name_prefix: String,
) -> TempFile

Set a fixed prefix that is going to be added to the temporary file’s name.

Examples

temporary.file()
|> temporary.with_prefix("wibble")
|> temporary.create(fn(file) {
  // The temporary file will have a random
  // name that starts with `wibble`.
})
pub fn with_suffix(
  temp_file: TempFile,
  name_suffix: String,
) -> TempFile

Set a fixed suffix that is going to be added to the temporary file’s name.

Examples

temporary.file()
|> temporary.with_suffix("wibble")
|> temporary.create(fn(file) {
  // The temporary file will have a random name
  // that ends with `wibble`.
})

Search Document