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
52
53
54
55
56
57
58
use async_trait::async_trait;
use log::info;
use maildirpp::Maildir;
use std::path::PathBuf;
use thiserror::Error;

use crate::{folder::FolderKind, maildir, notmuch::NotmuchContextSync, Result};

use super::AddFolder;

#[derive(Error, Debug)]
pub enum Error {
    #[error("cannot create notmuch folder structure at {1}")]
    CreateFolderStructureError(#[source] maildirpp::Error, PathBuf),
}

pub struct AddNotmuchFolder {
    ctx: NotmuchContextSync,
}

impl AddNotmuchFolder {
    pub fn new(ctx: &NotmuchContextSync) -> Self {
        Self { ctx: ctx.clone() }
    }

    pub fn new_boxed(ctx: &NotmuchContextSync) -> Box<dyn AddFolder> {
        Box::new(Self::new(ctx))
    }

    pub fn some_new_boxed(ctx: &NotmuchContextSync) -> Option<Box<dyn AddFolder>> {
        Some(Self::new_boxed(ctx))
    }
}

#[async_trait]
impl AddFolder for AddNotmuchFolder {
    async fn add_folder(&self, folder: &str) -> Result<()> {
        info!("creating notmuch folder {folder}");

        let config = &self.ctx.account_config;
        let ctx = self.ctx.lock().await;
        let mdir_ctx = &ctx.mdir_ctx;

        let path = if FolderKind::matches_inbox(folder) {
            mdir_ctx.root.path().to_owned()
        } else {
            let folder = config.get_folder_alias(folder);
            let folder = maildir::encode_folder(folder);
            mdir_ctx.root.path().join(format!(".{}", folder))
        };

        Maildir::from(path.clone())
            .create_dirs()
            .map_err(|err| Error::CreateFolderStructureError(err, path))?;

        Ok(())
    }
}