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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
//! Module dedicated to the Notmuch backend configuration.
//!
//! This module contains the configuration specific to the Notmuch
//! backend.

use notmuch::{Database, DatabaseMode};
use serde::{Deserialize, Serialize};
use std::path::{Path, PathBuf};

use crate::Result;

/// The Notmuch backend config.
#[derive(Debug, Default, Clone, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub struct NotmuchConfig {
    /// The path to the Notmuch database.
    ///
    /// The path should point to the root directory containing the
    /// Notmuch database (usually the root Maildir directory). Path is
    /// shell-expanded, which means environment variables and tilde
    /// `~` are replaced by their values.
    #[serde(alias = "db-path")]
    pub database_path: Option<PathBuf>,

    /// Override the default path to the Maildir folder.
    ///
    /// Path is shell-expanded, which means environment variables and
    /// tilde `~` are replaced by their values. Defaults to
    /// `database_path` if omitted.
    pub maildir_path: Option<PathBuf>,

    /// Override the default Notmuch configuration file path.
    ///
    /// Path is shell-expanded, which means environment variables and
    /// tilde `~` are replaced by their values.
    pub config_path: Option<PathBuf>,

    /// Override the default Notmuch profile name.
    pub profile: Option<String>,
}

impl NotmuchConfig {
    /// Get the default Notmuch database path.
    pub fn get_default_database_path() -> Result<PathBuf> {
        Ok(Database::open_with_config(
            None::<PathBuf>,
            DatabaseMode::ReadOnly,
            None::<PathBuf>,
            None,
        )?
        .path()
        .to_owned())
    }

    /// Get the reference to the Notmuch database path.
    pub fn get_database_path(&self) -> Result<PathBuf> {
        match self.database_path.as_ref() {
            Some(path) => Ok(path.to_owned()),
            None => Self::get_default_database_path(),
        }
    }

    /// Get the reference to the Maildir path.
    ///
    /// Try the `maildir_path` first, otherwise falls back to
    /// `database_path`.
    pub fn get_maildir_path(&self) -> Result<PathBuf> {
        match self.maildir_path.as_ref() {
            Some(path) => Ok(path.to_owned()),
            None => self.get_database_path(),
        }
    }

    /// Find the Notmuch configuration path reference.
    pub fn find_config_path(&self) -> Option<&Path> {
        self.config_path.as_ref().map(AsRef::as_ref)
    }

    /// Find the Notmuch profile.
    pub fn find_profile(&self) -> Option<&str> {
        self.profile.as_deref()
    }
}