notmuch-tagrewriter 0.1.0

Retag notmuch mails
Documentation
use std::path::PathBuf;

use itertools::Itertools;
use log::error;
use nm_tagrewriter::{config::Config, graph::GraphWithData};

use clap::{Parser, Subcommand};

#[derive(Parser)]
struct Cli {
    /// Set config file
    #[arg(short, long, value_name = "FILE")]
    config: Option<PathBuf>,

    #[command(subcommand)]
    command: Option<Commands>,
}
impl Cli {
    fn execute(self) {
        let config = Config::read(self.config).unwrap();
        if let Some(command) = self.command {
            command.execute(config);
        } else {
            println!("No command specified, doing nothing. See --help for available commands.");
        }
    }
}

#[derive(Subcommand)]
enum Commands {
    /// Print a graphviz dot representation of the rewriting rules.
    Graph,

    /// Find cycles in the set of rules
    Cycles,

    /// Rewrite tags.
    Tag {
        #[arg(short, long)]
        dry_run: bool,
    },
}

impl Commands {
    fn execute(self, config: Config) {
        let graph =
            GraphWithData::from_arrow_list(config.get_rules().clone().try_into().expect("error"));
        match self {
            Commands::Tag { dry_run } => {
                if graph.has_cycles() {
                    println!("The rewriting rules induce a cycle. Aborting.")
                } else {
                    if let Err(e) = config.execute(dry_run) {
                        error!("Error: {:?}", e)
                    }
                }
            }
            Commands::Cycles => {
                let cycles = graph.find_cycles();
                if cycles.iter().len() == 0 {
                    println!("No cycle.")
                } else {
                    println!("{}", cycles.iter().map(|x| x.as_string()).join("\n---\n"))
                }
            }
            Commands::Graph => {
                let dotviz = graph.dot();
                println!("{}", dotviz);
            }
        }
    }
}

fn main() {
    colog::init();
    let cli = Cli::parse();
    cli.execute();
}