Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Cmd::inherit_stdin #98

Closed
wants to merge 5 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

## Unreleased

- Add `Cmd::inherit_stdin` to support pre-0.2.3 behaviour #98

## 0.2.7

- MSRV is raised to 1.63.0
Expand Down
3 changes: 2 additions & 1 deletion examples/ci.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,8 @@ fn test(sh: &Shell) -> Result<()> {

{
let _s = Section::new("TEST");
cmd!(sh, "cargo test --workspace").run()?;
// inherit_stdin tests are skipped because they require an interactive terminal
cmd!(sh, "cargo test --workspace -- --skip inherit_stdin").run()?;
}
Ok(())
}
Expand Down
50 changes: 44 additions & 6 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -752,7 +752,7 @@ struct CmdData {
ignore_status: bool,
quiet: bool,
secret: bool,
stdin_contents: Option<Vec<u8>>,
stdin_mode: StdinMode,
ignore_stdout: bool,
ignore_stderr: bool,
}
Expand All @@ -768,6 +768,33 @@ enum EnvChange {
Clear,
}

#[derive(Debug, Clone, Default)]
enum StdinMode {
/// Default mode.
#[default]
Null,
/// `Cmd::inherit_stdin`.
Inherited,
/// `Cmd::stdin`.
Piped(Vec<u8>),
}
impl StdinMode {
fn set_inherited(&mut self) {
match self {
Self::Null => *self = Self::Inherited,
Self::Inherited => {} // ignore
Self::Piped(_) => panic!("Cmd::inherit_stdin is mutually-exclusive with Cmd::stdin"),
}
}
fn set_piped(&mut self, data: Vec<u8>) {
match self {
Self::Null => *self = Self::Piped(data),
Self::Inherited => panic!("Cmd::stdin is mutually-exclusive with Cmd::inherit_stdin"),
Self::Piped(_) => *self = Self::Piped(data), // replace
}
}
}

impl fmt::Display for Cmd<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(&self.data, f)
Expand Down Expand Up @@ -917,13 +944,23 @@ impl<'a> Cmd<'a> {
self.data.secret = yes;
}

/// Inherit standard input of the parent shell.
///
/// Mutually-exclusive with [`Cmd::stdin`].
pub fn inherit_stdin(mut self) -> Cmd<'a> {
self.data.stdin_mode.set_inherited();
self
}

/// Pass the given slice to the standard input of the spawned process.
///
/// Mutually-exclusive with [`Cmd::inherit_stdin`].
pub fn stdin(mut self, stdin: impl AsRef<[u8]>) -> Cmd<'a> {
self._stdin(stdin.as_ref());
self
}
fn _stdin(&mut self, stdin: &[u8]) {
self.data.stdin_contents = Some(stdin.to_vec());
self.data.stdin_mode.set_piped(stdin.to_vec());
}

/// Ignores the standard output stream of the process.
Expand Down Expand Up @@ -1011,9 +1048,10 @@ impl<'a> Cmd<'a> {
command.stderr(if read_stderr { Stdio::piped() } else { Stdio::inherit() });
}

command.stdin(match &self.data.stdin_contents {
Some(_) => Stdio::piped(),
None => Stdio::null(),
command.stdin(match &self.data.stdin_mode {
StdinMode::Null => Stdio::null(),
StdinMode::Inherited => Stdio::inherit(),
StdinMode::Piped(_) => Stdio::piped(),
});

command.spawn().map_err(|err| {
Expand All @@ -1031,7 +1069,7 @@ impl<'a> Cmd<'a> {
};

let mut io_thread = None;
if let Some(stdin_contents) = self.data.stdin_contents.clone() {
if let StdinMode::Piped(stdin_contents) = self.data.stdin_mode.clone() {
let mut stdin = child.stdin.take().unwrap();
io_thread = Some(std::thread::spawn(move || {
stdin.write_all(&stdin_contents)?;
Expand Down
9 changes: 9 additions & 0 deletions tests/data/stdin_is_terminal/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
[package]
name = "stdin_is_terminal"
version = "0.0.0"
edition = "2021"

[workspace]

[dependencies]
is-terminal = "0.4.13"
14 changes: 14 additions & 0 deletions tests/data/stdin_is_terminal/src/main.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
use std::{io::stdin, process::exit};

// TODO: switch to `std::io::IsTerminal` when MSRV >= 1.70.0
use is_terminal::IsTerminal;

fn main() {
if stdin().is_terminal() {
println!("Stdin is terminal");
exit(0);
} else {
println!("Stdin is not terminal");
exit(1);
}
}
44 changes: 38 additions & 6 deletions tests/it/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,17 +10,33 @@ fn setup() -> Shell {
static ONCE: std::sync::Once = std::sync::Once::new();

let sh = Shell::new().unwrap();
let xecho_src = sh.current_dir().join("./tests/data/xecho.rs");
let single_file_sources = [sh.current_dir().join("./tests/data/xecho.rs")];
let crate_sources = [sh.current_dir().join("./tests/data/stdin_is_terminal/")];
let target_dir = sh.current_dir().join("./target/");

ONCE.call_once(|| {
cmd!(sh, "rustc {xecho_src} --out-dir {target_dir}")
.quiet()
.run()
.unwrap_or_else(|err| panic!("failed to install binaries from mock_bin: {}", err))
for src in single_file_sources {
cmd!(sh, "rustc {src} --out-dir {target_dir}")
.quiet()
.run()
.unwrap_or_else(|err| panic!("failed to install binaries from mock_bin: {}", err))
}
for src_dir in crate_sources {
sh.change_dir(src_dir);
cmd!(sh, "cargo build -q --target-dir {target_dir}")
.quiet()
.run()
.unwrap_or_else(|err| panic!("failed to build mock crate: {err}"));
}
});

sh.set_var("PATH", target_dir);
let path_env = std::env::join_paths([
&target_dir,
&target_dir.join("debug/"),
&target_dir.join("release/"),
])
.unwrap();
sh.set_var("PATH", path_env);
sh
}

Expand Down Expand Up @@ -210,6 +226,22 @@ fn escape() {
assert_eq!(output, r#"\hello\ \world\"#)
}

#[test]
fn inherit_stdin() {
let sh = setup();

let res = cmd!(sh, "stdin_is_terminal").inherit_stdin().run();
assert!(res.is_ok());
}

#[test]
fn no_inherit_stdin() {
let sh = setup();

let res = cmd!(sh, "stdin_is_terminal").run();
assert!(res.is_err());
}

#[test]
fn stdin_redirection() {
let sh = setup();
Expand Down
Loading