|
| 1 | +use libycresources::dat; |
| 2 | + |
| 3 | +use std::io::{Read, Seek}; |
| 4 | +use std::path::PathBuf; |
| 5 | + |
| 6 | +#[derive(Debug)] |
| 7 | +pub(crate) enum Error { |
| 8 | + Path, |
| 9 | + Buffer, |
| 10 | + Decompress, |
| 11 | + Read(std::io::Error), |
| 12 | + Write(std::io::Error), |
| 13 | +} |
| 14 | + |
| 15 | +pub(crate) fn tree<R>(reader: &mut R, tree: &dat::Directory, output: &String) -> Result<(), Error> |
| 16 | +where |
| 17 | + R: Read + Seek, |
| 18 | +{ |
| 19 | + let mut path = PathBuf::new(); |
| 20 | + |
| 21 | + for (depth, _, directory) in tree.iter() { |
| 22 | + if depth > path.components().count() { |
| 23 | + path.push(String::from(&directory.name)); |
| 24 | + } else { |
| 25 | + for _ in 0..path.components().count() - depth { |
| 26 | + path.pop(); |
| 27 | + } |
| 28 | + |
| 29 | + if !path.ends_with(String::from(&directory.name)) { |
| 30 | + path.push(String::from(&directory.name)); |
| 31 | + } |
| 32 | + } |
| 33 | + |
| 34 | + for file in &directory.files { |
| 35 | + let root = std::path::Path::new(&output); |
| 36 | + let full = root.join(&path).join(&file.name); |
| 37 | + let path = full.as_path(); |
| 38 | + |
| 39 | + println!("{:}", path.display()); |
| 40 | + |
| 41 | + let directory = match path.parent() { |
| 42 | + None => return Err(Error::Path), |
| 43 | + Some(directory) => directory, |
| 44 | + }; |
| 45 | + |
| 46 | + if let Err(error) = std::fs::create_dir_all(&directory) { |
| 47 | + return Err(Error::Write(error)); |
| 48 | + } |
| 49 | + |
| 50 | + let mut created = match std::fs::File::create(&path) { |
| 51 | + Err(error) => return Err(Error::Write(error)), |
| 52 | + Ok(created) => created, |
| 53 | + }; |
| 54 | + |
| 55 | + let mut writer = std::io::BufWriter::with_capacity(1 * 1024 * 1024, &mut created); |
| 56 | + |
| 57 | + if let Err(error) = dat::extract::file(reader, &file, &mut writer) { |
| 58 | + return match error { |
| 59 | + dat::extract::Error::Source => Err(Error::Buffer), |
| 60 | + dat::extract::Error::Decompress => Err(Error::Decompress), |
| 61 | + dat::extract::Error::Read(error) => Err(Error::Read(error)), |
| 62 | + dat::extract::Error::Write(error) => Err(Error::Write(error)), |
| 63 | + }; |
| 64 | + } |
| 65 | + } |
| 66 | + } |
| 67 | + |
| 68 | + Ok(()) |
| 69 | +} |
0 commit comments