summaryrefslogtreecommitdiff
path: root/src/cmd/folders.rs
blob: 0133528d3c6a3b078fe8365212bc3a8a9f0308ab (plain)
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
use std::collections::BTreeSet;
use std::ffi::{OsStr, OsString};
use std::path::Path;
use std::sync::OnceLock;

use maildir::Maildir;

use crate::error::Result;

static REQUIRED_MAILDIR_DIRS: OnceLock<BTreeSet<OsString>> = OnceLock::new();

fn is_mailsubdir(p: &Path) -> bool {
    let rmd = REQUIRED_MAILDIR_DIRS.get_or_init(|| {
        [
            OsString::from("cur"),
            "new".into(),
            "tmp".into(),
            "maildirfolder".into(),
        ]
        .into()
    });

    p.is_dir()
        && p.file_name()
            .map_or(false, |fname| fname.to_string_lossy().starts_with('.'))
        && p.read_dir()
            .map(|dir| {
                dir.filter_map(|child| {
                    child
                        .ok()
                        .and_then(|dir_entry| dir_entry.path().file_name().map(OsStr::to_owned))
                })
                .collect::<BTreeSet<_>>()
                .is_superset(rmd)
            })
            .unwrap_or_default()
}

pub fn folders(md: &Maildir) -> Result<Vec<String>> {
    let root_path = md.path();

    let subdirs = root_path
        .read_dir()?
        .filter_map(|d| d.ok())
        .filter(|d| is_mailsubdir(&d.path()))
        .filter_map(|d| Some(d.path().file_name()?.to_string_lossy()[1..].to_owned()))
        .collect();

    Ok(subdirs)
}