1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131
use crate::utils::{exec, pckg}; use duckscript::types::command::{Command, CommandResult}; use std::thread; use std::time::Duration; #[cfg(test)] #[path = "./mod_test.rs"] mod mod_test; enum LookingFor { Flag, MaxRetries, Interval, } #[derive(Clone)] pub(crate) struct CommandImpl { package: String, } impl Command for CommandImpl { fn name(&self) -> String { pckg::concat(&self.package, "Watchdog") } fn aliases(&self) -> Vec<String> { vec!["watchdog".to_string()] } fn help(&self) -> String { include_str!("help.md").to_string() } fn clone_and_box(&self) -> Box<dyn Command> { Box::new((*self).clone()) } fn run(&self, arguments: Vec<String>) -> CommandResult { if arguments.is_empty() { CommandResult::Error("Command not provided.".to_string()) } else { let mut max_retries: isize = -1; let mut interval: u64 = 0; let mut command_start_index = 0; let mut index = 0; let mut looking_for = LookingFor::Flag; for argument in &arguments { index = index + 1; match looking_for { LookingFor::Flag => match argument.as_str() { "--" => { command_start_index = index; break; } "--max-retries" => looking_for = LookingFor::MaxRetries, "--interval" => looking_for = LookingFor::Interval, _ => { return CommandResult::Error( format!("Unexpected argument: {} found", argument).to_string(), ); } }, LookingFor::MaxRetries => { max_retries = match argument.parse() { Ok(value) => value, Err(_) => { return CommandResult::Error( format!( "Max retries value must be positive number, found: {}", argument ) .to_string(), ); } }; looking_for = LookingFor::Flag; } LookingFor::Interval => { interval = match argument.parse() { Ok(value) => value, Err(_) => { return CommandResult::Error( format!( "Interval value must be positive number, found: {}", argument ) .to_string(), ); } }; looking_for = LookingFor::Flag; } } } if command_start_index == 0 { CommandResult::Error("Command not provided.".to_string()) } else { let millis = Duration::from_millis(interval); let mut attempt = 0; loop { attempt = attempt + 1; match exec::exec(&arguments, false, false, command_start_index) { Ok(_) => (), Err(error) => return CommandResult::Error(error), } if max_retries <= 0 || attempt > max_retries { break; } else if interval > 0 { thread::sleep(millis); } } CommandResult::Continue(Some(attempt.to_string())) } } } } pub(crate) fn create(package: &str) -> Box<dyn Command> { Box::new(CommandImpl { package: package.to_string(), }) }