From c8681e50194855a2ad36bf984866a30cfcfb8ec9 Mon Sep 17 00:00:00 2001 From: Toby Vincent Date: Fri, 4 Nov 2022 18:48:18 -0500 Subject: refactor: move run to main.rs and impl output from Finder --- src/finder.rs | 80 ++++++++++++++++++++++++++++++++++++----------------------- 1 file changed, 49 insertions(+), 31 deletions(-) (limited to 'src/finder.rs') diff --git a/src/finder.rs b/src/finder.rs index 688009c..db92c83 100644 --- a/src/finder.rs +++ b/src/finder.rs @@ -1,8 +1,9 @@ use std::{ io::Write, - ops::Deref, + ops::{Deref, DerefMut}, + os::unix::prelude::OsStrExt, path::PathBuf, - process::{Child, Command, Stdio}, + process::{Child, Command, Output, Stdio}, }; pub use config::Config; @@ -11,45 +12,62 @@ pub use error::{Error, Result}; mod config; mod error; -pub struct Finder { - pub(crate) child: Child, +pub struct Finder(Child); + +impl Finder { + pub fn new(config: &Config) -> Result { + 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(&mut self, directories: V) -> Result<()> + where + V: IntoIterator, + { + 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 { + self.into_inner().wait_with_output().map_err(From::from) + } } impl Deref for Finder { type Target = Child; fn deref(&self) -> &Self::Target { - &self.child + &self.0 } } -impl Finder { - pub(crate) fn new(config: &Config) -> Result { - Ok(Finder { - child: Command::new(&config.program) - .args(&config.args) - .stdin(Stdio::piped()) - .stdout(Stdio::piped()) - .spawn()?, - }) +impl DerefMut for Finder { + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 } +} - pub(crate) fn run(&mut self, directories: V) -> Result<()> - where - V: IntoIterator, - { - let stdin = directories - .into_iter() - .map(|p: PathBuf| p.to_string_lossy().into()) - .collect::>() - .join("\n"); - - self.child - .stdin - .as_mut() - .ok_or(Error::Stdin)? - .deref() - .write_all(stdin.as_bytes()) - .map_err(Into::into) +impl From for Finder { + fn from(value: Child) -> Self { + Self(value) + } +} + +impl From for Child { + fn from(value: Finder) -> Child { + value.0 } } -- cgit v1.2.3-70-g09d2