himalaya/src/config/config.rs

703 lines
22 KiB
Rust
Raw Normal View History

2022-09-22 14:38:38 +00:00
//! Deserialized config module.
//!
//! This module contains the raw deserialized representation of the
//! user configuration file.
use anyhow::{anyhow, Context, Result};
use dialoguer::Confirm;
release v0.7.0 (#433) * update codebase with email lib changes (#431) update himalaya-lib, rename remaining mbox vars add missing methods from lib update changelog * fixed missing folder aliases #430 * improve README links * fix README repology link * fix README repology table * fix README repology table 2 * center README repology table * fix README cosmetic issues * fix README cosmetic issues 2 * fix README title * fix README wiki links * fix lock file * prepare v0.6.2 * fix ci * try some musl builds #356 * add musl build to artifact #356 * add musl build to deployment pipeline #356 * migrate clap v4, add man command #419 * add option to choose color manually #407 * update links and badges * update matrix badge * add github release version badge * update badges links * fix code bloc type * fix tests * fix cargo lock * generate all man pages for all subcommands #419 * fix query and headers arg parsers * fix invalid flags and options due to clap v4 migration * fix tests * remove -l|--log-level option * refactor contributing guide * update lib * fix flags string printer * make commands read, attachments, copy, move and delete accept multiple ids * fix ids arg parser * fix flags subcommands conflicts between ids and flags * flip back copy and move arguments * add issue template (#439) * update lib, prepare for sync feature * update himalaya lib, fix senders and config * update lock file himalaya lib * fix sync enabling issues * fix wrong imap backend init in main file * fix notmuch backend post sync feature * configuration wizard (#432) * make DeserializedConfig::path more robust With this change, himalaya uses the crate `dirs` in order to follow XDG specifications on Unix, Known Folder on Windows and Standard Directories on MacOS. This gives us much smoother cross-platform support. It still has the same fallbacks (`$HOME/.config/himalaya/config.toml` and `$HOME/.himalayarc`.) Additionally, this commit removes a bit of in-house code-bloat. * add wizard entrypoint and basic structure * wip * feat: impl Serialize for all DeserializedConfigs * feat: select default account and write to file * feat: add SMTP part of wizard * build: update lockfile * refactor: separate out multiple files for wizard * style: friendlier and prettier messages * feat: add maildir part of wizard * feat: add notmuch part of wizard * chore: clippy lints and reorder prompts * fix: contrived solution to serializing None values * fix: allow empty Option field when deserializing * style: address PR review comments * fix: utilize notmuch lib in finding database path * fix notmuch wizard --------- Co-authored-by: Clément DOUIN <clement.douin@posteo.net> * add account sync progress bar * improve sync spinner * make the sync dry run flag show patches without applying them * update himalaya lib, increase imap session pool size * add disable cache flag * add nlnet logo in readme * update himalaya lib deps, make use of sync reports * prepare v0.7.0 * bump rustc v1.67.0 and clap v4.1.4 * bump himalaya lib v0.5.1, fix flake lock file --------- Co-authored-by: janabhumi <dmitriy@ideascup.me> Co-authored-by: Knut Magnus Aasrud <km@aasrud.com>
2023-02-08 15:03:45 +00:00
use dirs::{config_dir, home_dir};
2023-11-28 11:30:50 +00:00
use email::{
account::AccountConfig,
config::Config,
email::{EmailHooks, EmailTextPlainFormat},
};
2023-08-28 07:04:13 +00:00
use log::{debug, trace};
release v0.7.0 (#433) * update codebase with email lib changes (#431) update himalaya-lib, rename remaining mbox vars add missing methods from lib update changelog * fixed missing folder aliases #430 * improve README links * fix README repology link * fix README repology table * fix README repology table 2 * center README repology table * fix README cosmetic issues * fix README cosmetic issues 2 * fix README title * fix README wiki links * fix lock file * prepare v0.6.2 * fix ci * try some musl builds #356 * add musl build to artifact #356 * add musl build to deployment pipeline #356 * migrate clap v4, add man command #419 * add option to choose color manually #407 * update links and badges * update matrix badge * add github release version badge * update badges links * fix code bloc type * fix tests * fix cargo lock * generate all man pages for all subcommands #419 * fix query and headers arg parsers * fix invalid flags and options due to clap v4 migration * fix tests * remove -l|--log-level option * refactor contributing guide * update lib * fix flags string printer * make commands read, attachments, copy, move and delete accept multiple ids * fix ids arg parser * fix flags subcommands conflicts between ids and flags * flip back copy and move arguments * add issue template (#439) * update lib, prepare for sync feature * update himalaya lib, fix senders and config * update lock file himalaya lib * fix sync enabling issues * fix wrong imap backend init in main file * fix notmuch backend post sync feature * configuration wizard (#432) * make DeserializedConfig::path more robust With this change, himalaya uses the crate `dirs` in order to follow XDG specifications on Unix, Known Folder on Windows and Standard Directories on MacOS. This gives us much smoother cross-platform support. It still has the same fallbacks (`$HOME/.config/himalaya/config.toml` and `$HOME/.himalayarc`.) Additionally, this commit removes a bit of in-house code-bloat. * add wizard entrypoint and basic structure * wip * feat: impl Serialize for all DeserializedConfigs * feat: select default account and write to file * feat: add SMTP part of wizard * build: update lockfile * refactor: separate out multiple files for wizard * style: friendlier and prettier messages * feat: add maildir part of wizard * feat: add notmuch part of wizard * chore: clippy lints and reorder prompts * fix: contrived solution to serializing None values * fix: allow empty Option field when deserializing * style: address PR review comments * fix: utilize notmuch lib in finding database path * fix notmuch wizard --------- Co-authored-by: Clément DOUIN <clement.douin@posteo.net> * add account sync progress bar * improve sync spinner * make the sync dry run flag show patches without applying them * update himalaya lib, increase imap session pool size * add disable cache flag * add nlnet logo in readme * update himalaya lib deps, make use of sync reports * prepare v0.7.0 * bump rustc v1.67.0 and clap v4.1.4 * bump himalaya lib v0.5.1, fix flake lock file --------- Co-authored-by: janabhumi <dmitriy@ideascup.me> Co-authored-by: Knut Magnus Aasrud <km@aasrud.com>
2023-02-08 15:03:45 +00:00
use serde::{Deserialize, Serialize};
2023-08-28 07:04:13 +00:00
use std::{collections::HashMap, fs, path::PathBuf, process::exit};
2022-09-22 14:38:38 +00:00
use toml;
release v0.7.0 (#433) * update codebase with email lib changes (#431) update himalaya-lib, rename remaining mbox vars add missing methods from lib update changelog * fixed missing folder aliases #430 * improve README links * fix README repology link * fix README repology table * fix README repology table 2 * center README repology table * fix README cosmetic issues * fix README cosmetic issues 2 * fix README title * fix README wiki links * fix lock file * prepare v0.6.2 * fix ci * try some musl builds #356 * add musl build to artifact #356 * add musl build to deployment pipeline #356 * migrate clap v4, add man command #419 * add option to choose color manually #407 * update links and badges * update matrix badge * add github release version badge * update badges links * fix code bloc type * fix tests * fix cargo lock * generate all man pages for all subcommands #419 * fix query and headers arg parsers * fix invalid flags and options due to clap v4 migration * fix tests * remove -l|--log-level option * refactor contributing guide * update lib * fix flags string printer * make commands read, attachments, copy, move and delete accept multiple ids * fix ids arg parser * fix flags subcommands conflicts between ids and flags * flip back copy and move arguments * add issue template (#439) * update lib, prepare for sync feature * update himalaya lib, fix senders and config * update lock file himalaya lib * fix sync enabling issues * fix wrong imap backend init in main file * fix notmuch backend post sync feature * configuration wizard (#432) * make DeserializedConfig::path more robust With this change, himalaya uses the crate `dirs` in order to follow XDG specifications on Unix, Known Folder on Windows and Standard Directories on MacOS. This gives us much smoother cross-platform support. It still has the same fallbacks (`$HOME/.config/himalaya/config.toml` and `$HOME/.himalayarc`.) Additionally, this commit removes a bit of in-house code-bloat. * add wizard entrypoint and basic structure * wip * feat: impl Serialize for all DeserializedConfigs * feat: select default account and write to file * feat: add SMTP part of wizard * build: update lockfile * refactor: separate out multiple files for wizard * style: friendlier and prettier messages * feat: add maildir part of wizard * feat: add notmuch part of wizard * chore: clippy lints and reorder prompts * fix: contrived solution to serializing None values * fix: allow empty Option field when deserializing * style: address PR review comments * fix: utilize notmuch lib in finding database path * fix notmuch wizard --------- Co-authored-by: Clément DOUIN <clement.douin@posteo.net> * add account sync progress bar * improve sync spinner * make the sync dry run flag show patches without applying them * update himalaya lib, increase imap session pool size * add disable cache flag * add nlnet logo in readme * update himalaya lib deps, make use of sync reports * prepare v0.7.0 * bump rustc v1.67.0 and clap v4.1.4 * bump himalaya lib v0.5.1, fix flake lock file --------- Co-authored-by: janabhumi <dmitriy@ideascup.me> Co-authored-by: Knut Magnus Aasrud <km@aasrud.com>
2023-02-08 15:03:45 +00:00
use crate::{
account::DeserializedAccountConfig,
2023-11-28 21:28:28 +00:00
backend::BackendKind,
config::{prelude::*, wizard},
wizard_prompt, wizard_warn,
release v0.7.0 (#433) * update codebase with email lib changes (#431) update himalaya-lib, rename remaining mbox vars add missing methods from lib update changelog * fixed missing folder aliases #430 * improve README links * fix README repology link * fix README repology table * fix README repology table 2 * center README repology table * fix README cosmetic issues * fix README cosmetic issues 2 * fix README title * fix README wiki links * fix lock file * prepare v0.6.2 * fix ci * try some musl builds #356 * add musl build to artifact #356 * add musl build to deployment pipeline #356 * migrate clap v4, add man command #419 * add option to choose color manually #407 * update links and badges * update matrix badge * add github release version badge * update badges links * fix code bloc type * fix tests * fix cargo lock * generate all man pages for all subcommands #419 * fix query and headers arg parsers * fix invalid flags and options due to clap v4 migration * fix tests * remove -l|--log-level option * refactor contributing guide * update lib * fix flags string printer * make commands read, attachments, copy, move and delete accept multiple ids * fix ids arg parser * fix flags subcommands conflicts between ids and flags * flip back copy and move arguments * add issue template (#439) * update lib, prepare for sync feature * update himalaya lib, fix senders and config * update lock file himalaya lib * fix sync enabling issues * fix wrong imap backend init in main file * fix notmuch backend post sync feature * configuration wizard (#432) * make DeserializedConfig::path more robust With this change, himalaya uses the crate `dirs` in order to follow XDG specifications on Unix, Known Folder on Windows and Standard Directories on MacOS. This gives us much smoother cross-platform support. It still has the same fallbacks (`$HOME/.config/himalaya/config.toml` and `$HOME/.himalayarc`.) Additionally, this commit removes a bit of in-house code-bloat. * add wizard entrypoint and basic structure * wip * feat: impl Serialize for all DeserializedConfigs * feat: select default account and write to file * feat: add SMTP part of wizard * build: update lockfile * refactor: separate out multiple files for wizard * style: friendlier and prettier messages * feat: add maildir part of wizard * feat: add notmuch part of wizard * chore: clippy lints and reorder prompts * fix: contrived solution to serializing None values * fix: allow empty Option field when deserializing * style: address PR review comments * fix: utilize notmuch lib in finding database path * fix notmuch wizard --------- Co-authored-by: Clément DOUIN <clement.douin@posteo.net> * add account sync progress bar * improve sync spinner * make the sync dry run flag show patches without applying them * update himalaya lib, increase imap session pool size * add disable cache flag * add nlnet logo in readme * update himalaya lib deps, make use of sync reports * prepare v0.7.0 * bump rustc v1.67.0 and clap v4.1.4 * bump himalaya lib v0.5.1, fix flake lock file --------- Co-authored-by: janabhumi <dmitriy@ideascup.me> Co-authored-by: Knut Magnus Aasrud <km@aasrud.com>
2023-02-08 15:03:45 +00:00
};
2022-09-22 14:38:38 +00:00
/// Represents the user config file.
2023-02-18 20:12:47 +00:00
#[derive(Clone, Debug, Default, Eq, PartialEq, Deserialize, Serialize)]
2022-09-22 14:38:38 +00:00
#[serde(rename_all = "kebab-case")]
pub struct DeserializedConfig {
#[serde(alias = "name")]
pub display_name: Option<String>,
pub signature_delim: Option<String>,
pub signature: Option<String>,
pub downloads_dir: Option<PathBuf>,
pub folder_listing_page_size: Option<usize>,
pub folder_aliases: Option<HashMap<String, String>>,
pub email_listing_page_size: Option<usize>,
2023-06-15 13:45:36 +00:00
pub email_listing_datetime_fmt: Option<String>,
pub email_listing_datetime_local_tz: Option<bool>,
2022-09-22 14:38:38 +00:00
pub email_reading_headers: Option<Vec<String>>,
2023-11-25 11:37:00 +00:00
#[serde(default, with = "OptionEmailTextPlainFormatDef")]
pub email_reading_format: Option<EmailTextPlainFormat>,
release v0.7.0 (#433) * update codebase with email lib changes (#431) update himalaya-lib, rename remaining mbox vars add missing methods from lib update changelog * fixed missing folder aliases #430 * improve README links * fix README repology link * fix README repology table * fix README repology table 2 * center README repology table * fix README cosmetic issues * fix README cosmetic issues 2 * fix README title * fix README wiki links * fix lock file * prepare v0.6.2 * fix ci * try some musl builds #356 * add musl build to artifact #356 * add musl build to deployment pipeline #356 * migrate clap v4, add man command #419 * add option to choose color manually #407 * update links and badges * update matrix badge * add github release version badge * update badges links * fix code bloc type * fix tests * fix cargo lock * generate all man pages for all subcommands #419 * fix query and headers arg parsers * fix invalid flags and options due to clap v4 migration * fix tests * remove -l|--log-level option * refactor contributing guide * update lib * fix flags string printer * make commands read, attachments, copy, move and delete accept multiple ids * fix ids arg parser * fix flags subcommands conflicts between ids and flags * flip back copy and move arguments * add issue template (#439) * update lib, prepare for sync feature * update himalaya lib, fix senders and config * update lock file himalaya lib * fix sync enabling issues * fix wrong imap backend init in main file * fix notmuch backend post sync feature * configuration wizard (#432) * make DeserializedConfig::path more robust With this change, himalaya uses the crate `dirs` in order to follow XDG specifications on Unix, Known Folder on Windows and Standard Directories on MacOS. This gives us much smoother cross-platform support. It still has the same fallbacks (`$HOME/.config/himalaya/config.toml` and `$HOME/.himalayarc`.) Additionally, this commit removes a bit of in-house code-bloat. * add wizard entrypoint and basic structure * wip * feat: impl Serialize for all DeserializedConfigs * feat: select default account and write to file * feat: add SMTP part of wizard * build: update lockfile * refactor: separate out multiple files for wizard * style: friendlier and prettier messages * feat: add maildir part of wizard * feat: add notmuch part of wizard * chore: clippy lints and reorder prompts * fix: contrived solution to serializing None values * fix: allow empty Option field when deserializing * style: address PR review comments * fix: utilize notmuch lib in finding database path * fix notmuch wizard --------- Co-authored-by: Clément DOUIN <clement.douin@posteo.net> * add account sync progress bar * improve sync spinner * make the sync dry run flag show patches without applying them * update himalaya lib, increase imap session pool size * add disable cache flag * add nlnet logo in readme * update himalaya lib deps, make use of sync reports * prepare v0.7.0 * bump rustc v1.67.0 and clap v4.1.4 * bump himalaya lib v0.5.1, fix flake lock file --------- Co-authored-by: janabhumi <dmitriy@ideascup.me> Co-authored-by: Knut Magnus Aasrud <km@aasrud.com>
2023-02-08 15:03:45 +00:00
pub email_writing_headers: Option<Vec<String>>,
pub email_sending_save_copy: Option<bool>,
2023-11-25 11:37:00 +00:00
#[serde(default, with = "OptionEmailHooksDef")]
pub email_hooks: Option<EmailHooks>,
2022-09-22 14:38:38 +00:00
#[serde(flatten)]
pub accounts: HashMap<String, DeserializedAccountConfig>,
}
impl DeserializedConfig {
/// Tries to create a config from an optional path.
2023-07-20 09:43:28 +00:00
pub async fn from_opt_path(path: Option<&str>) -> Result<Self> {
2022-09-22 14:38:38 +00:00
debug!("path: {:?}", path);
let config = if let Some(path) = path.map(PathBuf::from).or_else(Self::path) {
let content = fs::read_to_string(path).context("cannot read config file")?;
toml::from_str(&content).context("cannot parse config file")?
} else {
wizard_warn!("Himalaya could not find an already existing configuration file.");
if !Confirm::new()
.with_prompt(wizard_prompt!(
"Would you like to create one with the wizard?"
))
.default(true)
.interact_opt()?
.unwrap_or_default()
{
2023-08-28 07:04:13 +00:00
exit(0);
}
2023-07-20 09:43:28 +00:00
wizard::configure().await?
};
2022-09-22 14:38:38 +00:00
if config.accounts.is_empty() {
return Err(anyhow!("config file must contain at least one account"));
}
release v0.7.0 (#433) * update codebase with email lib changes (#431) update himalaya-lib, rename remaining mbox vars add missing methods from lib update changelog * fixed missing folder aliases #430 * improve README links * fix README repology link * fix README repology table * fix README repology table 2 * center README repology table * fix README cosmetic issues * fix README cosmetic issues 2 * fix README title * fix README wiki links * fix lock file * prepare v0.6.2 * fix ci * try some musl builds #356 * add musl build to artifact #356 * add musl build to deployment pipeline #356 * migrate clap v4, add man command #419 * add option to choose color manually #407 * update links and badges * update matrix badge * add github release version badge * update badges links * fix code bloc type * fix tests * fix cargo lock * generate all man pages for all subcommands #419 * fix query and headers arg parsers * fix invalid flags and options due to clap v4 migration * fix tests * remove -l|--log-level option * refactor contributing guide * update lib * fix flags string printer * make commands read, attachments, copy, move and delete accept multiple ids * fix ids arg parser * fix flags subcommands conflicts between ids and flags * flip back copy and move arguments * add issue template (#439) * update lib, prepare for sync feature * update himalaya lib, fix senders and config * update lock file himalaya lib * fix sync enabling issues * fix wrong imap backend init in main file * fix notmuch backend post sync feature * configuration wizard (#432) * make DeserializedConfig::path more robust With this change, himalaya uses the crate `dirs` in order to follow XDG specifications on Unix, Known Folder on Windows and Standard Directories on MacOS. This gives us much smoother cross-platform support. It still has the same fallbacks (`$HOME/.config/himalaya/config.toml` and `$HOME/.himalayarc`.) Additionally, this commit removes a bit of in-house code-bloat. * add wizard entrypoint and basic structure * wip * feat: impl Serialize for all DeserializedConfigs * feat: select default account and write to file * feat: add SMTP part of wizard * build: update lockfile * refactor: separate out multiple files for wizard * style: friendlier and prettier messages * feat: add maildir part of wizard * feat: add notmuch part of wizard * chore: clippy lints and reorder prompts * fix: contrived solution to serializing None values * fix: allow empty Option field when deserializing * style: address PR review comments * fix: utilize notmuch lib in finding database path * fix notmuch wizard --------- Co-authored-by: Clément DOUIN <clement.douin@posteo.net> * add account sync progress bar * improve sync spinner * make the sync dry run flag show patches without applying them * update himalaya lib, increase imap session pool size * add disable cache flag * add nlnet logo in readme * update himalaya lib deps, make use of sync reports * prepare v0.7.0 * bump rustc v1.67.0 and clap v4.1.4 * bump himalaya lib v0.5.1, fix flake lock file --------- Co-authored-by: janabhumi <dmitriy@ideascup.me> Co-authored-by: Knut Magnus Aasrud <km@aasrud.com>
2023-02-08 15:03:45 +00:00
trace!("config: {:#?}", config);
2022-09-22 14:38:38 +00:00
Ok(config)
}
release v0.7.0 (#433) * update codebase with email lib changes (#431) update himalaya-lib, rename remaining mbox vars add missing methods from lib update changelog * fixed missing folder aliases #430 * improve README links * fix README repology link * fix README repology table * fix README repology table 2 * center README repology table * fix README cosmetic issues * fix README cosmetic issues 2 * fix README title * fix README wiki links * fix lock file * prepare v0.6.2 * fix ci * try some musl builds #356 * add musl build to artifact #356 * add musl build to deployment pipeline #356 * migrate clap v4, add man command #419 * add option to choose color manually #407 * update links and badges * update matrix badge * add github release version badge * update badges links * fix code bloc type * fix tests * fix cargo lock * generate all man pages for all subcommands #419 * fix query and headers arg parsers * fix invalid flags and options due to clap v4 migration * fix tests * remove -l|--log-level option * refactor contributing guide * update lib * fix flags string printer * make commands read, attachments, copy, move and delete accept multiple ids * fix ids arg parser * fix flags subcommands conflicts between ids and flags * flip back copy and move arguments * add issue template (#439) * update lib, prepare for sync feature * update himalaya lib, fix senders and config * update lock file himalaya lib * fix sync enabling issues * fix wrong imap backend init in main file * fix notmuch backend post sync feature * configuration wizard (#432) * make DeserializedConfig::path more robust With this change, himalaya uses the crate `dirs` in order to follow XDG specifications on Unix, Known Folder on Windows and Standard Directories on MacOS. This gives us much smoother cross-platform support. It still has the same fallbacks (`$HOME/.config/himalaya/config.toml` and `$HOME/.himalayarc`.) Additionally, this commit removes a bit of in-house code-bloat. * add wizard entrypoint and basic structure * wip * feat: impl Serialize for all DeserializedConfigs * feat: select default account and write to file * feat: add SMTP part of wizard * build: update lockfile * refactor: separate out multiple files for wizard * style: friendlier and prettier messages * feat: add maildir part of wizard * feat: add notmuch part of wizard * chore: clippy lints and reorder prompts * fix: contrived solution to serializing None values * fix: allow empty Option field when deserializing * style: address PR review comments * fix: utilize notmuch lib in finding database path * fix notmuch wizard --------- Co-authored-by: Clément DOUIN <clement.douin@posteo.net> * add account sync progress bar * improve sync spinner * make the sync dry run flag show patches without applying them * update himalaya lib, increase imap session pool size * add disable cache flag * add nlnet logo in readme * update himalaya lib deps, make use of sync reports * prepare v0.7.0 * bump rustc v1.67.0 and clap v4.1.4 * bump himalaya lib v0.5.1, fix flake lock file --------- Co-authored-by: janabhumi <dmitriy@ideascup.me> Co-authored-by: Knut Magnus Aasrud <km@aasrud.com>
2023-02-08 15:03:45 +00:00
/// Tries to return a config path from a few default settings.
///
/// Tries paths in this order:
///
/// - `"$XDG_CONFIG_DIR/himalaya/config.toml"` (or equivalent to `$XDG_CONFIG_DIR` in other
/// OSes.)
/// - `"$HOME/.config/himalaya/config.toml"`
/// - `"$HOME/.himalayarc"`
///
/// Returns `Some(path)` if the path exists, otherwise `None`.
pub fn path() -> Option<PathBuf> {
config_dir()
.map(|p| p.join("himalaya").join("config.toml"))
.filter(|p| p.exists())
.or_else(|| home_dir().map(|p| p.join(".config").join("himalaya").join("config.toml")))
.filter(|p| p.exists())
.or_else(|| home_dir().map(|p| p.join(".himalayarc")))
.filter(|p| p.exists())
2022-09-22 14:38:38 +00:00
}
2023-11-28 11:30:50 +00:00
pub fn into_account_configs(
self,
account_name: Option<&str>,
2023-11-28 21:28:28 +00:00
disable_cache: bool,
2023-11-28 11:30:50 +00:00
) -> Result<(DeserializedAccountConfig, AccountConfig)> {
let (account_name, mut toml_account_config) = match account_name {
Some("default") | Some("") | None => self
.accounts
.iter()
.find_map(|(name, account)| {
account
.default
.filter(|default| *default == true)
.map(|_| (name.to_owned(), account.clone()))
})
.ok_or_else(|| anyhow!("cannot find default account")),
Some(name) => self
.accounts
.get(name)
.map(|account| (name.to_owned(), account.clone()))
.ok_or_else(|| anyhow!("cannot find account {name}")),
}?;
#[cfg(feature = "imap-backend")]
if let Some(imap_config) = toml_account_config.imap.as_mut() {
imap_config
.auth
.replace_undefined_keyring_entries(&account_name);
}
#[cfg(feature = "smtp-sender")]
if let Some(smtp_config) = toml_account_config.smtp.as_mut() {
smtp_config
.auth
.replace_undefined_keyring_entries(&account_name);
}
2023-11-28 21:28:28 +00:00
if let Some(true) = toml_account_config.sync {
if !disable_cache {
toml_account_config.backend = Some(BackendKind::MaildirForSync);
}
}
2023-11-28 11:30:50 +00:00
let config = Config {
display_name: self.display_name,
signature_delim: self.signature_delim,
signature: self.signature,
downloads_dir: self.downloads_dir,
folder_listing_page_size: self.folder_listing_page_size,
folder_aliases: self.folder_aliases,
email_listing_page_size: self.email_listing_page_size,
email_listing_datetime_fmt: self.email_listing_datetime_fmt,
email_listing_datetime_local_tz: self.email_listing_datetime_local_tz,
email_reading_headers: self.email_reading_headers,
email_reading_format: self.email_reading_format,
email_writing_headers: self.email_writing_headers,
email_sending_save_copy: self.email_sending_save_copy,
email_hooks: self.email_hooks,
accounts: HashMap::from_iter(self.accounts.clone().into_iter().map(
|(name, config)| {
(
name.clone(),
AccountConfig {
name,
email: config.email,
display_name: config.display_name,
signature_delim: config.signature_delim,
signature: config.signature,
downloads_dir: config.downloads_dir,
folder_listing_page_size: config.folder_listing_page_size,
folder_aliases: config.folder_aliases.unwrap_or_default(),
email_listing_page_size: config.email_listing_page_size,
email_listing_datetime_fmt: config.email_listing_datetime_fmt,
email_listing_datetime_local_tz: config.email_listing_datetime_local_tz,
email_reading_headers: config.email_reading_headers,
email_reading_format: config.email_reading_format.unwrap_or_default(),
email_writing_headers: config.email_writing_headers,
email_sending_save_copy: config.email_sending_save_copy,
email_hooks: config.email_hooks.unwrap_or_default(),
sync: config.sync.unwrap_or_default(),
sync_dir: config.sync_dir,
sync_folders_strategy: config.sync_folders_strategy.unwrap_or_default(),
#[cfg(feature = "pgp")]
pgp: config.pgp,
},
)
},
)),
};
let account_config = config.account(&account_name)?;
Ok((toml_account_config, account_config))
}
2022-09-22 14:38:38 +00:00
}
#[cfg(test)]
mod tests {
2023-08-28 07:04:13 +00:00
use email::{
account::PasswdConfig,
backend::{BackendConfig, MaildirConfig},
sender::{SenderConfig, SendmailConfig},
};
2023-08-28 07:04:13 +00:00
use secret::Secret;
2022-09-28 22:44:31 +00:00
#[cfg(feature = "notmuch-backend")]
2023-08-28 07:04:13 +00:00
use email::backend::NotmuchConfig;
2023-05-04 22:28:50 +00:00
#[cfg(feature = "imap-backend")]
2023-08-28 07:04:13 +00:00
use email::backend::{ImapAuthConfig, ImapConfig};
2023-05-08 12:31:36 +00:00
#[cfg(feature = "smtp-sender")]
2023-08-28 07:04:13 +00:00
use email::sender::{SmtpAuthConfig, SmtpConfig};
2022-09-28 22:44:31 +00:00
2022-09-22 14:38:38 +00:00
use std::io::Write;
use tempfile::NamedTempFile;
use super::*;
2023-07-20 09:43:28 +00:00
async fn make_config(config: &str) -> Result<DeserializedConfig> {
2022-09-22 14:38:38 +00:00
let mut file = NamedTempFile::new().unwrap();
write!(file, "{}", config).unwrap();
2023-07-20 09:43:28 +00:00
DeserializedConfig::from_opt_path(file.into_temp_path().to_str()).await
2022-09-22 14:38:38 +00:00
}
2023-07-20 09:43:28 +00:00
#[tokio::test]
async fn empty_config() {
let config = make_config("").await;
2022-09-22 14:38:38 +00:00
assert_eq!(
config.unwrap_err().root_cause().to_string(),
"config file must contain at least one account"
);
}
2023-07-20 09:43:28 +00:00
#[tokio::test]
async fn account_missing_email_field() {
let config = make_config("[account]").await;
2022-09-22 14:38:38 +00:00
2023-02-20 16:47:40 +00:00
assert!(config
.unwrap_err()
.root_cause()
.to_string()
.contains("missing field `email`"));
2022-09-22 14:38:38 +00:00
}
2023-07-20 09:43:28 +00:00
#[tokio::test]
async fn account_missing_backend_field() {
2022-09-22 14:38:38 +00:00
let config = make_config(
"[account]
email = \"test@localhost\"",
2023-07-20 09:43:28 +00:00
)
.await;
2022-09-22 14:38:38 +00:00
2022-09-28 22:44:31 +00:00
assert!(config
.unwrap_err()
.root_cause()
.to_string()
.contains("missing field `backend`"));
2022-09-22 14:38:38 +00:00
}
2023-07-20 09:43:28 +00:00
#[tokio::test]
async fn account_invalid_backend_field() {
2022-09-22 14:38:38 +00:00
let config = make_config(
"[account]
email = \"test@localhost\"
backend = \"bad\"",
2023-07-20 09:43:28 +00:00
)
.await;
2022-09-22 14:38:38 +00:00
2023-02-20 16:47:40 +00:00
assert!(config
.unwrap_err()
.root_cause()
.to_string()
.contains("unknown variant `bad`"));
2022-09-22 14:38:38 +00:00
}
2023-07-20 09:43:28 +00:00
#[tokio::test]
async fn imap_account_missing_host_field() {
2022-09-22 14:38:38 +00:00
let config = make_config(
"[account]
email = \"test@localhost\"
sender = \"none\"
backend = \"imap\"",
2023-07-20 09:43:28 +00:00
)
.await;
2022-09-22 14:38:38 +00:00
2023-02-20 16:47:40 +00:00
assert!(config
.unwrap_err()
.root_cause()
.to_string()
.contains("missing field `imap-host`"));
2022-09-22 14:38:38 +00:00
}
2023-07-20 09:43:28 +00:00
#[tokio::test]
async fn account_backend_imap_missing_port_field() {
2022-09-22 14:38:38 +00:00
let config = make_config(
"[account]
email = \"test@localhost\"
sender = \"none\"
backend = \"imap\"
imap-host = \"localhost\"",
2023-07-20 09:43:28 +00:00
)
.await;
2022-09-22 14:38:38 +00:00
2023-02-20 16:47:40 +00:00
assert!(config
.unwrap_err()
.root_cause()
.to_string()
.contains("missing field `imap-port`"));
2022-09-22 14:38:38 +00:00
}
2023-07-20 09:43:28 +00:00
#[tokio::test]
async fn account_backend_imap_missing_login_field() {
2022-09-22 14:38:38 +00:00
let config = make_config(
"[account]
email = \"test@localhost\"
sender = \"none\"
backend = \"imap\"
imap-host = \"localhost\"
imap-port = 993",
2023-07-20 09:43:28 +00:00
)
.await;
2022-09-22 14:38:38 +00:00
2023-02-20 16:47:40 +00:00
assert!(config
.unwrap_err()
.root_cause()
.to_string()
.contains("missing field `imap-login`"));
2022-09-22 14:38:38 +00:00
}
2023-07-20 09:43:28 +00:00
#[tokio::test]
async fn account_backend_imap_missing_passwd_cmd_field() {
2022-09-22 14:38:38 +00:00
let config = make_config(
"[account]
email = \"test@localhost\"
sender = \"none\"
backend = \"imap\"
imap-host = \"localhost\"
imap-port = 993
imap-login = \"login\"",
2023-07-20 09:43:28 +00:00
)
.await;
2022-09-22 14:38:38 +00:00
2023-02-20 16:47:40 +00:00
assert!(config
.unwrap_err()
.root_cause()
.to_string()
2023-05-04 22:28:50 +00:00
.contains("missing field `imap-auth`"));
2022-09-22 14:38:38 +00:00
}
2023-07-20 09:43:28 +00:00
#[tokio::test]
async fn account_backend_maildir_missing_root_dir_field() {
2022-09-22 14:38:38 +00:00
let config = make_config(
"[account]
email = \"test@localhost\"
sender = \"none\"
backend = \"maildir\"",
2023-07-20 09:43:28 +00:00
)
.await;
2022-09-22 14:38:38 +00:00
2023-02-20 16:47:40 +00:00
assert!(config
.unwrap_err()
.root_cause()
.to_string()
.contains("missing field `maildir-root-dir`"));
2022-09-22 14:38:38 +00:00
}
2022-09-28 22:44:31 +00:00
#[cfg(feature = "notmuch-backend")]
2023-07-20 09:43:28 +00:00
#[tokio::test]
async fn account_backend_notmuch_missing_db_path_field() {
2022-09-22 14:38:38 +00:00
let config = make_config(
"[account]
email = \"test@localhost\"
sender = \"none\"
backend = \"notmuch\"",
2023-07-20 09:43:28 +00:00
)
.await;
2022-09-22 14:38:38 +00:00
2023-02-20 16:47:40 +00:00
assert!(config
.unwrap_err()
.root_cause()
.to_string()
.contains("missing field `notmuch-db-path`"));
2022-09-22 14:38:38 +00:00
}
2023-07-20 09:43:28 +00:00
#[tokio::test]
async fn account_missing_sender_field() {
2022-09-22 14:38:38 +00:00
let config = make_config(
"[account]
email = \"test@localhost\"
backend = \"none\"",
2023-07-20 09:43:28 +00:00
)
.await;
2022-09-22 14:38:38 +00:00
2023-02-20 16:47:40 +00:00
assert!(config
.unwrap_err()
.root_cause()
.to_string()
.contains("missing field `sender`"));
2022-09-22 14:38:38 +00:00
}
2023-07-20 09:43:28 +00:00
#[tokio::test]
async fn account_invalid_sender_field() {
2022-09-22 14:38:38 +00:00
let config = make_config(
"[account]
email = \"test@localhost\"
backend = \"none\"
sender = \"bad\"",
2023-07-20 09:43:28 +00:00
)
.await;
2022-09-22 14:38:38 +00:00
2023-02-20 16:47:40 +00:00
assert!(config
.unwrap_err()
.root_cause()
.to_string()
.contains("unknown variant `bad`, expected one of `none`, `smtp`, `sendmail`"),);
2022-09-22 14:38:38 +00:00
}
2023-07-20 09:43:28 +00:00
#[tokio::test]
async fn account_smtp_sender_missing_host_field() {
2022-09-22 14:38:38 +00:00
let config = make_config(
"[account]
email = \"test@localhost\"
backend = \"none\"
2022-10-10 16:06:13 +00:00
sender = \"smtp\"",
2023-07-20 09:43:28 +00:00
)
.await;
2022-09-22 14:38:38 +00:00
2023-02-20 16:47:40 +00:00
assert!(config
.unwrap_err()
.root_cause()
.to_string()
.contains("missing field `smtp-host`"));
2022-09-22 14:38:38 +00:00
}
2023-07-20 09:43:28 +00:00
#[tokio::test]
async fn account_smtp_sender_missing_port_field() {
2022-09-22 14:38:38 +00:00
let config = make_config(
"[account]
email = \"test@localhost\"
backend = \"none\"
2022-10-10 16:06:13 +00:00
sender = \"smtp\"
2022-09-22 14:38:38 +00:00
smtp-host = \"localhost\"",
2023-07-20 09:43:28 +00:00
)
.await;
2022-09-22 14:38:38 +00:00
2023-02-20 16:47:40 +00:00
assert!(config
.unwrap_err()
.root_cause()
.to_string()
.contains("missing field `smtp-port`"));
2022-09-22 14:38:38 +00:00
}
2023-07-20 09:43:28 +00:00
#[tokio::test]
async fn account_smtp_sender_missing_login_field() {
2022-09-22 14:38:38 +00:00
let config = make_config(
"[account]
email = \"test@localhost\"
backend = \"none\"
2022-10-10 16:06:13 +00:00
sender = \"smtp\"
2022-09-22 14:38:38 +00:00
smtp-host = \"localhost\"
smtp-port = 25",
2023-07-20 09:43:28 +00:00
)
.await;
2022-09-22 14:38:38 +00:00
2023-02-20 16:47:40 +00:00
assert!(config
.unwrap_err()
.root_cause()
.to_string()
.contains("missing field `smtp-login`"));
2022-09-22 14:38:38 +00:00
}
2023-07-20 09:43:28 +00:00
#[tokio::test]
async fn account_smtp_sender_missing_auth_field() {
2022-09-22 14:38:38 +00:00
let config = make_config(
"[account]
email = \"test@localhost\"
backend = \"none\"
2022-10-10 16:06:13 +00:00
sender = \"smtp\"
2022-09-22 14:38:38 +00:00
smtp-host = \"localhost\"
smtp-port = 25
smtp-login = \"login\"",
2023-07-20 09:43:28 +00:00
)
.await;
2022-09-22 14:38:38 +00:00
2023-02-20 16:47:40 +00:00
assert!(config
.unwrap_err()
.root_cause()
.to_string()
2023-05-08 12:31:36 +00:00
.contains("missing field `smtp-auth`"));
2022-09-22 14:38:38 +00:00
}
2023-07-20 09:43:28 +00:00
#[tokio::test]
async fn account_sendmail_sender_missing_cmd_field() {
2022-09-22 14:38:38 +00:00
let config = make_config(
"[account]
email = \"test@localhost\"
backend = \"none\"
2022-10-10 16:06:13 +00:00
sender = \"sendmail\"",
2023-07-20 09:43:28 +00:00
)
.await;
2022-09-22 14:38:38 +00:00
2023-08-28 07:04:13 +00:00
assert_eq!(
config.unwrap(),
DeserializedConfig {
accounts: HashMap::from_iter([(
"account".into(),
DeserializedAccountConfig {
email: "test@localhost".into(),
sender: SenderConfig::Sendmail(SendmailConfig {
cmd: "/usr/sbin/sendmail".into()
}),
..DeserializedAccountConfig::default()
}
)]),
..DeserializedConfig::default()
}
)
2022-09-22 14:38:38 +00:00
}
2023-05-08 12:31:36 +00:00
#[cfg(feature = "smtp-sender")]
2023-07-20 09:43:28 +00:00
#[tokio::test]
async fn account_smtp_sender_minimum_config() {
2023-08-28 07:04:13 +00:00
use email::sender::SenderConfig;
2022-09-22 14:38:38 +00:00
let config = make_config(
"[account]
email = \"test@localhost\"
backend = \"none\"
2022-10-10 16:06:13 +00:00
sender = \"smtp\"
2022-09-22 14:38:38 +00:00
smtp-host = \"localhost\"
smtp-port = 25
smtp-login = \"login\"
2023-05-08 12:31:36 +00:00
smtp-auth = \"passwd\"
smtp-passwd = { cmd = \"echo password\" }",
2023-07-20 09:43:28 +00:00
)
.await;
2022-09-22 14:38:38 +00:00
assert_eq!(
config.unwrap(),
DeserializedConfig {
accounts: HashMap::from_iter([(
"account".into(),
DeserializedAccountConfig {
2022-09-22 14:38:38 +00:00
email: "test@localhost".into(),
sender: SenderConfig::Smtp(SmtpConfig {
2022-09-22 14:38:38 +00:00
host: "localhost".into(),
port: 25,
login: "login".into(),
2023-05-08 12:31:36 +00:00
auth: SmtpAuthConfig::Passwd(PasswdConfig {
passwd: Secret::new_cmd(String::from("echo password"))
}),
2022-09-22 14:38:38 +00:00
..SmtpConfig::default()
}),
..DeserializedAccountConfig::default()
}
2022-09-22 14:38:38 +00:00
)]),
..DeserializedConfig::default()
}
2023-07-20 09:43:28 +00:00
)
2022-09-22 14:38:38 +00:00
}
2023-07-20 09:43:28 +00:00
#[tokio::test]
async fn account_sendmail_sender_minimum_config() {
2022-09-22 14:38:38 +00:00
let config = make_config(
"[account]
email = \"test@localhost\"
backend = \"none\"
2022-10-10 16:06:13 +00:00
sender = \"sendmail\"
sendmail-cmd = \"echo send\"",
2023-07-20 09:43:28 +00:00
)
.await;
2022-09-22 14:38:38 +00:00
assert_eq!(
config.unwrap(),
DeserializedConfig {
accounts: HashMap::from_iter([(
"account".into(),
DeserializedAccountConfig {
2022-09-22 14:38:38 +00:00
email: "test@localhost".into(),
sender: SenderConfig::Sendmail(SendmailConfig {
cmd: Cmd::from("echo send")
2022-09-22 14:38:38 +00:00
}),
..DeserializedAccountConfig::default()
}
2022-09-22 14:38:38 +00:00
)]),
..DeserializedConfig::default()
}
2023-07-20 09:43:28 +00:00
)
2022-09-22 14:38:38 +00:00
}
2023-07-20 09:43:28 +00:00
#[tokio::test]
async fn account_backend_imap_minimum_config() {
2022-09-22 14:38:38 +00:00
let config = make_config(
"[account]
email = \"test@localhost\"
sender = \"none\"
backend = \"imap\"
imap-host = \"localhost\"
imap-port = 993
imap-login = \"login\"
2023-05-08 12:31:36 +00:00
imap-auth = \"passwd\"
imap-passwd = { cmd = \"echo password\" }",
2023-07-20 09:43:28 +00:00
)
.await;
2022-09-22 14:38:38 +00:00
assert_eq!(
config.unwrap(),
DeserializedConfig {
accounts: HashMap::from_iter([(
"account".into(),
DeserializedAccountConfig {
email: "test@localhost".into(),
backend: BackendConfig::Imap(ImapConfig {
2022-09-22 14:38:38 +00:00
host: "localhost".into(),
port: 993,
login: "login".into(),
2023-05-08 12:31:36 +00:00
auth: ImapAuthConfig::Passwd(PasswdConfig {
passwd: Secret::new_cmd(String::from("echo password"))
}),
2022-09-22 14:38:38 +00:00
..ImapConfig::default()
}),
..DeserializedAccountConfig::default()
}
2022-09-22 14:38:38 +00:00
)]),
..DeserializedConfig::default()
}
2023-07-20 09:43:28 +00:00
)
2022-09-22 14:38:38 +00:00
}
2023-07-20 09:43:28 +00:00
#[tokio::test]
async fn account_backend_maildir_minimum_config() {
2022-09-22 14:38:38 +00:00
let config = make_config(
"[account]
email = \"test@localhost\"
sender = \"none\"
backend = \"maildir\"
maildir-root-dir = \"/tmp/maildir\"",
2023-07-20 09:43:28 +00:00
)
.await;
2022-09-22 14:38:38 +00:00
assert_eq!(
config.unwrap(),
DeserializedConfig {
accounts: HashMap::from_iter([(
"account".into(),
DeserializedAccountConfig {
email: "test@localhost".into(),
backend: BackendConfig::Maildir(MaildirConfig {
2022-09-22 14:38:38 +00:00
root_dir: "/tmp/maildir".into(),
}),
..DeserializedAccountConfig::default()
}
2022-09-22 14:38:38 +00:00
)]),
..DeserializedConfig::default()
}
2023-07-20 09:43:28 +00:00
)
2022-09-22 14:38:38 +00:00
}
2022-09-28 22:44:31 +00:00
#[cfg(feature = "notmuch-backend")]
2023-07-20 09:43:28 +00:00
#[tokio::test]
async fn account_backend_notmuch_minimum_config() {
2022-09-22 14:38:38 +00:00
let config = make_config(
"[account]
email = \"test@localhost\"
sender = \"none\"
backend = \"notmuch\"
notmuch-db-path = \"/tmp/notmuch.db\"",
2023-07-20 09:43:28 +00:00
)
.await;
2022-09-22 14:38:38 +00:00
assert_eq!(
config.unwrap(),
DeserializedConfig {
accounts: HashMap::from_iter([(
"account".into(),
DeserializedAccountConfig {
email: "test@localhost".into(),
backend: BackendConfig::Notmuch(NotmuchConfig {
2022-09-22 14:38:38 +00:00
db_path: "/tmp/notmuch.db".into(),
}),
..DeserializedAccountConfig::default()
}
2022-09-22 14:38:38 +00:00
)]),
..DeserializedConfig::default()
}
);
}
}