/*
* meli - configuration module.
*
* Copyright 2017 Manos Pitsidianakis
*
* This file is part of meli.
*
* meli is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* meli is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with meli. If not, see .
*/
//! Configuration logic and `config.toml` interfaces.
extern crate serde;
extern crate toml;
extern crate xdg;
use std::{
collections::HashSet,
io::Read,
process::{Command, Stdio},
};
use melib::{
backends::{MailboxHash, TagHash},
search::Query,
SortField, SortOrder, StderrLogger,
};
use crate::{
conf::deserializers::non_empty_opt_string,
terminal::{Ask, Color},
};
#[rustfmt::skip]
mod overrides;
pub use overrides::*;
pub mod composing;
pub mod notifications;
pub mod pager;
pub mod pgp;
pub mod tags;
#[macro_use]
pub mod shortcuts;
mod listing;
pub mod terminal;
mod themes;
use std::{
collections::HashMap,
env,
fs::OpenOptions,
io::{self, BufRead, Write},
os::unix::fs::PermissionsExt,
path::{Path, PathBuf},
};
use indexmap::IndexMap;
use melib::{
conf::{AccountSettings, ActionFlag, MailboxConf, ToggleFlag},
error::*,
};
use pager::PagerSettings;
use serde::{de, Deserialize, Deserializer, Serialize, Serializer};
pub use themes::*;
pub use self::{composing::*, pgp::*, shortcuts::*, tags::*};
use self::{
default_vals::*, listing::ListingSettings, notifications::NotificationsSettings,
terminal::TerminalSettings,
};
#[macro_export]
macro_rules! split_command {
($cmd:expr) => {{
$cmd.split_whitespace().collect::>()
}};
}
#[macro_export]
macro_rules! account_settings {
($context:ident[$account_hash:expr].$setting:ident.$field:ident) => {{
$context.accounts[&$account_hash]
.settings
.conf_override
.$setting
.$field
.as_ref()
.unwrap_or(&$context.settings.$setting.$field)
}};
}
#[macro_export]
macro_rules! mailbox_settings {
($context:ident[$account_hash:expr][$mailbox_path:expr].$setting:ident.$field:ident) => {{
$context.accounts[&$account_hash][$mailbox_path]
.conf
.conf_override
.$setting
.$field
.as_ref()
.or($context.accounts[&$account_hash]
.settings
.conf_override
.$setting
.$field
.as_ref())
.unwrap_or(&$context.settings.$setting.$field)
}};
}
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct MailUIConf {
#[serde(default)]
pub pager: PagerSettingsOverride,
#[serde(default)]
pub listing: ListingSettingsOverride,
#[serde(default)]
pub notifications: NotificationsSettingsOverride,
#[serde(default)]
pub shortcuts: ShortcutsOverride,
#[serde(default)]
pub composing: ComposingSettingsOverride,
#[serde(default)]
pub identity: Option,
#[serde(default)]
pub tags: TagsSettingsOverride,
#[serde(default)]
pub themes: Option,
#[serde(default)]
pub pgp: PGPSettingsOverride,
}
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[serde(default)]
pub struct FileMailboxConf {
#[serde(flatten)]
pub conf_override: MailUIConf,
#[serde(default = "false_val")]
pub collapsed: bool,
#[serde(flatten)]
pub mailbox_conf: MailboxConf,
}
impl FileMailboxConf {
pub fn conf_override(&self) -> &MailUIConf {
&self.conf_override
}
pub fn mailbox_conf(&self) -> &MailboxConf {
&self.mailbox_conf
}
}
use crate::conf::deserializers::extra_settings;
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
pub struct FileAccount {
pub root_mailbox: String,
pub format: String,
pub identity: String,
#[serde(default)]
pub extra_identities: Vec,
#[serde(default = "none", skip_serializing_if = "Option::is_none")]
pub display_name: Option,
#[serde(default = "false_val")]
pub read_only: bool,
#[serde(default)]
pub subscribed_mailboxes: Vec,
#[serde(default)]
pub mailboxes: IndexMap,
#[serde(default)]
pub search_backend: SearchBackend,
#[serde(default)]
pub order: (SortField, SortOrder),
#[serde(default = "false_val")]
pub manual_refresh: bool,
#[serde(default = "none", skip_serializing_if = "Option::is_none")]
pub refresh_command: Option,
#[serde(flatten)]
pub conf_override: MailUIConf,
#[serde(flatten)]
#[serde(
deserialize_with = "extra_settings",
skip_serializing_if = "IndexMap::is_empty"
)]
/// Use custom deserializer to convert any given value (eg `bool`, number,
/// etc) to `String`.
pub extra: IndexMap,
}
impl FileAccount {
pub fn mailboxes(&self) -> &IndexMap {
&self.mailboxes
}
pub fn search_backend(&self) -> &SearchBackend {
&self.search_backend
}
}
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct FileSettings {
pub accounts: IndexMap,
#[serde(default)]
pub pager: PagerSettings,
#[serde(default)]
pub listing: ListingSettings,
#[serde(default)]
pub notifications: NotificationsSettings,
#[serde(default)]
pub shortcuts: Shortcuts,
pub composing: ComposingSettings,
#[serde(default)]
pub tags: TagsSettings,
#[serde(default)]
pub pgp: PGPSettings,
#[serde(default)]
pub terminal: TerminalSettings,
#[serde(default)]
pub log: LogSettings,
}
#[derive(Clone, Debug, Default, Serialize)]
pub struct AccountConf {
pub account: AccountSettings,
pub sent_mailbox: Option,
pub conf: FileAccount,
pub conf_override: MailUIConf,
pub mailbox_confs: IndexMap,
}
impl AccountConf {
pub fn account(&self) -> &AccountSettings {
&self.account
}
pub fn account_mut(&mut self) -> &mut AccountSettings {
&mut self.account
}
pub fn conf(&self) -> &FileAccount {
&self.conf
}
pub fn conf_mut(&mut self) -> &mut FileAccount {
&mut self.conf
}
}
impl From for AccountConf {
fn from(x: FileAccount) -> Self {
let format = x.format.to_lowercase();
let root_mailbox = x.root_mailbox.clone();
let identity = x.identity.clone();
let display_name = x.display_name.clone();
let order = x.order;
let mailboxes = x
.mailboxes
.iter()
.map(|(k, v)| (k.clone(), v.mailbox_conf.clone()))
.collect();
let acc = AccountSettings {
name: String::new(),
root_mailbox,
format,
identity,
extra_identities: x.extra_identities.clone(),
read_only: x.read_only,
display_name,
order,
subscribed_mailboxes: x.subscribed_mailboxes.clone(),
mailboxes,
manual_refresh: x.manual_refresh,
extra: x.extra.clone().into_iter().collect(),
};
let mailbox_confs = x.mailboxes.clone();
Self {
account: acc,
sent_mailbox: None,
conf_override: x.conf_override.clone(),
conf: x,
mailbox_confs,
}
}
}
pub fn get_config_file() -> Result {
let xdg_dirs = xdg::BaseDirectories::with_prefix("meli").map_err(|err| {
Error::new(format!(
"Could not detect XDG directories for user: {}",
err
))
.set_source(Some(std::sync::Arc::new(Box::new(err))))
})?;
match env::var("MELI_CONFIG") {
Ok(path) => Ok(PathBuf::from(path)),
Err(_) => Ok(xdg_dirs
.place_config_file("config.toml")
.chain_err_summary(|| {
format!(
"Cannot create configuration directory in {}",
xdg_dirs.get_config_home().display()
)
})?),
}
}
pub fn get_included_configs(conf_path: PathBuf) -> Result> {
const M4_PREAMBLE: &str = r#"divert(-1)dnl
define(`include', `divert(0)$1
divert(-1)
')dnl
changequote(`"', `"')dnl
"#;
let mut ret = vec![];
let prefix = conf_path.parent().unwrap().to_path_buf();
let mut stack = vec![(None::, conf_path)];
let mut contents = String::new();
while let Some((parent, p)) = stack.pop() {
if !p.exists() || p.is_dir() {
return Err(format!(
"Path {}{included}{in_parent} {msg}.",
p.display(),
included = if parent.is_some() {
" which is included in "
} else {
""
},
in_parent = if let Some(parent) = parent {
std::borrow::Cow::Owned(parent.display().to_string())
} else {
std::borrow::Cow::Borrowed("")
},
msg = if !p.exists() {
"does not exist"
} else {
"is a directory, not a text file"
}
)
.into());
}
contents.clear();
let mut file = std::fs::File::open(&p)?;
file.read_to_string(&mut contents)?;
let mut handle = match Command::new("m4")
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
{
Ok(handle) => handle,
Err(error) => match error.kind() {
io::ErrorKind::NotFound => {
return Err("`m4` executable not found. Please install.".into())
}
_ => return Err(error.into()),
},
};
let mut stdin = handle.stdin.take().unwrap();
stdin.write_all(M4_PREAMBLE.as_bytes())?;
stdin.write_all(contents.as_bytes())?;
drop(stdin);
let stdout = handle.wait_with_output()?.stdout.clone();
for subpath in stdout.lines() {
let subpath = subpath?;
let path = &Path::new(&subpath);
if path.is_absolute() {
stack.push((Some(p.clone()), path.to_path_buf()));
} else {
stack.push((Some(p.clone()), prefix.join(path)));
}
}
ret.push(p);
}
Ok(ret)
}
pub fn expand_config(conf_path: PathBuf) -> Result {
let _paths = get_included_configs(conf_path.clone())?;
const M4_PREAMBLE: &str = r#"define(`builtin_include', defn(`include'))dnl
define(`include', `builtin_include(substr($1,1,decr(decr(len($1)))))dnl')dnl
"#;
let mut contents = String::new();
contents.clear();
let mut file = std::fs::File::open(&conf_path)?;
file.read_to_string(&mut contents)?;
let mut handle = Command::new("m4")
.current_dir(conf_path.parent().unwrap_or_else(|| Path::new("/")))
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()?;
let mut stdin = handle.stdin.take().unwrap();
stdin.write_all(M4_PREAMBLE.as_bytes())?;
stdin.write_all(contents.as_bytes())?;
drop(stdin);
let stdout = handle.wait_with_output()?.stdout;
Ok(String::from_utf8_lossy(&stdout).to_string())
}
impl FileSettings {
pub fn new() -> Result {
let config_path = get_config_file()?;
if !config_path.exists() {
let path_string = config_path.display().to_string();
if path_string.is_empty() {
return Err(Error::new("No configuration found."));
}
#[cfg(not(test))]
let ask = Ask {
message: format!(
"No configuration found. Would you like to generate one in {}?",
path_string
),
};
#[cfg(not(test))]
if ask.run() {
create_config_file(&config_path)?;
return Err(Error::new(
"Edit the sample configuration and relaunch meli.",
));
}
#[cfg(test)]
return Ok(Self::default());
#[cfg(not(test))]
return Err(Error::new("No configuration file found."));
}
Self::validate(config_path, true, false)
}
pub fn validate(path: PathBuf, interactive: bool, clear_extras: bool) -> Result {
let s = pp::pp(&path)?;
let map: toml::value::Table = toml::from_str(&s).map_err(|err| {
Error::new(format!(
"{}: Config file is invalid TOML; {}",
path.display(),
err
))
})?;
// Check that a global composing option is set and return a user-friendly
// error message because the default serde one is confusing.
if !map.contains_key("composing") {
let err_msg = r#"You must set a global `composing` option. If you override `composing` in each account, you can use a dummy global like follows:
[composing]
send_mail = 'false'
This is required so that you don't accidentally start meli and find out later that you can't send emails."#;
if interactive {
println!("{}", err_msg);
let ask = Ask {
message: format!(
"Would you like to append this dummy value in your configuration file {} \
and continue?",
path.display()
),
};
if ask.run() {
let mut file = OpenOptions::new().append(true).open(&path)?;
file.write_all(b"[composing]\nsend_mail = 'false'\n")
.map_err(|err| {
Error::new(format!("Could not append to {}: {}", path.display(), err))
})?;
return Self::validate(path, interactive, clear_extras);
}
}
return Err(Error::new(format!(
"{}\n\nEdit the {} and relaunch meli.",
if interactive { "" } else { err_msg },
path.display()
)));
}
let mut s: Self = toml::from_str(&s).map_err(|err| {
Error::new(format!(
"{}: Config file contains errors; {}",
path.display(),
err
))
})?;
let backends = melib::backends::Backends::new();
let Themes {
light: default_light,
dark: default_dark,
..
} = Themes::default();
for (k, v) in default_light.keys.into_iter() {
if !s.terminal.themes.light.contains_key(&k) {
s.terminal.themes.light.insert(k, v);
}
}
for theme in s.terminal.themes.other_themes.values_mut() {
for (k, v) in default_dark.keys.clone().into_iter() {
if !theme.contains_key(&k) {
theme.insert(k, v);
}
}
}
for (k, v) in default_dark.keys.into_iter() {
if !s.terminal.themes.dark.contains_key(&k) {
s.terminal.themes.dark.insert(k, v);
}
}
match s.terminal.theme.as_str() {
"dark" | "light" => {}
t if s.terminal.themes.other_themes.contains_key(t) => {}
t => {
return Err(Error::new(format!("Theme `{}` was not found.", t)));
}
}
s.terminal.themes.validate()?;
for (name, acc) in s.accounts.iter_mut() {
let FileAccount {
root_mailbox,
format,
identity,
extra_identities,
read_only,
display_name,
order,
subscribed_mailboxes,
mailboxes,
extra,
manual_refresh,
refresh_command: _,
search_backend: _,
conf_override: _,
} = acc.clone();
let lowercase_format = format.to_lowercase();
let mut s = AccountSettings {
name: name.to_string(),
root_mailbox,
format: format.clone(),
identity,
extra_identities,
read_only,
display_name,
order,
subscribed_mailboxes,
manual_refresh,
mailboxes: mailboxes
.into_iter()
.map(|(k, v)| (k, v.mailbox_conf))
.collect(),
extra: extra.into_iter().collect(),
};
s.validate_config()?;
backends.validate_config(&lowercase_format, &mut s)?;
if !s.extra.is_empty() {
return Err(Error::new(format!(
"Unrecognised configuration values: {:?}",
s.extra
)));
}
if clear_extras {
acc.extra.clear();
}
}
Ok(s)
}
}
#[derive(Clone, Debug, Default, Serialize)]
pub struct Settings {
pub accounts: IndexMap,
pub pager: PagerSettings,
pub listing: ListingSettings,
pub notifications: NotificationsSettings,
pub shortcuts: Shortcuts,
pub tags: TagsSettings,
pub composing: ComposingSettings,
pub pgp: PGPSettings,
pub terminal: TerminalSettings,
pub log: LogSettings,
#[serde(skip)]
pub _logger: StderrLogger,
}
impl Settings {
pub fn new() -> Result {
let fs = FileSettings::new()?;
let mut s: IndexMap = IndexMap::new();
for (id, x) in fs.accounts {
let mut ac = AccountConf::from(x);
ac.account.name = id.clone();
s.insert(id, ac);
}
let mut _logger = StderrLogger::new(fs.log.maximum_level);
if let Some(ref log_path) = fs.log.log_file {
_logger.change_log_dest(log_path.into());
}
Ok(Self {
accounts: s,
pager: fs.pager,
listing: fs.listing,
notifications: fs.notifications,
shortcuts: fs.shortcuts,
tags: fs.tags,
composing: fs.composing,
pgp: fs.pgp,
terminal: fs.terminal,
log: fs.log,
_logger,
})
}
pub fn without_accounts() -> Result {
let fs = FileSettings::new()?;
let mut _logger = StderrLogger::new(fs.log.maximum_level);
if let Some(ref log_path) = fs.log.log_file {
_logger.change_log_dest(log_path.into());
}
Ok(Self {
accounts: IndexMap::new(),
pager: fs.pager,
listing: fs.listing,
notifications: fs.notifications,
shortcuts: fs.shortcuts,
tags: fs.tags,
composing: fs.composing,
pgp: fs.pgp,
terminal: fs.terminal,
log: fs.log,
_logger,
})
}
}
#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)]
pub enum IndexStyle {
Plain,
Threaded,
#[default]
Compact,
Conversations,
}
/*
* Deserialize default functions
*/
mod default_vals {
pub(in crate::conf) fn false_val>() -> T {
false.into()
}
pub(in crate::conf) fn true_val>() -> T {
true.into()
}
pub(in crate::conf) fn zero_val>() -> T {
0.into()
}
pub(in crate::conf) fn eighty_val>() -> T {
80.into()
}
pub(in crate::conf) fn none() -> Option {
None
}
pub(in crate::conf) fn internal_value_false>(
) -> T {
melib::conf::ToggleFlag::InternalVal(false).into()
}
pub(in crate::conf) fn internal_value_true>() -> T
{
melib::conf::ToggleFlag::InternalVal(true).into()
}
pub(in crate::conf) fn action_internal_value_false>(
) -> T {
melib::conf::ActionFlag::InternalVal(false).into()
}
//pub(in crate::conf) fn action_internal_value_true<
// T: std::convert::From,
//>() -> T {
// melib::conf::ActionFlag::InternalVal(true).into()
//}
pub(in crate::conf) fn ask>() -> T {
melib::conf::ActionFlag::Ask.into()
}
}
mod deserializers {
use serde::{de, Deserialize, Deserializer};
pub(in crate::conf) fn non_empty_opt_string<'de, D, T: std::convert::From