summaryrefslogtreecommitdiffstats
path: root/src/finder.rs
blob: 688009c063c70d5009cf086c198dfd6977ed4470 (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
use std::{
    io::Write,
    ops::Deref,
    path::PathBuf,
    process::{Child, Command, Stdio},
};

pub use config::Config;
pub use error::{Error, Result};

mod config;
mod error;

pub struct Finder {
    pub(crate) child: Child,
}

impl Deref for Finder {
    type Target = Child;

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

impl Finder {
    pub(crate) fn new(config: &Config) -> Result<Self> {
        Ok(Finder {
            child: Command::new(&config.program)
                .args(&config.args)
                .stdin(Stdio::piped())
                .stdout(Stdio::piped())
                .spawn()?,
        })
    }

    pub(crate) fn run<V>(&mut self, directories: V) -> Result<()>
    where
        V: IntoIterator<Item = PathBuf>,
    {
        let stdin = directories
            .into_iter()
            .map(|p: PathBuf| p.to_string_lossy().into())
            .collect::<Vec<String>>()
            .join("\n");

        self.child
            .stdin
            .as_mut()
            .ok_or(Error::Stdin)?
            .deref()
            .write_all(stdin.as_bytes())
            .map_err(Into::into)
    }
}