i think i got it

mail@pastecode.io avatar
unknown
rust
2 months ago
2.4 kB
1
Indexable
Never
#[derive(Debug)]
pub struct DFS {
    path: PathBuf,
    stack: Vec<PathBuf>,
    read_dir: io::Result<ReadDir>,
    search: String,
    gitignore: Gitignore,
    visited_vertices: HashSet<PathBuf>,
}
impl DFS {
    pub fn new(args: Args) -> DFS {
        let mut new_dfs = DFS {
            path: Default::default(),
            read_dir: std::fs::read_dir(args.get_starting_dir()),
            stack: Vec::new(),
            search: args.get_keywords(),
            gitignore: IgnoreFiles::new(args.get_starting_dir().as_path(), args.get_gitignore())
                .build(),
            visited_vertices: HashSet::new(),
        };
        new_dfs.stack.push(args.get_starting_dir());
        new_dfs
    }
    fn push_children_to_stack(&mut self, p: &Path) {
        match std::fs::read_dir(p) {
            Err(_) => self.stack.push(p.to_path_buf()),
            Ok(readdir) => {
                for dir in readdir {
                    match dir {
                        Err(_) => (),
                        Ok(direntry) => {
                            self.stack.push(direntry.path());
                            // dbg!(&self.stack);
                        }
                    }
                }
            }
        }
    }
}
impl Iterator for DFS {
    type Item = PathBuf;
    fn next(&mut self) -> Option<Self::Item> {
        match self.stack.pop() {
            None => None,
            Some(current_vertex) => {
                if self.visited_vertices.insert(current_vertex.clone()) {
                    match self
                        .gitignore
                        .matched(current_vertex.clone(), current_vertex.is_dir())
                    {
                        Match::None => self.push_children_to_stack(current_vertex.as_path()),
                        _ => (),
                    }
                };
                if let Some(readdir) = self.read_dir.as_mut().ok() {
                    if let Some(res) = readdir.next() {
                        match res {
                            Err(_) => (),
                            Ok(direntry) => {
                                //how to push entire children of each dir into self.stack?
                                self.read_dir = std::fs::read_dir(direntry.path());
                            }
                        }
                    }
                }
                Some(current_vertex)
            }
        }
    }
}
Leave a Comment