pub mod count;
pub mod file;
use crate::{tree::summary::NodeSummary, utils::check_path};
use std::fmt::Display;
#[derive(Debug, Clone)]
pub struct TreeNode {
pub path: String,
pub is_dir: bool,
pub children: Option<Vec<TreeNode>>,
pub summary: NodeSummary,
}
impl Display for TreeNode {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"\n----- TreeNode -----\n\n- path: {}\n- is_dir: {}\n- children: {}\n- summary: {}\n\n--------------------",
self.path,
self.is_dir,
self.children.as_ref().unwrap_or(&Vec::new()).len(),
self.summary
)
}
}
impl TreeNode {
pub fn new<P>(path: P, is_dir: bool) -> Self
where
P: Into<String>,
{
TreeNode {
is_dir,
path: path.into(),
children: if is_dir { Some(Vec::new()) } else { None },
summary: NodeSummary::new(),
}
}
pub fn is_valid(&self) -> bool {
check_path(&self.path).is_ok()
}
}
impl TreeNode {
pub fn upsert_summary(&mut self) {
let summary = NodeSummary::update(self);
self.summary = summary;
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_display() {
let node = TreeNode::new("./tests/examples/tree/summary".to_string(), true);
println!("{}", node);
}
#[test]
fn test_new() {
let node = TreeNode::new("./tests/examples/tree/summary".to_string(), true);
assert_eq!(node.path, "./tests/examples/tree/summary");
assert_eq!(node.is_dir, true);
assert!(node.children.is_some());
assert_eq!(node.summary.size, 0);
assert_eq!(node.summary.count, 0);
}
#[test]
fn test_summary_update() {
let mut node = TreeNode::new("./tests/examples/tree/summary", true);
node.upsert_summary();
println!("{}", node);
}
}