Temporary directory management for Rust

Related tags

Filesystem tempdir
Overview

tempdir

A Rust library for creating a temporary directory and deleting its entire contents when the directory is dropped.

Build Status Build status

Documentation

Deprecation Note

The tempdir crate is being merged into tempfile and is available in 3.x. Please direct new issues and pull requests to tempfile.

Usage

Add this to your Cargo.toml:

[dependencies]
tempdir = "0.3"

and this to your crate root:

extern crate tempdir;

Example

This sample method does the following:

  1. Create a temporary directory in the default location with the given prefix.
  2. Determine a file path in the directory and print it out.
  3. Create a file inside the temp folder.
  4. Write to the file and sync it to disk.
  5. Close the directory, deleting the contents in the process.
use std::io::{self, Write};
use std::fs::File;
use tempdir::TempDir;

fn write_temp_folder_with_files() -> io::Result<()> {
    let dir = TempDir::new("my_directory_prefix")?;
    let file_path = dir.path().join("foo.txt");
    println!("{:?}", file_path);

    let mut f = File::create(file_path)?;
    f.write_all(b"Hello, world!")?;
    f.sync_all()?;
    dir.close()?;

    Ok(())
}

Note: Closing the directory is actually optional, as it would be done on drop. The benefit of closing here is that it allows possible errors to be handled.

Comments
  • Design question: why support just dirs and not files?

    Design question: why support just dirs and not files?

    I'm curious about the reasons for focusing specifically on temp dirs and not temp files. Are there security benefits to always using a dir? Or simplicity/portability benefits? Asking out of historical interest more than anything else. (Apologies if this is an abuse of issues :) )

    opened by oconnor663 16
  • Deprecate the tempdir crate

    Deprecate the tempdir crate

    In https://github.com/Stebalien/tempfile/pull/33 we combined the tempdir and tempfile APIs, with the goal of using the tempfile crate as the source of temporary files and directories going forward.

    I've gone through and review the open issues here (and basically just closed them all). I think the next step is to propose deprecating this repository and moving into rust-lang-deprecated, with a note in the readme that tempfile is the place to go for temporary directories going forward.

    What do you all think? Is there anything else we should consider?

    opened by KodrAus 11
  • option to keep a temporary directory after panic, for debugging purposes

    option to keep a temporary directory after panic, for debugging purposes

    Suppose that I have some code which works inside of a temp dir, and a bug is detected which causes it to panic. When this occurs, I would like to be able to go look at the temporary directory and inspect the files created leading up to the error. However, during the panic, it will invariably have unwound through the TempDir destructor, and so the directory is gone.

    Currently the only real solution I have is to write all of my temp dir construction like this:

    let tmp = TempDir::new("my-thing");
    let tmp = tmp.path();
    

    and then after a crash occurs, I find the line for the pertinent temp dir, change path to into_path, and then try to reproduce the crash. I don't think this strategy will scale very well.

    opened by ExpHP 9
  • Publish New Version

    Publish New Version

    This is just a request for a new version of tempdir to be published with the updated version of rand (from https://github.com/rust-lang-nursery/tempdir/pull/40).

    opened by cramertj 5
  • deprecate into_path(), rename persist()

    deprecate into_path(), rename persist()

    Feature Request

    This is a feature/API change request to rename into_path() to persist(), while deprecating into_path().

    Reasoning

    While I understand the logic behind calling it into_path() (since it "converts" the temporary directory into an "ordinary path"), into_path() actually performs an action from the programmers point of view, namely it removes the invariant that the temporary directory will be deleted on drop.

    This is made even more confusing by the documentation, which says: "This destroys the TempDir without deleting the directory represented by the returned Path." -- from a lingual point of view it sounds like we are destroying the directory

    Solution

    /// Consumes the `TempDir` object without deleting the directory, 
    /// returning the `PathBuf` where it is located.
    ///
    /// The directory will no longer be automatically deleted.
    fn persist(self) -> PathBuf { self.into_path() }
    
    opened by vitiral 4
  • Library evaluation tracking issue

    Library evaluation tracking issue

    opened by brson 4
  • Support randomly-named directories

    Support randomly-named directories

    When writing tests that need a working directly I've used randomly-named directories a lot. The Python equivalent of tempdir does that by default. I was thinking of the addition of tempdir::new_unique() that would generate a new unique temporary directory.

    opened by Susurrus 3
  • Support ramfs through type `RamDir`

    Support ramfs through type `RamDir`

    I'm curious whether tempdir would be interested in adding a RamDir type if it were possible to make such a type.

    tmpfs is:

    tmpfs is a temporary filesystem that resides in memory and/or swap partition(s). Mounting directories as tmpfs can be an effective way of speeding up accesses to their files, or to ensure that their contents are automatically cleared upon reboot.

    It looks like there is a (linux only) libmount that could be leveraged to do the job, although I would prefer using ramfs, as it is guaranteed to be in ram. I haven't looked at that crate, but ramfs could potentially be added there.

    It's also at least theoretically possible to support windows, as a tool exists called ImDisk, but this issue is suggesting unix-only support through the tmpfs call (for now).

    This issue is mostly to ask whether this feature would be supported by the project devs or whether a new crate should be made instead. Thanks!

    opened by vitiral 2
  • path to 1.0

    path to 1.0

    Ive been going through our dependencies and I saw that this crate is pre-1.0 and also didn't have a tracking issue for getting there. I wanted to post this to see if there was a plan for getting to 1.0. Considering how few issues have been posted with this crate and how often it's used, I'd think it would be pretty close to a 1.0, so wanted to check in here to see what the maintainers think.

    opened by Susurrus 2
  • Unnecessary Option in TempDir or panicky code

    Unnecessary Option in TempDir or panicky code

    TempDir currently looks like this:

    pub struct TempDir {
        path: Option<PathBuf>,
    }
    

    And functions rely on it being an Option, ex:

    pub fn path(&self) -> &path::Path {
        self.path.as_ref().unwrap()
    }
    // and
    pub fn into_path(mut self) -> PathBuf {
        self.path.take().unwrap()
    }
    

    These functions do not take into consideration that the path could be set to None. Currently this is not a problem because fn new_in will never set it to None however many times it will retry to find a random folder name. So, the result is either path(from TempDir) being set to Some(path) or the user receiving Err. In this case, why not get rid of the Option and just set the TempDir { path: } directly to path and return Err otherwise?

    If None is planned for feature use, than functions like path and into_path should probably return Option<&path::Path> and Option<PathBuf> instead of unwrapping for the user and panicking.

    This of course will bump the library version.

    opened by lilianmoraru 2
  • (Not)Equivalent of dangling pointer dereferencing when calling `path` after `into_path`

    (Not)Equivalent of dangling pointer dereferencing when calling `path` after `into_path`

    I was just looking through the code("looking for inspiration") and observed a bug that is the equivalent of dangling pointers but with Rust Options(of course, no memory corruption). When calling into_path, path will be replaced with None - then -> if somebody calls the path function, the application will panic(because it unwraps for the user - which would be the equivalent of dereferencing a dangling pointer). I think it's better to break the API(v0.4) and make this function return an Option<&path::Path>, or maybe some other option(solution).

    opened by lilianmoraru 2
Releases(v0.3.7)
Temporary file library for rust

tempfile A secure, cross-platform, temporary file library for Rust. In addition to creating temporary files, this library also allows users to securel

Steven Allen 782 Dec 27, 2022
Highly parallelized, blazing fast directory tree analyzer

Parallel Disk Usage (pdu) Highly parallelized, blazing fast directory tree analyzer. Description pdu is a CLI program that renders a graphical chart f

Khải 237 Dec 22, 2022
Serve-live: static directory server with change notification

Serve a directory of static files, with server-sent events for automatic refresh.

Jim Blandy 3 Dec 15, 2022
Minty is an amazingly fast file deduplication app built in rust with a rust user interface.

minty Project Minty has a new look and feel!!! Minty is an amazingly fast file deduplication app built in rust with a rust user interface. I say super

null 26 Nov 20, 2022
High level FFI binding around the sys mount & umount2 calls, for Rust

sys-mount High level FFI bindings to the mount and umount2 system calls, for Rust. Examples Mount This is how the mount command could be written with

Pop!_OS 31 Dec 9, 2022
ergonomic paths and files in rust

path_abs: ergonomic paths and files in rust. This library aims to provide ergonomic path and file operations to rust with reasonable performance. See

Rett Berg 45 Oct 29, 2022
Extended attribute library for rust.

xattr A small library for setting, getting, and listing extended attributes. Supported Platforms: Linux, MacOS, FreeBSD, and NetBSD. API Documentation

Steven Allen 33 Nov 12, 2022
Rust implemention of Ascon

Ascon Pure Rust implementation of the lightweight Authenticated Encryption and Associated Data (AEAD) Ascon-128 and Ascon-128a. Security Notes This cr

Sebastian Ramacher 4 May 28, 2022
Lightweight Google Cloud Storage sync Rust Client with better performance than gsutil rsync

gcs-rsync Lightweight and efficient Rust gcs rsync for Google Cloud Storage. gcs-sync is faster than gsutil rsync when files change a lot while perfor

@cboudereau 4 Sep 8, 2022
A POSIX select I/O Multiplexing Rust library.

A POSIX select I/O Multiplexing Rust library.

b23r0 4 Jul 6, 2022
Supertag is a tag-based filesystem, written in Rust, for Linux and MacOS

Supertag is a tag-based filesystem, written in Rust, for Linux and MacOS. It provides a tag-based view of your files by removing the hierarchy constraints typically imposed on files and folders. In other words, it allows you to think about your files not as objects stored in folders, but as objects that can be filtered by folders.

Andrew Moffat 539 Dec 24, 2022
🦀 How to minimize Rust binary size 📦

Minimizing Rust Binary Size To help this project reach more users, consider upvoting the min-sized-rust Stack Overflow answer. This repository demonst

null 4.9k Jan 8, 2023
Spacedrive is an open source cross-platform file explorer, powered by a virtual distributed filesystem written in Rust.

Spacedrive A file explorer from the future. spacedrive.com » Download for macOS · Windows · Linux · iOS · watchOS · Android ~ Links will be added once

Spacedrive 16.2k Jan 7, 2023
Easy c̵̰͠r̵̛̠ö̴̪s̶̩̒s̵̭̀-t̶̲͝h̶̯̚r̵̺͐e̷̖̽ḁ̴̍d̶̖̔ ȓ̵͙ė̶͎ḟ̴͙e̸̖͛r̶̖͗ë̶̱́ṉ̵̒ĉ̷̥e̷͚̍ s̷̹͌h̷̲̉a̵̭͋r̷̫̊ḭ̵̊n̷̬͂g̵̦̃ f̶̻̊ơ̵̜ṟ̸̈́ R̵̞̋ù̵̺s̷̖̅ţ̸͗!̸̼͋

Rust S̵̓i̸̓n̵̉ I̴n̴f̶e̸r̵n̷a̴l mutability! Howdy, friendly Rust developer! Ever had a value get m̵̯̅ð̶͊v̴̮̾ê̴̼͘d away right under your nose just when

null 294 Dec 23, 2022
Simplify temporary email management and interaction, including message retrieval and attachment downloads, using Rust.

Tempmail The Tempmail simplifies temporary email management and interaction, including message retrieval and attachment downloads, using the Rust prog

Dilshad 6 Sep 21, 2023
Temporary elevated access management as a self-hosted service

????☁️ S A T O U N K I Temporary elevated access management as a self-hosted service Overview Satounki is a self-hosted service which brings visibilit

جاد 31 Dec 17, 2023
Mount portable directory as consistent user directory.

PortableDesktop Mount portable directory as consistent user directory. PortableDesktopCli help PortableDesktopCli [options] <Target Path> <Link Path>

Kerwin Bryant 3 May 8, 2023
Rust File Management CLI is a command-line tool written in Rust that provides essential file management functionalities. Whether you're working with files or directories, this tool simplifies common file operations with ease.

Rust FileOps Rust File Management CLI is a command-line tool written in Rust that provides essential file management functionalities. Whether you're w

Harikesh Ranjan Sinha 5 May 2, 2024
This is a `Rust` based package to help with the management of complex medicine (pill) management cycles.

reepicheep This is a Rust based package to help with the management of complex medicine (pill) management cycles. reepicheep notifies a person(s) via

Daniel B 24 Dec 13, 2023