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
use std::{
    collections::BTreeSet,
    env::current_exe,
    fs::{read, write},
    path::{Path, PathBuf},
};

use async_walkdir::{DirEntry, WalkDir};
use futures::StreamExt;
use log::LevelFilter;

use find_target::find_directory_or_create;

use crate::{
    utils::{hash_file, logger, optimize_png},
    TinyResult,
};

mod config;

pub struct TinyConfig {
    pub writable: bool,
    pub database: bool,
    pub log_level: LevelFilter,
}

pub struct TinyWorkspace {
    workspace: PathBuf,
    writable: bool,
    database: PathBuf,
    files: BTreeSet<u64>,
}

impl TinyWorkspace {
    pub async fn check_all_pngs(&mut self) -> TinyResult {
        let mut entries = WalkDir::new(&self.workspace);
        loop {
            let path = match entries.next().await {
                Some(out) => match continue_search(out) {
                    Some(path) => path,
                    None => continue,
                },
                None => break,
            };
            if let Err(e) = self.optimize_png(&path) {
                log::error!("{e}")
            }
        }
        Ok(())
    }
    pub fn optimize_png(&mut self, path: &Path) -> TinyResult {
        let bytes = read(path)?;
        let hash = hash_file(&bytes);
        if self.files.contains(&hash) {
            log::info!("Skip Optimized \n{}", path.display());
            return Ok(());
        }
        let hash = match optimize_png(&bytes) {
            Ok(o) => {
                log::info!("{} => {} ({:+.2}%)\n{}", o.before, o.after, o.reduce, path.display());
                hash_file(&o.output)
            }
            Err(_) => hash_file(&bytes),
        };

        if self.writable {
            write(path, bytes)?;
            self.files.insert(hash);
        }
        Ok(())
    }
}

fn continue_search(r: Result<DirEntry, std::io::Error>) -> Option<PathBuf> {
    let path = match r {
        Ok(o) => o.path(),
        Err(e) => {
            log::error!("{e}");
            return None;
        }
    };
    if !path.is_file() {
        return None;
    }
    let name = path.file_name()?.to_str()?;
    if name.ends_with(".png") { Some(path) } else { None }
}