summaryrefslogtreecommitdiffstats
path: root/src/finder.rs
blob: db92c835a7a147b62e42859804deab527e0c798e (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
69
70
71
72
73
use std::{
    io::Write,
    ops::{Deref, DerefMut},
    os::unix::prelude::OsStrExt,
    path::PathBuf,
    process::{Child, Command, Output, Stdio},
};

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

mod config;
mod error;

pub struct Finder(Child);

impl Finder {
    pub fn new(config: &Config) -> Result<Self> {
        Command::new(&config.program)
            .args(&config.args)
            .stdin(Stdio::piped())
            .stdout(Stdio::piped())
            .spawn()
            .map(Into::into)
            .map_err(Into::into)
    }

    pub fn into_inner(self) -> Child {
        self.0
    }

    pub fn write_path_buf_vectored<V>(&mut self, directories: V) -> Result<()>
    where
        V: IntoIterator<Item = PathBuf>,
    {
        let stdin = self.stdin.as_mut().ok_or(Error::Stdin)?;
        directories.into_iter().try_for_each(|path_buf| {
            stdin
                .write_all(path_buf.into_os_string().as_bytes())
                .map_err(From::from)
        })
    }

    pub fn wait_with_output(self) -> Result<Output> {
        self.into_inner().wait_with_output().map_err(From::from)
    }
}

impl Deref for Finder {
    type Target = Child;

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

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

impl From<Child> for Finder {
    fn from(value: Child) -> Self {
        Self(value)
    }
}

impl From<Finder> for Child {
    fn from(value: Finder) -> Child {
        value.0
    }
}