rmjs/
lib.rs

1use std::{fs, path::PathBuf, time::Instant};
2
3use glob::glob;
4
5pub fn find_and_remove(directory: &str, debug: bool) {
6    let start = Instant::now();
7    println!("Searching files in {directory}...");
8    let all_js_files: Vec<PathBuf> = glob(&format!("{directory}/**/*.js"))
9        .expect("whoops")
10        .filter_map(|f| {
11            if let Ok(f) = f {
12                (!f.is_symlink()).then(|| f)
13            } else {
14                None
15            }
16        })
17        .collect();
18
19    let total_js_files = all_js_files.len();
20    if total_js_files == 0 {
21        println!("Couldn't find any JS files!");
22        return;
23    } else {
24        println!("Found {total_js_files} total JavaScript files.");
25    };
26
27    let mut rmjs_change_counter: usize = 0;
28    let mut removed_change_counter: usize = 0;
29
30    all_js_files.into_iter().for_each(|js_file| {
31        let ts_file = {
32            let mut file = js_file.clone();
33            file.set_extension("ts");
34            file
35        };
36        if ts_file.is_file() {
37            rmjs_change_counter += 1;
38            match fs::remove_file(&js_file) {
39                Ok(_) => {
40                    removed_change_counter += 1;
41                }
42                Err(e) => {
43                    if debug {
44                        println!("Unable to delete {js_file:?}! Error: {e}");
45                    }
46                }
47            }
48        }
49    });
50    let duration = start.elapsed();
51    let duration_message = if duration.as_secs() > 5 {
52        let duration = duration.as_secs();
53        format!("{duration} seconds")
54    } else {
55        let duration = duration.as_millis();
56        format!("{duration} milliseconds")
57    };
58    if rmjs_change_counter == 0 {
59        println!("Couldn't find any eligible .js files to remove!");
60    } else if rmjs_change_counter != removed_change_counter {
61        println!("Removed {removed_change_counter} .js files out of {rmjs_change_counter} detected eligible files in {duration_message}.");
62        if !debug {
63            println!("Rerun with the --debug option enabled for more detailed information.");
64        }
65    } else {
66        println!("Removed all {removed_change_counter} eligible .js files in {duration_message}.");
67    }
68}