spx_codegen/
ext.rs

1/*
2 * Created on Wed Jul 12 2023
3 *
4 * Copyright (c) storycraft. Licensed under the Apache Licence 2.0.
5 */
6
7use std::{
8    fs::File,
9    io::{self, BufReader, Read, Seek, Write},
10    path::Path,
11};
12
13use easy_ext::ext;
14use path_slash::PathExt;
15use walkdir::WalkDir;
16
17use crate::SpxBuilder;
18
19#[ext(StreamExt)]
20pub impl<W: Write + Seek> SpxBuilder<W> {
21    /// Write a file entry from [`Read`] stream
22    fn write_stream(&mut self, name: String, mut stream: impl Read) -> io::Result<u64> {
23        io::copy(&mut stream, &mut self.start_file(name)?)
24    }
25}
26
27#[ext(FileExt)]
28pub impl<W: Write + Seek> SpxBuilder<W> {
29
30    /// Write every disk files from base directory
31    fn write_dir(&mut self, base: impl AsRef<Path>) -> io::Result<u64> {
32        let mut count = 0;
33
34        for entry in WalkDir::new(&base) {
35            let entry = entry?;
36            if entry.file_type().is_dir() {
37                continue;
38            }
39
40            let path = entry.path();
41            let striped_path = entry.path().strip_prefix(&base).unwrap();
42
43            self.write_stream(
44                striped_path.to_slash_lossy().to_string(),
45                BufReader::new(File::open(path)?),
46            )?;
47            count += 1;
48        }
49
50        Ok(count)
51    }
52}