rename config and account config

This commit is contained in:
Clément DOUIN 2023-11-29 07:52:08 +01:00
parent fb8f356e8c
commit 41a2f02699
No known key found for this signature in database
GPG key ID: 353E4A18EE0FAB72
8 changed files with 64 additions and 61 deletions

View file

@ -45,11 +45,13 @@ use email::{
}; };
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use crate::{account::DeserializedAccountConfig, Envelopes, IdMapper}; use crate::{account::TomlAccountConfig, Envelopes, IdMapper};
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] #[derive(Clone, Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")] #[serde(rename_all = "kebab-case")]
pub enum BackendKind { pub enum BackendKind {
#[default]
None,
Maildir, Maildir,
#[serde(skip_deserializing)] #[serde(skip_deserializing)]
MaildirForSync, MaildirForSync,
@ -123,7 +125,7 @@ pub struct BackendContext {
} }
pub struct Backend { pub struct Backend {
toml_account_config: DeserializedAccountConfig, toml_account_config: TomlAccountConfig,
backend: email::backend::Backend<BackendContext>, backend: email::backend::Backend<BackendContext>,
} }
@ -262,13 +264,13 @@ impl Deref for Backend {
} }
pub struct BackendBuilder { pub struct BackendBuilder {
toml_account_config: DeserializedAccountConfig, toml_account_config: TomlAccountConfig,
builder: email::backend::BackendBuilder<BackendContextBuilder>, builder: email::backend::BackendBuilder<BackendContextBuilder>,
} }
impl BackendBuilder { impl BackendBuilder {
pub async fn new( pub async fn new(
toml_account_config: DeserializedAccountConfig, toml_account_config: TomlAccountConfig,
account_config: AccountConfig, account_config: AccountConfig,
) -> Result<Self> { ) -> Result<Self> {
let backend_ctx_builder = BackendContextBuilder { let backend_ctx_builder = BackendContextBuilder {

View file

@ -17,7 +17,7 @@ use std::{collections::HashMap, fs, path::PathBuf, process::exit};
use toml; use toml;
use crate::{ use crate::{
account::DeserializedAccountConfig, account::TomlAccountConfig,
backend::BackendKind, backend::BackendKind,
config::{prelude::*, wizard}, config::{prelude::*, wizard},
wizard_prompt, wizard_warn, wizard_prompt, wizard_warn,
@ -26,7 +26,7 @@ use crate::{
/// Represents the user config file. /// Represents the user config file.
#[derive(Clone, Debug, Default, Eq, PartialEq, Deserialize, Serialize)] #[derive(Clone, Debug, Default, Eq, PartialEq, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")] #[serde(rename_all = "kebab-case")]
pub struct DeserializedConfig { pub struct TomlConfig {
#[serde(alias = "name")] #[serde(alias = "name")]
pub display_name: Option<String>, pub display_name: Option<String>,
pub signature_delim: Option<String>, pub signature_delim: Option<String>,
@ -48,12 +48,12 @@ pub struct DeserializedConfig {
pub email_hooks: Option<EmailHooks>, pub email_hooks: Option<EmailHooks>,
#[serde(flatten)] #[serde(flatten)]
pub accounts: HashMap<String, DeserializedAccountConfig>, pub accounts: HashMap<String, TomlAccountConfig>,
} }
impl DeserializedConfig { impl TomlConfig {
/// Tries to create a config from an optional path. /// Tries to create a config from an optional path.
pub async fn from_opt_path(path: Option<&str>) -> Result<Self> { pub async fn from_maybe_path(path: Option<&str>) -> Result<Self> {
debug!("path: {:?}", path); debug!("path: {:?}", path);
let config = if let Some(path) = path.map(PathBuf::from).or_else(Self::path) { let config = if let Some(path) = path.map(PathBuf::from).or_else(Self::path) {
@ -108,7 +108,7 @@ impl DeserializedConfig {
self, self,
account_name: Option<&str>, account_name: Option<&str>,
disable_cache: bool, disable_cache: bool,
) -> Result<(DeserializedAccountConfig, AccountConfig)> { ) -> Result<(TomlAccountConfig, AccountConfig)> {
let (account_name, mut toml_account_config) = match account_name { let (account_name, mut toml_account_config) = match account_name {
Some("default") | Some("") | None => self Some("default") | Some("") | None => self
.accounts .accounts
@ -229,10 +229,10 @@ mod tests {
use super::*; use super::*;
async fn make_config(config: &str) -> Result<DeserializedConfig> { async fn make_config(config: &str) -> Result<TomlConfig> {
let mut file = NamedTempFile::new().unwrap(); let mut file = NamedTempFile::new().unwrap();
write!(file, "{}", config).unwrap(); write!(file, "{}", config).unwrap();
DeserializedConfig::from_opt_path(file.into_temp_path().to_str()).await TomlConfig::from_maybe_path(file.into_temp_path().to_str()).await
} }
#[tokio::test] #[tokio::test]
@ -515,18 +515,18 @@ mod tests {
assert_eq!( assert_eq!(
config.unwrap(), config.unwrap(),
DeserializedConfig { TomlConfig {
accounts: HashMap::from_iter([( accounts: HashMap::from_iter([(
"account".into(), "account".into(),
DeserializedAccountConfig { TomlAccountConfig {
email: "test@localhost".into(), email: "test@localhost".into(),
sender: SenderConfig::Sendmail(SendmailConfig { sender: SenderConfig::Sendmail(SendmailConfig {
cmd: "/usr/sbin/sendmail".into() cmd: "/usr/sbin/sendmail".into()
}), }),
..DeserializedAccountConfig::default() ..TomlAccountConfig::default()
} }
)]), )]),
..DeserializedConfig::default() ..TomlConfig::default()
} }
) )
} }
@ -551,10 +551,10 @@ mod tests {
assert_eq!( assert_eq!(
config.unwrap(), config.unwrap(),
DeserializedConfig { TomlConfig {
accounts: HashMap::from_iter([( accounts: HashMap::from_iter([(
"account".into(), "account".into(),
DeserializedAccountConfig { TomlAccountConfig {
email: "test@localhost".into(), email: "test@localhost".into(),
sender: SenderConfig::Smtp(SmtpConfig { sender: SenderConfig::Smtp(SmtpConfig {
host: "localhost".into(), host: "localhost".into(),
@ -565,10 +565,10 @@ mod tests {
}), }),
..SmtpConfig::default() ..SmtpConfig::default()
}), }),
..DeserializedAccountConfig::default() ..TomlAccountConfig::default()
} }
)]), )]),
..DeserializedConfig::default() ..TomlConfig::default()
} }
) )
} }
@ -586,18 +586,18 @@ mod tests {
assert_eq!( assert_eq!(
config.unwrap(), config.unwrap(),
DeserializedConfig { TomlConfig {
accounts: HashMap::from_iter([( accounts: HashMap::from_iter([(
"account".into(), "account".into(),
DeserializedAccountConfig { TomlAccountConfig {
email: "test@localhost".into(), email: "test@localhost".into(),
sender: SenderConfig::Sendmail(SendmailConfig { sender: SenderConfig::Sendmail(SendmailConfig {
cmd: Cmd::from("echo send") cmd: Cmd::from("echo send")
}), }),
..DeserializedAccountConfig::default() ..TomlAccountConfig::default()
} }
)]), )]),
..DeserializedConfig::default() ..TomlConfig::default()
} }
) )
} }
@ -619,10 +619,10 @@ mod tests {
assert_eq!( assert_eq!(
config.unwrap(), config.unwrap(),
DeserializedConfig { TomlConfig {
accounts: HashMap::from_iter([( accounts: HashMap::from_iter([(
"account".into(), "account".into(),
DeserializedAccountConfig { TomlAccountConfig {
email: "test@localhost".into(), email: "test@localhost".into(),
backend: BackendConfig::Imap(ImapConfig { backend: BackendConfig::Imap(ImapConfig {
host: "localhost".into(), host: "localhost".into(),
@ -633,10 +633,10 @@ mod tests {
}), }),
..ImapConfig::default() ..ImapConfig::default()
}), }),
..DeserializedAccountConfig::default() ..TomlAccountConfig::default()
} }
)]), )]),
..DeserializedConfig::default() ..TomlConfig::default()
} }
) )
} }
@ -654,18 +654,18 @@ mod tests {
assert_eq!( assert_eq!(
config.unwrap(), config.unwrap(),
DeserializedConfig { TomlConfig {
accounts: HashMap::from_iter([( accounts: HashMap::from_iter([(
"account".into(), "account".into(),
DeserializedAccountConfig { TomlAccountConfig {
email: "test@localhost".into(), email: "test@localhost".into(),
backend: BackendConfig::Maildir(MaildirConfig { backend: BackendConfig::Maildir(MaildirConfig {
root_dir: "/tmp/maildir".into(), root_dir: "/tmp/maildir".into(),
}), }),
..DeserializedAccountConfig::default() ..TomlAccountConfig::default()
} }
)]), )]),
..DeserializedConfig::default() ..TomlConfig::default()
} }
) )
} }
@ -684,18 +684,18 @@ mod tests {
assert_eq!( assert_eq!(
config.unwrap(), config.unwrap(),
DeserializedConfig { TomlConfig {
accounts: HashMap::from_iter([( accounts: HashMap::from_iter([(
"account".into(), "account".into(),
DeserializedAccountConfig { TomlAccountConfig {
email: "test@localhost".into(), email: "test@localhost".into(),
backend: BackendConfig::Notmuch(NotmuchConfig { backend: BackendConfig::Notmuch(NotmuchConfig {
db_path: "/tmp/notmuch.db".into(), db_path: "/tmp/notmuch.db".into(),
}), }),
..DeserializedAccountConfig::default() ..TomlAccountConfig::default()
} }
)]), )]),
..DeserializedConfig::default() ..TomlConfig::default()
} }
); );
} }

View file

@ -1,4 +1,4 @@
use super::DeserializedConfig; use super::TomlConfig;
use crate::account; use crate::account;
use anyhow::Result; use anyhow::Result;
use dialoguer::{theme::ColorfulTheme, Confirm, Input, Password, Select}; use dialoguer::{theme::ColorfulTheme, Confirm, Input, Password, Select};
@ -31,10 +31,10 @@ macro_rules! wizard_log {
pub(crate) static THEME: Lazy<ColorfulTheme> = Lazy::new(ColorfulTheme::default); pub(crate) static THEME: Lazy<ColorfulTheme> = Lazy::new(ColorfulTheme::default);
pub(crate) async fn configure() -> Result<DeserializedConfig> { pub(crate) async fn configure() -> Result<TomlConfig> {
wizard_log!("Configuring your first account:"); wizard_log!("Configuring your first account:");
let mut config = DeserializedConfig::default(); let mut config = TomlConfig::default();
while let Some((name, account_config)) = account::wizard::configure().await? { while let Some((name, account_config)) = account::wizard::configure().await? {
config.accounts.insert(name, account_config); config.accounts.insert(name, account_config);

View file

@ -13,7 +13,7 @@ use crate::{
ui::Table, ui::Table,
}; };
use super::{Account, DeserializedAccountConfig}; use super::{Account, TomlAccountConfig};
/// Represents the list of printable accounts. /// Represents the list of printable accounts.
#[derive(Debug, Default, Serialize)] #[derive(Debug, Default, Serialize)]
@ -36,8 +36,8 @@ impl PrintTable for Accounts {
} }
} }
impl From<Iter<'_, String, DeserializedAccountConfig>> for Accounts { impl From<Iter<'_, String, TomlAccountConfig>> for Accounts {
fn from(map: Iter<'_, String, DeserializedAccountConfig>) -> Self { fn from(map: Iter<'_, String, TomlAccountConfig>) -> Self {
let mut accounts: Vec<_> = map let mut accounts: Vec<_> = map
.map(|(name, account)| { .map(|(name, account)| {
let mut backends = String::new(); let mut backends = String::new();

View file

@ -29,7 +29,7 @@ use crate::{
/// Represents all existing kind of account config. /// Represents all existing kind of account config.
#[derive(Clone, Debug, Default, Eq, PartialEq, Deserialize, Serialize)] #[derive(Clone, Debug, Default, Eq, PartialEq, Deserialize, Serialize)]
#[serde(tag = "backend", rename_all = "kebab-case")] #[serde(tag = "backend", rename_all = "kebab-case")]
pub struct DeserializedAccountConfig { pub struct TomlAccountConfig {
pub default: Option<bool>, pub default: Option<bool>,
pub email: String, pub email: String,
@ -87,7 +87,7 @@ pub struct DeserializedAccountConfig {
pub pgp: Option<PgpConfig>, pub pgp: Option<PgpConfig>,
} }
impl DeserializedAccountConfig { impl TomlAccountConfig {
pub fn add_folder_kind(&self) -> Option<&BackendKind> { pub fn add_folder_kind(&self) -> Option<&BackendKind> {
self.folder self.folder
.as_ref() .as_ref()

View file

@ -20,7 +20,7 @@ use crate::{
backend::BackendContextBuilder, backend::BackendContextBuilder,
config::{ config::{
wizard::{prompt_passwd, prompt_secret}, wizard::{prompt_passwd, prompt_secret},
DeserializedConfig, TomlConfig,
}, },
printer::{PrintTableOpts, Printer}, printer::{PrintTableOpts, Printer},
Accounts, Accounts,
@ -120,7 +120,7 @@ pub async fn configure(config: &AccountConfig, reset: bool) -> Result<()> {
pub fn list<'a, P: Printer>( pub fn list<'a, P: Printer>(
max_width: Option<usize>, max_width: Option<usize>,
config: &AccountConfig, config: &AccountConfig,
deserialized_config: &DeserializedConfig, deserialized_config: &TomlConfig,
printer: &mut P, printer: &mut P,
) -> Result<()> { ) -> Result<()> {
info!("entering the list accounts handler"); info!("entering the list accounts handler");
@ -298,7 +298,7 @@ mod tests {
use termcolor::ColorSpec; use termcolor::ColorSpec;
use crate::{ use crate::{
account::DeserializedAccountConfig, account::TomlAccountConfig,
printer::{Print, PrintTable, WriteColor}, printer::{Print, PrintTable, WriteColor},
}; };
@ -367,16 +367,16 @@ mod tests {
let mut printer = PrinterServiceTest::default(); let mut printer = PrinterServiceTest::default();
let config = AccountConfig::default(); let config = AccountConfig::default();
let deserialized_config = DeserializedConfig { let deserialized_config = TomlConfig {
accounts: HashMap::from_iter([( accounts: HashMap::from_iter([(
"account-1".into(), "account-1".into(),
DeserializedAccountConfig { TomlAccountConfig {
default: Some(true), default: Some(true),
backend: BackendConfig::Imap(ImapConfig::default()), backend: BackendConfig::Imap(ImapConfig::default()),
..DeserializedAccountConfig::default() ..TomlAccountConfig::default()
}, },
)]), )]),
..DeserializedConfig::default() ..TomlConfig::default()
}; };
assert!(list(None, &config, &deserialized_config, &mut printer).is_ok()); assert!(list(None, &config, &deserialized_config, &mut printer).is_ok());

View file

@ -4,10 +4,10 @@ use email_address::EmailAddress;
use crate::config::wizard::THEME; use crate::config::wizard::THEME;
use super::DeserializedAccountConfig; use super::TomlAccountConfig;
pub(crate) async fn configure() -> Result<Option<(String, DeserializedAccountConfig)>> { pub(crate) async fn configure() -> Result<Option<(String, TomlAccountConfig)>> {
let mut config = DeserializedAccountConfig::default(); let mut config = TomlAccountConfig::default();
let account_name = Input::with_theme(&*THEME) let account_name = Input::with_theme(&*THEME)
.with_prompt("Account name") .with_prompt("Account name")

View file

@ -11,7 +11,7 @@ use himalaya::{
account, account,
backend::BackendBuilder, backend::BackendBuilder,
cache, compl, cache, compl,
config::{self, DeserializedConfig}, config::{self, TomlConfig},
email, flag, folder, man, output, email, flag, folder, man, output,
printer::StdoutPrinter, printer::StdoutPrinter,
tpl, tpl,
@ -53,11 +53,11 @@ async fn main() -> Result<()> {
let default_env_filter = env_logger::DEFAULT_FILTER_ENV; let default_env_filter = env_logger::DEFAULT_FILTER_ENV;
env_logger::init_from_env(env_logger::Env::default().filter_or(default_env_filter, "off")); env_logger::init_from_env(env_logger::Env::default().filter_or(default_env_filter, "off"));
// checks mailto command before app initialization // check mailto command before app initialization
let raw_args: Vec<String> = env::args().collect(); let raw_args: Vec<String> = env::args().collect();
if raw_args.len() > 1 && raw_args[1].starts_with("mailto:") { if raw_args.len() > 1 && raw_args[1].starts_with("mailto:") {
let url = Url::parse(&raw_args[1])?; let url = Url::parse(&raw_args[1])?;
let (toml_account_config, account_config) = DeserializedConfig::from_opt_path(None) let (toml_account_config, account_config) = TomlConfig::from_maybe_path(None)
.await? .await?
.into_account_configs(None, false)?; .into_account_configs(None, false)?;
let backend_builder = let backend_builder =
@ -88,11 +88,12 @@ async fn main() -> Result<()> {
_ => (), _ => (),
} }
let folder = folder::args::parse_source_arg(&m); let maybe_config_path = config::args::parse_arg(&m);
let disable_cache = cache::args::parse_disable_cache_flag(&m);
let maybe_account_name = account::args::parse_arg(&m); let maybe_account_name = account::args::parse_arg(&m);
let disable_cache = cache::args::parse_disable_cache_flag(&m);
let folder = folder::args::parse_source_arg(&m);
let toml_config = DeserializedConfig::from_opt_path(config::args::parse_arg(&m)).await?; let toml_config = TomlConfig::from_maybe_path(maybe_config_path).await?;
let mut printer = StdoutPrinter::try_from(&m)?; let mut printer = StdoutPrinter::try_from(&m)?;