Skip to content

Commit

Permalink
wip: fix printer, make thread compatible with it
Browse files Browse the repository at this point in the history
  • Loading branch information
soywod committed May 23, 2024
1 parent 6cbfc57 commit b773218
Show file tree
Hide file tree
Showing 45 changed files with 553 additions and 691 deletions.
10 changes: 0 additions & 10 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 0 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,6 @@ serde-toml-merge = "0.3"
serde_json = "1"
shellexpand-utils = "=0.2.1"
sled = "=0.34.7"
termcolor = "1"
terminal_size = "0.1"
tokio = { version = "1.23", default-features = false, features = ["macros", "rt-multi-thread"] }
toml = "0.8"
Expand Down
16 changes: 8 additions & 8 deletions src/account/command/check_up.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ impl AccountCheckUpCommand {

let account = self.account.name.as_ref().map(String::as_str);

printer.print_log("Checking configuration integrity…")?;
printer.log("Checking configuration integrity…")?;

let (toml_account_config, account_config) = config.clone().into_account_configs(
account,
Expand All @@ -33,7 +33,7 @@ impl AccountCheckUpCommand {
)?;
let used_backends = toml_account_config.get_used_backends();

printer.print_log("Checking backend context integrity…")?;
printer.log("Checking backend context integrity…")?;

let ctx_builder = backend::BackendContextBuilder::new(
toml_account_config.clone(),
Expand All @@ -46,7 +46,7 @@ impl AccountCheckUpCommand {

#[cfg(feature = "maildir")]
{
printer.print_log("Checking Maildir integrity…")?;
printer.log("Checking Maildir integrity…")?;

let maildir = ctx_builder
.maildir
Expand All @@ -61,7 +61,7 @@ impl AccountCheckUpCommand {

#[cfg(feature = "imap")]
{
printer.print_log("Checking IMAP integrity…")?;
printer.log("Checking IMAP integrity…")?;

let imap = ctx_builder
.imap
Expand All @@ -76,7 +76,7 @@ impl AccountCheckUpCommand {

#[cfg(feature = "notmuch")]
{
printer.print_log("Checking Notmuch integrity…")?;
printer.print("Checking Notmuch integrity…")?;

let notmuch = ctx_builder
.notmuch
Expand All @@ -91,7 +91,7 @@ impl AccountCheckUpCommand {

#[cfg(feature = "smtp")]
{
printer.print_log("Checking SMTP integrity…")?;
printer.log("Checking SMTP integrity…")?;

let smtp = ctx_builder
.smtp
Expand All @@ -106,7 +106,7 @@ impl AccountCheckUpCommand {

#[cfg(feature = "sendmail")]
{
printer.print_log("Checking Sendmail integrity…")?;
printer.log("Checking Sendmail integrity…")?;

let sendmail = ctx_builder
.sendmail
Expand All @@ -119,6 +119,6 @@ impl AccountCheckUpCommand {
}
}

printer.print("Checkup successfully completed!")
printer.out("Checkup successfully completed!")
}
}
2 changes: 1 addition & 1 deletion src/account/command/configure.rs
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ impl AccountConfigureCommand {
.await?;
}

printer.print(format!(
printer.out(format!(
"Account {account} successfully {}configured!",
if self.reset { "re" } else { "" }
))
Expand Down
11 changes: 8 additions & 3 deletions src/account/command/list.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,11 @@ use clap::Parser;
use color_eyre::Result;
use tracing::info;

use crate::{account::Accounts, config::TomlConfig, printer::Printer};
use crate::{
account::{Accounts, AccountsTable},
config::TomlConfig,
printer::Printer,
};

/// List all accounts.
///
Expand All @@ -23,9 +27,10 @@ impl AccountListCommand {
pub async fn execute(self, printer: &mut impl Printer, config: &TomlConfig) -> Result<()> {
info!("executing list accounts command");

let accounts: Accounts = config.accounts.iter().into();
let accounts = Accounts::from(config.accounts.iter());
let table = AccountsTable::from(accounts).with_some_width(self.table_max_width);

printer.print_table(accounts, self.table_max_width)?;
printer.out(table)?;
Ok(())
}
}
30 changes: 15 additions & 15 deletions src/account/command/sync.rs
Original file line number Diff line number Diff line change
Expand Up @@ -138,28 +138,28 @@ impl AccountSyncCommand {
let mut hunks_count = report.folder.patch.len();

if !report.folder.patch.is_empty() {
printer.print_log("Folders patch:")?;
printer.log("Folders patch:")?;
for (hunk, _) in report.folder.patch {
printer.print_log(format!(" - {hunk}"))?;
printer.log(format!(" - {hunk}"))?;
}
printer.print_log("")?;
printer.log("")?;
}

if !report.email.patch.is_empty() {
printer.print_log("Envelopes patch:")?;
printer.log("Envelopes patch:")?;
for (hunk, _) in report.email.patch {
hunks_count += 1;
printer.print_log(format!(" - {hunk}"))?;
printer.log(format!(" - {hunk}"))?;
}
printer.print_log("")?;
printer.log("")?;
}

printer.print(format!(
printer.out(format!(
"Estimated patch length for account {account_name} to be synchronized: {hunks_count}"
))?;
} else if printer.is_json() {
sync_builder.sync().await?;
printer.print(format!("Account {account_name} successfully synchronized!"))?;
printer.out(format!("Account {account_name} successfully synchronized!"))?;
} else {
let multi = MultiProgress::new();
let sub_progresses = Mutex::new(HashMap::new());
Expand Down Expand Up @@ -239,11 +239,11 @@ impl AccountSyncCommand {
.filter_map(|(hunk, err)| err.as_ref().map(|err| (hunk, err)))
.collect::<Vec<_>>();
if !folders_patch_err.is_empty() {
printer.print_log("")?;
printer.print_log("Errors occurred while applying the folders patch:")?;
printer.log("")?;
printer.log("Errors occurred while applying the folders patch:")?;
folders_patch_err
.iter()
.try_for_each(|(hunk, err)| printer.print_log(format!(" - {hunk}: {err}")))?;
.try_for_each(|(hunk, err)| printer.log(format!(" - {hunk}: {err}")))?;
}

let envelopes_patch_err = report
Expand All @@ -253,14 +253,14 @@ impl AccountSyncCommand {
.filter_map(|(hunk, err)| err.as_ref().map(|err| (hunk, err)))
.collect::<Vec<_>>();
if !envelopes_patch_err.is_empty() {
printer.print_log("")?;
printer.print_log("Errors occurred while applying the envelopes patch:")?;
printer.log("")?;
printer.log("Errors occurred while applying the envelopes patch:")?;
for (hunk, err) in envelopes_patch_err {
printer.print_log(format!(" - {hunk}: {err}"))?;
printer.log(format!(" - {hunk}: {err}"))?;
}
}

printer.print(format!("Account {account_name} successfully synchronized!"))?;
printer.out(format!("Account {account_name} successfully synchronized!"))?;
}

Ok(())
Expand Down
126 changes: 66 additions & 60 deletions src/account/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,10 @@ pub mod command;
pub mod config;
pub(crate) mod wizard;

use color_eyre::Result;
use comfy_table::{presets, Attribute, Cell, Color, ContentArrangement, Row, Table};
use serde::Serialize;
use serde::{Serialize, Serializer};
use std::{collections::hash_map::Iter, fmt, ops::Deref};

use crate::printer::{PrintTable, WriteColor};

use self::config::TomlAccountConfig;

/// Represents the printable account.
Expand All @@ -31,6 +28,16 @@ impl Account {
default,
}
}

pub fn to_row(&self) -> Row {
let mut row = Row::new();

row.add_cell(Cell::new(&self.name).fg(Color::Green));
row.add_cell(Cell::new(&self.backend).fg(Color::Blue));
row.add_cell(Cell::new(if self.default { "yes" } else { "" }).fg(Color::White));

row
}
}

impl fmt::Display for Account {
Expand All @@ -39,56 +46,14 @@ impl fmt::Display for Account {
}
}

impl From<Account> for Row {
fn from(account: Account) -> Self {
let mut r = Row::new();
r.add_cell(Cell::new(account.name).fg(Color::Green));
r.add_cell(Cell::new(account.backend).fg(Color::Blue));
r.add_cell(Cell::new(if account.default { "yes" } else { "" }).fg(Color::White));
r
}
}
impl From<&Account> for Row {
fn from(account: &Account) -> Self {
let mut r = Row::new();
r.add_cell(Cell::new(&account.name).fg(Color::Green));
r.add_cell(Cell::new(&account.backend).fg(Color::Blue));
r.add_cell(Cell::new(if account.default { "yes" } else { "" }).fg(Color::White));
r
}
}

/// Represents the list of printable accounts.
#[derive(Debug, Default, Serialize)]
pub struct Accounts(pub Vec<Account>);

impl Deref for Accounts {
type Target = Vec<Account>;
pub struct Accounts(Vec<Account>);

fn deref(&self) -> &Self::Target {
&self.0
}
}

impl From<Accounts> for Table {
fn from(accounts: Accounts) -> Self {
impl Accounts {
pub fn to_table(&self) -> Table {
let mut table = Table::new();
table
.load_preset(presets::NOTHING)
.set_content_arrangement(ContentArrangement::Dynamic)
.set_header(Row::from([
Cell::new("NAME").add_attribute(Attribute::Reverse),
Cell::new("BACKENDS").add_attribute(Attribute::Reverse),
Cell::new("DEFAULT").add_attribute(Attribute::Reverse),
]))
.add_rows(accounts.0.into_iter().map(Row::from));
table
}
}

impl From<&Accounts> for Table {
fn from(accounts: &Accounts) -> Self {
let mut table = Table::new();
table
.load_preset(presets::NOTHING)
.set_content_arrangement(ContentArrangement::Dynamic)
Expand All @@ -97,21 +62,17 @@ impl From<&Accounts> for Table {
Cell::new("BACKENDS").add_attribute(Attribute::Reverse),
Cell::new("DEFAULT").add_attribute(Attribute::Reverse),
]))
.add_rows(accounts.0.iter().map(Row::from));
.add_rows(self.iter().map(Account::to_row));

table
}
}

impl PrintTable for Accounts {
fn print_table(&self, writer: &mut dyn WriteColor, table_max_width: Option<u16>) -> Result<()> {
let mut table = Table::from(self);
if let Some(width) = table_max_width {
table.set_width(width);
}
writeln!(writer)?;
write!(writer, "{}", table)?;
writeln!(writer)?;
Ok(())
impl Deref for Accounts {
type Target = Vec<Account>;

fn deref(&self) -> &Self::Target {
&self.0
}
}

Expand Down Expand Up @@ -169,3 +130,48 @@ impl From<Iter<'_, String, TomlAccountConfig>> for Accounts {
Self(accounts)
}
}

pub struct AccountsTable {
accounts: Accounts,
width: Option<u16>,
}

impl AccountsTable {
pub fn with_some_width(mut self, width: Option<u16>) -> Self {
self.width = width;
self
}
}

impl From<Accounts> for AccountsTable {
fn from(accounts: Accounts) -> Self {
Self {
accounts,
width: None,
}
}
}

impl fmt::Display for AccountsTable {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut table = self.accounts.to_table();

if let Some(width) = self.width {
table.set_width(width);
}

writeln!(f)?;
write!(f, "{table}")?;
writeln!(f)?;
Ok(())
}
}

impl Serialize for AccountsTable {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
self.accounts.serialize(serializer)
}
}
2 changes: 1 addition & 1 deletion src/backend/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -701,7 +701,7 @@ impl Backend {
let id_mapper = self.build_id_mapper(folder, backend_kind)?;
let envelopes = self.backend.list_envelopes(folder, opts).await?;
let envelopes =
Envelopes::from_backend(&self.backend.account_config, &id_mapper, envelopes)?;
Envelopes::try_from_backend(&self.backend.account_config, &id_mapper, envelopes)?;
Ok(envelopes)
}

Expand Down
Loading

0 comments on commit b773218

Please sign in to comment.