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
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
use colorful::{Color, Colorful};
use ex::fs;
use libcli::args::*;
use std::{path::Path, thread, time};
use time::{Duration, SystemTime};
#[macro_use]
mod macros;

mod subprocess;
use subprocess::Subprocess;

pub fn run(config: Config) {
    let watching_default = [String::from(".")];
    let watching = match config.option("(unnamed)") {
        None => &watching_default,
        // Empty list
        Some(v) if v.len() == 0 => &watching_default,
        Some(v) => v,
    };
    let interval = config.option("interval").unwrap_or(&["100".to_owned()])[0]
        .parse::<u64>()
        .unwrap_or_else(|e| error!("Invalid interval {}", e));
    let clear = config.option("clear").is_some();
    let kill = config.option("kill").is_some();
    let command = config.option("").unwrap();

    let mut subprocess: Option<Subprocess> = None;

    if config.option("wait").is_none() {
        let command = subst_args(command, &[]);
        subprocess = start_process(&command, clear);
    }

    let needs_subst = command.iter().find(|s| s.contains("{}")).is_some();

    let mut last_check = SystemTime::now();
    loop {
        // Check if subprocess has exited
        if let Some(child) = subprocess.as_mut() {
            if !child.is_running() {
                let code = child.wait();
                print_exit_code(code);
                subprocess = None;
            }
        }
        // Check if any files have changed
        // Run the find_all_modified version to get a list of all changed files
        if needs_subst {
            let changed = watching
                .iter()
                .flat_map(|entry| find_all_modified(entry, last_check).into_iter())
                .collect::<Vec<String>>();
            if changed.len() != 0 {
                let command = subst_args(command, &changed);
                if let Some(child) = subprocess.as_mut() {
                    kill_or_wait_process(child, kill);
                }
                subprocess = start_process(&command, clear);
            }
        }
        // Only run find_modified to see if atleast on thing changed
        else if watching
            .iter()
            .find(|entry| find_modified(entry, last_check))
            .is_some()
        {
            // Run command
            // Wait or kill previous subprocess if already running
            if let Some(child) = subprocess.as_mut() {
                kill_or_wait_process(child, kill);
            }
            subprocess = start_process(command, clear);
        }
        last_check = SystemTime::now();
        thread::sleep(Duration::from_millis(interval));
    }
}

/// Either kills or waits for process depending on config
fn kill_or_wait_process(process: &mut Subprocess, kill: bool) {
    let code = match kill {
        true => process.wait_kill(),
        false => process.wait(),
    };
    print_exit_code(code);
}

fn start_process(command: &[String], clear: bool) -> Option<Subprocess> {
    if clear {
        print!("\x1B[2J\x1B[1;1H\n");
    }

    let command_str = command.join(" ");
    let command_str = match command_str.len() > 50 {
        true => command_str[0..50].to_owned() + "...",
        false => command_str,
    };

    println!("{} {}", "Running".color(Color::Green).bold(), command_str);
    Subprocess::new(command)
}

fn print_exit_code(code: Option<i32>) {
    match code {
        Some(code) => println!(
            "{} with code {}",
            "Finished".color(Color::Blue).bold(),
            match code {
                0 => code.to_string().color(Color::Green),
                _ => code.to_string().color(Color::Red),
            }
        ),
        None => println!("{} process", "Killed".color(Color::Magenta).bold()),
    }
}

/// Substitute each argument of "{}" with all subst
fn subst_args(command: &[String], subst: &[String]) -> Vec<String> {
    let mut result = Vec::with_capacity(command.len());
    for arg in command {
        if arg == "{}" {
            result.append(&mut subst.to_vec());
        } else {
            result.push(arg.to_owned());
        }
    }
    result
}

// Check if any files have changes since last timepoint
// Returns true as soon as if sees a file changed after `last_time`
fn find_modified<P: AsRef<Path> + std::fmt::Debug>(path: P, last_time: SystemTime) -> bool {
    let metadata = match fs::metadata(&path) {
        Ok(v) => v,
        Err(e) => error!("Error: {}", e),
    };

    if get_modified(&metadata, last_time) {
        return true;
    }

    if metadata.is_file() {
        return false;
    }

    let entries = match fs::read_dir(path) {
        Ok(v) => v,
        Err(e) => {
            error!("Error: {}", e);
        }
    };

    // Iterate everything
    for entry in entries {
        let entry = match entry {
            Ok(v) => v,
            Err(e) => error!("Error: {}", e),
        };

        let metadata = match entry.metadata() {
            Ok(v) => v,
            Err(e) => error!("Error: {}", e),
        };

        if get_modified(&metadata, last_time) {
            return true;
        }

        if metadata.is_dir() && find_modified(entry.path(), last_time) {
            return true;
        }
    }

    false
}

fn get_modified(metadata: &fs::Metadata, last_time: SystemTime) -> bool {
    let modified_time = match metadata.modified() {
        Ok(v) => v,
        Err(e) => error!("Error: {}", e),
    };

    last_time < modified_time
}

// Check if any files have changes since last timepoint
// Returns true as soon as if sees a file changed after `last_time`
fn find_all_modified(path: &str, last_time: SystemTime) -> Vec<String> {
    let metadata = match fs::metadata(&path) {
        Ok(v) => v,
        Err(e) => error!("Error: {}", e),
    };

    let mut changed = Vec::new();

    if get_modified(&metadata, last_time) {
        changed.push(path.to_owned());
    }

    if metadata.is_file() {
        return changed;
    }

    let entries = match fs::read_dir(path) {
        Ok(v) => v,
        Err(e) => {
            error!("Error: {}", e);
        }
    };

    // Iterate everything
    for entry in entries {
        let entry = match entry {
            Ok(v) => v,
            Err(e) => error!("Error: {}", e),
        };

        let metadata = match entry.metadata() {
            Ok(v) => v,
            Err(e) => error!("Error: {}", e),
        };

        let modified_time = match metadata.modified() {
            Ok(v) => v,
            Err(e) => error!("Error: {}", e),
        };

        if last_time < modified_time {
            changed.push(entry.path().to_string_lossy().into_owned())
        }

        if metadata.is_dir() {
            changed.append(&mut find_all_modified(
                &entry.path().to_string_lossy(),
                last_time,
            ));
        }
    }

    changed
}