use crate::list::list_folder_contents;
use crate::path::get_last_path_component;
use std::path::Path;
fn helper<W: std::io::Write>(path: &Path, prefix: String, is_last: bool, output: &mut W) {
let name = get_last_path_component(path);
let connector = if is_last { "└── " } else { "├── " };
writeln!(output, "{prefix}{connector}{name}").unwrap();
if path.is_dir() {
let new_prefix = format!("{}{}", prefix, if is_last { " " } else { "│ " });
let entries = list_folder_contents(path);
for (i, entry) in entries.iter().enumerate() {
let is_last = i == entries.len() - 1;
helper(entry, new_prefix.clone(), is_last, output);
}
}
}
fn write_folder_tree<P: AsRef<Path>, W: std::io::Write>(path: P, output: &mut W) {
let path = path.as_ref();
writeln!(output, "{}", path.display()).unwrap();
let entries = list_folder_contents(path);
for (i, entry) in entries.iter().enumerate() {
let is_last = i == entries.len() - 1;
helper(entry, "".to_string(), is_last, output);
}
}
pub fn print_folder_tree<P: AsRef<Path>>(path: P) {
write_folder_tree(path, &mut std::io::stdout());
}
#[cfg(test)]
mod tests {
use super::*;
use crate::save_string_to_file;
use crate::test_utils::get_temp_dir_path;
use tempfile::tempdir;
#[test]
fn test_write_folder_tree() {
let temp_dir = tempdir().unwrap();
let temp_dir_path = get_temp_dir_path(&temp_dir);
save_string_to_file("Content 1", temp_dir_path.join("file1.txt"));
save_string_to_file("Content 2", temp_dir_path.join("file2.txt"));
save_string_to_file("Content 3", temp_dir_path.join("subfolder/file3.txt"));
let mut stdout: Vec<u8> = Vec::new();
write_folder_tree(&temp_dir_path, &mut stdout);
let output = String::from_utf8(stdout).unwrap();
assert_eq!(
output,
format!(
"{}\n├── file1.txt\n├── file2.txt\n└── subfolder\n └── file3.txt\n",
temp_dir_path.display()
)
);
}
}