use clap::Clap; use ct::projects::ProjectFrame; use super::fmt::*; use super::log; use crate::error_handling::CtUnwrap; enum OpMode { Project(String), Task(String), Faulty, } #[derive(Clap, Debug)] pub struct Opts { #[clap(short, long)] /// Is this a project? project: bool, /// Whats the name of the task/project /// If none is provided, ct will attempt to stop the last started project task_name: Option, } impl Opts { fn task_name(&self) -> &Option { &self.task_name } fn is_proj(&self) -> bool { self.project } fn extract_task_name(&self) -> Option { match self.task_name() { Some(name) => Some(name.to_owned()), None => ct::projects::persistent::has_project().ct_unwrap(), } } fn op_mode(&self) -> OpMode { if let Some(name) = self.extract_task_name() { if self.is_proj() { OpMode::Project(name) } else { OpMode::Task(name) } } else { OpMode::Faulty } } } impl Opts { pub fn execute(&self) { match self.op_mode() { OpMode::Project(name) => { stop_project(name.as_str()); } OpMode::Task(_) => { bunt::writeln!( log::err(), "{$red}Error: Not implemented!{/$}\n\ Task based tracking will likely come in v0.2.0" ) .ct_unwrap(); } OpMode::Faulty => handle_faulty_args(), } } } fn handle_faulty_args() { bunt::writeln!( log::err(), "{$red}Error: Faulty arguments!{/$}\n\ Please check 'ct stop --help' for clues as to what might be wrong.\n\ {$yellow}Hint: It might be that you didn't provide a project/task name, \ which means ct will check for an already running project and stop that. \ If there's nothing running, this happens.{/$}\n\ {$green}If you think this was a mistake, specify the name of the project \ that you think is running{/$}" ) .ct_unwrap() } fn stop_project(name: &str) { if ct::projects::has(name).ct_unwrap() { // We use load_from_name instead of load_or_create_from_name to prevent this command from // creating projects // This shouldn't happen, because of the if check, but better safe than sorry let mut project = match ProjectFrame::load_from_name(name) { Err(e) => { bunt::writeln!( log::err(), "{$red}Could not load project.{/$}\nReason: {}", e ) .ct_unwrap(); return; } Ok(p) => p, }; if project.is_open() { bunt::writeln!( log::out(), "{$green}Stop tracking project {[blue]}{/$}", name ) .ct_unwrap(); // Running this on a stopped project shouldn't do anything bad // It's still accessing files if we don't have to, so we do it only once project.stop().ct_unwrap(); } else { bunt::writeln!( log::out(), "{$green}Project {[blue]} was already stopped.{/$}", name ) .ct_unwrap(); } bunt::writeln!( log::out(), "Time spent overall on {[blue]}: {[green]}", project.name(), project.duration().wrap_into() ) .ct_unwrap(); } else { bunt::writeln!( log::err(), "{$red}Error{/$}: Project {[blue]} doesn't exist", name ) .ct_unwrap(); } }