11 releases (3 stable)

2.0.1 Oct 3, 2023
1.0.1 Aug 17, 2022
0.11.1 Oct 31, 2020
0.10.3 Sep 14, 2020
0.9.1 Sep 13, 2020

#592 in Filesystem

Download history 106/week @ 2024-07-20 112/week @ 2024-07-27 94/week @ 2024-08-03 104/week @ 2024-08-10 138/week @ 2024-08-17 181/week @ 2024-08-24 147/week @ 2024-08-31 114/week @ 2024-09-07 138/week @ 2024-09-14 169/week @ 2024-09-21 348/week @ 2024-09-28 177/week @ 2024-10-05 144/week @ 2024-10-12 191/week @ 2024-10-19 167/week @ 2024-10-26 100/week @ 2024-11-02

635 downloads per month
Used in fs-tree

MIT license

15KB
167 lines

file_type_enum

An enum with a variant for each file type.

pub enum FileType {
    Regular,
    Directory,
    Symlink,
    BlockDevice, // unix only
    CharDevice,  // unix only
    Fifo,        // unix only
    Socket,      // unix only
}

Alternatives:

  1. If you want a enum tree, check the crate fs-tree.
  2. If you don't need an enum, check these methods from std instead:

Example:

use std::{fs, io, path::Path};

use file_type_enum::FileType;

fn move_file(from: &Path, to: &Path) -> io::Result<()> {
    let from_type = FileType::symlink_read_at(from)?;
    let to_type = FileType::symlink_read_at(to)?;

    use FileType::{Directory, Regular, Symlink};

    match (from_type, to_type) {
        (Directory, Directory) => {
            println!("Replacing directory {to:?} by directory {from:?}.");
        }
        (Regular, Regular) | (Symlink, Symlink) => {
            // Might print:
            //       "Overwriting regular file at PATH."
            //       "Overwriting symbolic link at PATH."
            println!("Overwriting {from_type} at {to:?} by {to:?}.");
        }
        (_, Directory) => {
            println!("Moving file at {from:?} into folder {to:?}.");
            fs::rename(from, to)?;
        }
        (_, _) => {
            // Might print:
            // -   "Cannot overwrite regular file  with a symbolic link."
            // -   "Cannot overwrite directory     with a symbolic link."
            // -   "Cannot overwrite symbolic link with a regular file."
            panic!("Cannot overwrite {to_type}     with a {from_type}.");
        }
    }

    Ok(())
}

As shown in the example FileType also implements Display.

Warning

Note that, like std functions, FileType::read_at follows symlinks, therefore it is impossible to get the FileType::Symlink variant. If you want symlink-awareness, use FileType::symlink_read_at instead.

Conversions

Dependencies