floem_css_parser/
read.rs

1/// Default read buffer size
2const DEFAULT_BUF_SIZE: usize = 16 * 1024;
3
4/// If path points to singe file, returns file content as `String`
5///
6/// If path points to directory, reads all `.css` files and combines them to single `String`
7///
8/// # Errors
9/// Returns `std::io::Error` if path is not readable
10pub fn read_styles(path: &std::path::Path) -> Result<String, std::io::Error> {
11    if path.is_dir() {
12        let combined = std::fs::read_dir(path)?
13            .filter_map(Result::ok)
14            .filter_map(|e| {
15                e.path()
16                    .extension()
17                    .is_some_and(|e| e.eq_ignore_ascii_case("css"))
18                    .then_some(e.path())
19            })
20            .filter_map(|path| match std::fs::read_to_string(&path) {
21                Err(e) => {
22                    log::warn!("Failed to read file {path:?}\n{e}");
23                    None
24                }
25                Ok(v) => Some(v),
26            })
27            .fold(String::with_capacity(DEFAULT_BUF_SIZE), |mut s, c| {
28                s.push_str(&c);
29                s
30            });
31
32        Ok(combined)
33    } else {
34        Ok(std::fs::read_to_string(path)?)
35    }
36}