From ab9baf17f110622391d143122195e2b82acc7d10 Mon Sep 17 00:00:00 2001 From: rabite Date: Tue, 22 Jan 2019 21:05:06 +0100 Subject: basic browsing working --- src/files.rs | 42 ++++++++++++++++++++++++++++-------------- 1 file changed, 28 insertions(+), 14 deletions(-) (limited to 'src/files.rs') diff --git a/src/files.rs b/src/files.rs index 2d83bd9..dd86304 100644 --- a/src/files.rs +++ b/src/files.rs @@ -1,4 +1,7 @@ use std::ops::Index; +use std::error::Error; +use std::path::PathBuf; +use std::ffi::OsStr; pub struct Files(Vec); @@ -10,6 +13,22 @@ impl Index for Files { } impl Files { + pub fn new_from_path + Sized>(path: S) + -> Result> + where S: std::convert::AsRef { + let mut files = Vec::new(); + for file in std::fs::read_dir(path)? { + let file = file?; + let name = file.file_name(); + let name = name.to_string_lossy(); + let path = file.path(); + let size = file.metadata()?.len() / 1024; + files.push(File::new(&name, path, size as usize)); + } + Ok(Files(files)) + } + + pub fn iter(&self) -> std::slice::Iter { self.0.iter() } @@ -22,7 +41,7 @@ impl Files { #[derive(Debug)] pub struct File { pub name: String, - pub path: String, + pub path: PathBuf, pub size: Option, // owner: Option, // group: Option, @@ -33,10 +52,10 @@ pub struct File { impl File { - pub fn new(name: &str, path: &str, size: usize) -> File { + pub fn new(name: &str, path: PathBuf, size: usize) -> File { File { name: name.to_string(), - path: path.to_string(), + path: path, size: Some(size), // owner: None, // group: None, @@ -62,18 +81,13 @@ impl File { }.to_string(); (size, unit) } -} -pub fn get_files(dir: &str) -> Result { - let mut files = Vec::new(); - for file in std::fs::read_dir(dir)? { - let name = file.as_ref().unwrap().file_name().into_string().unwrap(); - file.as_ref().unwrap().path().pop(); - let path = file.as_ref().unwrap().path().into_os_string().into_string().unwrap(); - let size = file.unwrap().metadata()?.len() / 1024; - files.push(File::new(&name, &path, size as usize)); + pub fn grand_parent(&self) -> Option { + Some(self.path.parent()?.parent()?.to_path_buf()) } - Ok(Files(files)) -} + pub fn path(&self) -> PathBuf { + self.path.clone() + } +} -- cgit v1.2.3