summaryrefslogtreecommitdiff
path: root/src/operations/ls.rs
blob: 2d2da5daa5a6ac15d40de31d2d801bd739b09f2b (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
47
48
49
50
51
use crate::{Entry, EntryReadError, EntryType};
use std::path::Path;

pub fn get_entry<P>(path: P) -> Result<Entry, EntryReadError>
where
    P: AsRef<Path>,
{
    Entry::from_path(path)
}

pub fn get_optional_entry<P>(path: P) -> Result<Option<Entry>, EntryReadError>
where
    P: AsRef<Path>,
{
    match get_entry(path) {
        Ok(e) => Ok(Some(e)),
        Err(EntryReadError::NotFound) => Ok(None),
        Err(other) => Err(other),
    }
}

pub fn list_directory<P>(path: P) -> Result<Vec<Entry>, EntryReadError>
where
    P: AsRef<Path>,
{
    let mut entries = Vec::new();
    for dir_entry in std::fs::read_dir(path)? {
        let entry = match Entry::from_path(&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`](struct.Entry.html) for each discovered file.
pub fn traverse_directory<P>(path: P) -> Result<Vec<Entry>, EntryReadError>
where
    P: AsRef<Path>,
{
    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);
}