Add trait for tree object

This commit is contained in:
Michael Mikovsky
2025-12-17 17:43:08 -07:00
parent 2dc736b02e
commit 0dcd841cc5
4 changed files with 69 additions and 80 deletions
+31 -66
View File
@@ -10,89 +10,54 @@ use unshell_lib::debug;
use crate::{Server, api::CurrentUser};
#[derive(Clone)]
enum Tree2Branch {
File(String),
Folder(String, HashMap<String, Tree2Branch>),
}
pub trait Tree {
fn is_folder() -> bool {
false
}
#[derive(Clone, Serialize, Deserialize)]
enum Tree2Repr {
File(String),
Folder(Vec<String>),
}
fn get_children_string(&self) -> Vec<String> {
Vec::new()
}
#[derive(Clone)]
pub struct Tree2 {
root: Tree2Branch,
}
fn select_child(&self, child: &str) -> Result<Tree2Repr, String>;
impl Tree2Branch {
pub fn get_path(&self, elements: &Vec<&str>, depth: usize) -> Result<&Tree2Branch, String> {
if depth == elements.len() {
return Ok(self);
}
fn get_value(&self) -> String {
"DEFAULT".into()
}
let element = elements[depth];
if let Tree2Branch::Folder(_, hash_map) = self {
if let Some(branch) = hash_map.get(element) {
branch.get_path(elements, depth + 1)
fn get_path(&self, elements: &mut Vec<&str>) -> Result<Tree2Repr, String> {
if elements.is_empty() {
return if Self::is_folder() {
Ok(Tree2Repr::Folder(self.get_children_string()))
} else {
Err("Invalid Path".into())
}
Ok(Tree2Repr::File(self.get_value()))
};
}
let child = elements.remove(0);
if Self::is_folder() {
self.select_child(child)
} else {
return Err("This is a folder, not a file".into());
Err("This is a folder, not a file".into())
}
}
pub fn to_repr(&self) -> Tree2Repr {
match self {
Tree2Branch::File(name) => Tree2Repr::File(name.clone()),
Tree2Branch::Folder(_, hash_map) => {
Tree2Repr::Folder(hash_map.keys().cloned().collect::<Vec<String>>())
}
}
}
}
impl Tree2 {
fn get(&self, path: &str) -> Result<Tree2Repr, String> {
let elements = if path.is_empty() {
let mut path = if path.is_empty() {
Vec::new()
} else {
path.split("/").collect::<Vec<&str>>()
};
// let elements = path.split("/").collect::<Vec<&str>>();
let branch = self.root.get_path(&elements, 0)?;
Ok(branch.to_repr())
self.get_path(&mut path)
}
}
impl Default for Tree2 {
fn default() -> Self {
Self {
root: Tree2Branch::Folder(
"ROOT".into(),
HashMap::from([
("File A".into(), Tree2Branch::File("A".into())),
("File B".into(), Tree2Branch::File("B".into())),
(
"Folder C".into(),
Tree2Branch::Folder(
"A".into(),
HashMap::from([
("File A".into(), Tree2Branch::File("A".into())),
("File B".into(), Tree2Branch::File("B".into())),
]),
),
),
]),
),
}
}
#[derive(Clone, Serialize, Deserialize)]
pub enum Tree2Repr {
File(String),
Folder(Vec<String>),
}
impl Server {
@@ -104,7 +69,7 @@ impl Server {
debug!("GET /api/interface/{}", path);
let result = (|| -> Result<_, String> {
let interface = server.tree.get(&path)?;
let interface = server.get(&path)?;
Ok(interface)
})();