summaryrefslogtreecommitdiff
path: root/src/operations/ls.rs
blob: 9dd32585b32359561e1ddeee4e5ae2b24540d3b9 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
use crate::*;

/// Convert a file path into an [Entry].
pub fn get_entry(path: impl AsRef<Path>) -> ReadResult<Entry> {
    Entry::from_path(path)
}

/// Convert a file path that might not be valid into an [Entry]. This will return
/// as [Option::None] instead of [EntryReadError::NotFound] if the file doesn't exist.
pub fn get_optional_entry(path: impl AsRef<Path>) -> ReadResult<Option<Entry>> {
    match get_entry(path) {
        Ok(e) => Ok(Some(e)),
        Err(EntryReadError { error_kind: EntryErrorKind::NotFound, .. }) => Ok(None),
        Err(other) => Err(other),
    }
}

/// Get an [Entry] for every file and subdirectory within a directory.
pub fn list_directory(path: impl AsRef<Path>) -> ReadResult<Vec<Entry>>{
    let path = path.as_ref();
    macro_rules! raise {
        ($err:expr) => {io_result_to_read_result($err, path)?}; }

    let mut entries = Vec::new();
    for dir_entry in raise!(std::fs::read_dir(path)) {
        let entry = match Entry::from_path(&raise!(dir_entry).path()) {
            Ok(v) => v,
            Err(_) => continue,
        };
        entries.push(entry);
    }
    return Ok(entries);
}

/// Recursively descend into a directory and all sub-directories, returning an
/// [Entry] for each discovered file.
pub fn traverse_directory(path: impl AsRef<Path>) -> ReadResult<Vec<Entry>> {
    let mut file_entries = Vec::new();
    for entry in list_directory(path)? {
        match entry.entry_type {
            EntryType::File => file_entries.push(entry),
            EntryType::Directory => file_entries.extend(traverse_directory(&entry.path)?),
        }
    }
    return Ok(file_entries);
}