Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #[derive(Clone, Debug)]
- pub enum FileTree {
- File(String),
- Directory(DirectoryData),
- }
- impl Display for FileTree {
- fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
- match self {
- FileTree::File(file_name) => write!(f, "{}", file_name),
- FileTree::Directory(directory_data) => write!(f, "{}", directory_data.name),
- }
- }
- }
- #[derive(Clone, Debug)]
- pub struct DirectoryData {
- depth: u16,
- name: String,
- path: String,
- }
- pub struct TreeFolder {
- current_depth: u16,
- directory_queue: Vec<ItemToSearch>,
- pub tree: Rc<RefCell<Tree<Box<FileTree>>>>,
- }
- impl TreeFolder {
- pub fn new() -> TreeFolder {
- TreeFolder {
- current_depth: 0,
- directory_queue: Vec::new(),
- tree: Rc::new(RefCell::new(Tree::new(Box::new(FileTree::Directory(DirectoryData {
- depth: 0,
- name: String::from("~"),
- path: String::from("~"),
- }))))),
- }
- }
- pub fn build_tree(&mut self, searcher:&impl Searcher, communicator: Box<dyn Communicate>, tcp_wrapper:&mut TcpWrapper) {
- self.search_directory(Rc::clone(&self.tree), searcher, communicator, tcp_wrapper);
- }
- fn search_directory(&mut self, parent: Rc<RefCell<Tree<Box<FileTree>>>>, searcher:&impl Searcher, communicator: Box<dyn Communicate>, tcp_wrapper:&mut TcpWrapper) {
- let (path, depth) = {
- let first = &parent.as_ref()
- .borrow()
- .root;
- match &**first {
- FileTree::Directory(directory_data) => (directory_data.path.clone(), directory_data.depth),
- _ => panic!("First element is not a directory"),
- }
- };
- let _ = tcp_wrapper.send_and_receive(EventsToSend::Cwd(path.to_string()));
- let lines = communicator.retrieve_lines(tcp_wrapper);
- for line in lines {
- let file_data = FileData::new(line);
- self.store_line_in_tree(Rc::clone(&parent), file_data, &path, depth);
- }
- if let Some(next) = searcher.get_next(&mut self.directory_queue) {
- let next_parent = Rc::new(RefCell::new(Tree::new(next.item)));
- self.search_directory(Rc::clone(&next_parent), searcher, communicator, tcp_wrapper);
- }
- }
- fn store_line_in_tree(&mut self, boxed_parent: Rc<RefCell<Tree<Box<FileTree>>>>, file_data: FileData, path:&str, depth: u16) {
- if file_data.m_rights.starts_with('d') {
- let new_directory = Box::new(FileTree::Directory(DirectoryData {
- depth: depth + 1,
- name: file_data.m_name.clone(),
- path: format!("{}/{}", path, file_data.m_name),
- }));
- let as_tree = Tree::new(Box::clone(&new_directory));
- (*boxed_parent).borrow_mut().push(as_tree);
- let new_item = ItemToSearch {
- parent: Rc::clone(&boxed_parent),
- item: new_directory,
- };
- self.directory_queue.push(new_item);
- } else {
- let new_file = Box::new(FileTree::File(file_data.m_name));
- (*boxed_parent).borrow_mut().push(Tree::new(new_file));
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment