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
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
#![deny(clippy::pedantic)]
// #![warn(missing_docs)]

use set_error::ChangeError;

use std::{
    path::Path,
    rc::Rc,
    thread,
    time::{Duration, SystemTime},
};

#[derive(Clone)]
pub struct FileListBuilder<T: Clone> {
    files: Vec<WatchedFile<T>>,
    interval: Duration,
    max_retries: Option<u32>,
    open_file_func: Rc<Fn(&str) -> WatchingFuncResult<T>>,
    run_only_once: bool,
}

#[derive(Clone)]
pub struct WatchedFile<T> {
    path: String,
    date_modified: SystemTime,
    functions_on_run: Vec<Rc<Fn(T) -> WatchingFuncResult<T>>>,
    function_on_end: Rc<Fn(T) -> Result<(), String>>,
}

pub enum WatchingFuncResult<T> {
    Success(T),
    Retry(String),
    Fail(String),
}
use WatchingFuncResult::{Fail, Retry, Success};

impl<T: Clone> FileListBuilder<T> {
    pub fn new<F: 'static + Fn(&str) -> WatchingFuncResult<T>>(open_func: F) -> Self {
        Self {
            files: Vec::new(),
            interval: Duration::from_millis(1000),
            max_retries: None,
            open_file_func: Rc::new(open_func),
            run_only_once: false,
        }
    }
    pub fn run_only_once(mut self, q: bool) -> Self {
        self.run_only_once = q;
        self
    }
    pub fn add_file(&mut self, file: WatchedFile<T>) {
        self.files.push(file);
    }
    pub fn with_interval(mut self, inter: Duration) -> Self {
        self.interval = inter;
        self
    }
    pub fn with_max_retries(mut self, re: u32) -> Self {
        self.max_retries = Some(re);
        self
    }
    pub fn launch(mut self) -> Result<(), String> {
        let mut on_first_run = self.files.len() + 1;
        loop {
            for mut file in &mut self.files {
                if on_first_run != 0 {
                    on_first_run -= 1
                }
                if (on_first_run != 0) || (file.date_modified != date_modified(&file.path)?) {
                    file.date_modified = date_modified(&file.path)?;
                    let open_file_func_as_not_mut = self.open_file_func.clone();
                    let mut file_data = keep_doing_until(self.max_retries, self.interval, || {
                        (open_file_func_as_not_mut)(&file.path)
                    })?;
                    for function_to_run in file.functions_on_run.clone() {
                        file_data = keep_doing_until(self.max_retries, self.interval, || {
                            function_to_run(file_data.clone())
                        })?
                    }
                    let mut retries = self.max_retries;
                    loop {
                        match (file.function_on_end)(file_data.clone()) {
                            Ok(_) => break,
                            Err(s) => {
                                retries = retries.map(|x| x - 1);
                                match retries {
                                    Some(n) if n == 0 => {
                                        return Err(String::from("no more retries"))
                                    }
                                    _ => {
                                        println!("{}", s);
                                        thread::sleep(self.interval);
                                        continue;
                                    }
                                }
                            }
                        }
                    }
                    thread::sleep(self.interval);
                }
            }
            if self.run_only_once {
                return Ok(());
            }
        }
    }
}

fn keep_doing_until<F, T>(mut retries: Option<u32>, interval: Duration, f: F) -> Result<T, String>
where
    F: Fn() -> WatchingFuncResult<T>,
{
    Ok(loop {
        match f() {
            Success(t) => break t,
            Fail(s) => return Err(s),
            Retry(s) => {
                retries = retries.map(|x| x - 1);
                match retries {
                    Some(n) if n == 0 => return Err(String::from("no more retries")),
                    _ => {
                        println!("{}", s);
                        thread::sleep(interval);
                        continue;
                    }
                }
            }
        }
    })
}

impl<T> WatchedFile<T> {
    pub fn new<G: 'static + Fn(T) -> Result<(), String>>(
        path: &str,
        end_func: G,
    ) -> Result<Self, String> {
        Ok(Self {
            path: path.to_string(),
            date_modified: date_modified(&path)?,
            functions_on_run: Vec::new(),
            function_on_end: Rc::new(end_func),
        })
    }
    pub fn add_func<F: 'static + Fn(T) -> WatchingFuncResult<T>>(&mut self, func: F) {
        self.functions_on_run.push(Rc::new(func));
    }
}

fn date_modified(path: &str) -> Result<SystemTime, String> {
    Ok(Path::new(path)
        .metadata()
        .set_error(&format!("failed to open file {} metadata", path))?
        .modified()
        .set_error(&format!("failed to find files date modified {}", path))?)
}