From 53b6b1f2cee6457e487427a878fc433ec761b8bc Mon Sep 17 00:00:00 2001 From: Tao Guo Date: Fri, 24 Nov 2023 20:36:42 -0800 Subject: [PATCH] Update custom command API signature To allow spawning process with stdin/stdout redirection. --- macros/src/lib.rs | 4 ++-- src/io.rs | 10 ++++++++++ src/lib.rs | 1 + src/process.rs | 8 ++++---- 4 files changed, 17 insertions(+), 6 deletions(-) diff --git a/macros/src/lib.rs b/macros/src/lib.rs index 084e0a4..bef67b6 100644 --- a/macros/src/lib.rs +++ b/macros/src/lib.rs @@ -44,8 +44,8 @@ pub fn main( /// ``` /// # use cmd_lib::*; /// fn my_cmd(env: &mut CmdEnv) -> CmdResult { -/// let msg = format!("msg from foo(), args: {:?}\n", env.args()); -/// writeln!(env.stderr(), "{}", msg)?; +/// let msg = format!("msg from foo(), args: {:?}", env.get_args()); +/// writeln!(env.stderr(), "{msg}")?; /// writeln!(env.stdout(), "bar") /// } /// diff --git a/src/io.rs b/src/io.rs index 833def0..fd233cd 100644 --- a/src/io.rs +++ b/src/io.rs @@ -29,6 +29,16 @@ impl From for Stdio { } } +impl CmdIn { + pub fn try_clone(&self) -> Result { + match self { + CmdIn::Null => Ok(CmdIn::Null), + CmdIn::File(file) => file.try_clone().map(CmdIn::File), + CmdIn::Pipe(pipe) => pipe.try_clone().map(CmdIn::Pipe), + } + } +} + pub enum CmdOut { Null, File(File), diff --git a/src/lib.rs b/src/lib.rs index d840e7a..2080bc8 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -377,6 +377,7 @@ pub type FunResult = std::io::Result; /// Return type for [`run_cmd!()`] macro. pub type CmdResult = std::io::Result<()>; pub use child::{CmdChildren, FunChildren}; +pub use io::{CmdIn, CmdOut}; #[doc(hidden)] pub use log as inner_log; #[doc(hidden)] diff --git a/src/process.rs b/src/process.rs index 7bae08f..4428efe 100644 --- a/src/process.rs +++ b/src/process.rs @@ -10,7 +10,7 @@ use std::collections::HashMap; use std::ffi::{OsStr, OsString}; use std::fmt; use std::fs::{File, OpenOptions}; -use std::io::{Error, ErrorKind, Read, Result, Write}; +use std::io::{Error, ErrorKind, Result}; use std::path::{Path, PathBuf}; use std::process::Command; use std::sync::Mutex; @@ -50,17 +50,17 @@ impl CmdEnv { } /// Returns a new handle to the standard input for this command. - pub fn stdin(&mut self) -> impl Read + '_ { + pub fn stdin(&mut self) -> &mut CmdIn { &mut self.stdin } /// Returns a new handle to the standard output for this command. - pub fn stdout(&mut self) -> impl Write + '_ { + pub fn stdout(&mut self) -> &mut CmdOut { &mut self.stdout } /// Returns a new handle to the standard error for this command. - pub fn stderr(&mut self) -> impl Write + '_ { + pub fn stderr(&mut self) -> &mut CmdOut { &mut self.stderr } }