Skip to main content

huff_neo_utils/file/
unpack_files.rs

1use std::{ffi::OsStr, path::Path};
2
3/// Returns a file extension from a path as a string.
4pub fn parse_extension(filename: &str) -> Option<&str> {
5    Path::new(filename).extension().and_then(OsStr::to_str)
6}
7
8/// Unpacking errors
9#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone)]
10pub enum UnpackError {
11    /// The file extension is not supported.
12    UnsupportedExtension(String),
13    /// Failed to read directory
14    InvalidDirectory(String),
15    /// Missing File
16    MissingFile(String),
17}
18
19/// Unpacks huff files into a vec of strings.
20pub fn unpack_files(path: &str) -> Result<Vec<String>, UnpackError> {
21    // If the path is a file, return a vec of the file
22    match parse_extension(path) {
23        Some(extension) => {
24            if extension == "huff" {
25                return Ok(vec![path.to_string()]);
26            }
27            Err(UnpackError::UnsupportedExtension(path.to_string()))
28        }
29        None => {
30            // We have a directory, try to extract huff files and parse
31            match std::fs::read_dir(path) {
32                Ok(files) => {
33                    let input_files: Vec<String> = files.map(|x| x.unwrap().path().to_str().unwrap().to_string()).collect();
34                    let filtered: Vec<String> =
35                        input_files.iter().filter(|&f| Path::new(&f).extension().unwrap_or_default().eq("huff")).cloned().collect();
36                    Ok(filtered)
37                }
38                Err(e) => {
39                    tracing::error!(target: "io", "ERROR READING DIRECTORY {}: {:?}", path, e);
40                    Err(UnpackError::InvalidDirectory(path.to_string()))
41                }
42            }
43        }
44    }
45}