summaryrefslogtreecommitdiffstats
path: root/src/search.rs
blob: 27495b0b625c62005afda472caa1b3adf83f317c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
use std::{
    ops::{Deref, DerefMut},
    path::{Path, PathBuf},
};

use ignore::{DirEntry, WalkBuilder};
use tracing::{debug, error};

use crate::{parser::Parser, project::Project};

pub struct SearchBuilder {
    walk_builder: WalkBuilder,
    projects: Vec<PathBuf>,
    parsers: Vec<Box<dyn Parser>>,
}

impl SearchBuilder {
    pub fn new<P: AsRef<Path>>(path: P) -> Self {
        Self {
            walk_builder: WalkBuilder::new(&path),
            projects: Default::default(),
            parsers: Default::default(),
        }
    }

    pub fn project<P: AsRef<Path>>(&mut self, path: P) {
        self.projects.push(path.as_ref().to_path_buf())
    }

    pub fn parser(&mut self, parser: impl Parser + 'static) {
        self.parsers.push(Box::new(parser))
    }

    pub fn build(mut self) -> impl Iterator<Item = Project> {
        self.walk_builder
            .standard_filters(true)
            .build()
            .inspect(|res| {
                if let Err(err) = res {
                    error!(%err, "Ignoring errored path");
                }
            })
            .flatten()
            .map(DirEntry::into_path)
            .chain(self.projects.into_iter())
            .map(move |p| self.parsers.parse(p))
            .inspect(|res| {
                if let Err(err) = res {
                    debug!(%err, "Failed to match");
                }
            })
            .flatten()
    }
}

impl Deref for SearchBuilder {
    type Target = WalkBuilder;

    fn deref(&self) -> &Self::Target {
        &self.walk_builder
    }
}

impl DerefMut for SearchBuilder {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.walk_builder
    }
}