From 78a3d8f52076fe66ac95bcfc8acec082cb3f68cd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Moritz=20H=C3=B6lting?= <87192362+moritz-hoelting@users.noreply.github.com> Date: Thu, 21 Mar 2024 19:50:00 +0100 Subject: [PATCH] Add TryFrom implementation for VFolder --- src/virtual_fs.rs | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/src/virtual_fs.rs b/src/virtual_fs.rs index acce10d..f4d4f9a 100644 --- a/src/virtual_fs.rs +++ b/src/virtual_fs.rs @@ -187,6 +187,41 @@ impl VFolder { } } +impl TryFrom<&Path> for VFolder { + type Error = io::Error; + + fn try_from(value: &Path) -> Result { + let mut root_vfolder = VFolder::new(); + let root_folder = fs::read_dir(value)?; + for dir_entry in root_folder { + let dir_entry = dir_entry?; + let path = dir_entry.path(); + let name = dir_entry + .file_name() + .into_string() + .map(Some) + .unwrap_or_default(); + if let Some(name) = name { + if path.is_dir() { + root_vfolder.add_existing_folder(&name, VFolder::try_from(path.as_path())?); + } else if path.is_file() { + let data = fs::read(path)?; + root_vfolder.add_file(&name, VFile::Binary(data)); + } else { + unreachable!("Path is neither file nor directory"); + } + } else { + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + "Invalid file name", + )); + } + } + + Ok(root_vfolder) + } +} + /// File representation in virtual file system #[derive(Debug, Clone)] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]