Skip to content

Commit

Permalink
Fix cargo fmt
Browse files Browse the repository at this point in the history
  • Loading branch information
zhiburt committed Jan 16, 2022
1 parent 4a6af3a commit c7ca22c
Show file tree
Hide file tree
Showing 15 changed files with 97 additions and 71 deletions.
1 change: 0 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ keywords = ["expect", "pty", "testing", "terminal", "automation"]
readme = "README.md"

[features]
# default = ["async"]
async = ["futures-lite", "futures-timer", "async-io", "blocking"]

[dependencies]
Expand Down
2 changes: 1 addition & 1 deletion examples/log.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use expectrl::{Error, spawn};
use expectrl::{spawn, Error};

#[cfg(not(feature = "async"))]
fn main() -> Result<(), Error> {
Expand Down
15 changes: 7 additions & 8 deletions examples/powershell.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,22 +4,21 @@ fn main() {

#[cfg(feature = "async")]
{
futures_lite::future::block_on( async {
futures_lite::future::block_on(async {
let mut p = spawn_powershell().await.unwrap();

eprintln!(
"Current hostname",
);
eprintln!("Current hostname",);

// case 1: execute
let hostname = p.execute("hostname").await.unwrap();
println!(
"Current hostname: {:?}",
String::from_utf8(hostname).unwrap()
);

// case 2: wait until done, only extract a few infos
p.send_line("type README.md | Measure-Object -line -word -character").await
p.send_line("type README.md | Measure-Object -line -word -character")
.await
.unwrap();
let lines = p.expect(Regex("[0-9]+\\s")).await.unwrap();
let words = p.expect(Regex("[0-9]+\\s")).await.unwrap();
Expand All @@ -32,7 +31,7 @@ fn main() {
String::from_utf8_lossy(words.first()),
String::from_utf8_lossy(bytes.matches()[1]),
);

// case 3: read while program is still executing
p.send_line("ping 8.8.8.8 -t").await.unwrap();
for _ in 0..5 {
Expand All @@ -42,7 +41,7 @@ fn main() {
String::from_utf8_lossy(duration.first())
);
}

p.send_control(ControlCode::ETX).await.unwrap();
p.expect_prompt().await.unwrap();
});
Expand Down
17 changes: 10 additions & 7 deletions src/interact.rs
Original file line number Diff line number Diff line change
Expand Up @@ -327,10 +327,7 @@ where
/// Runs interact interactively.
/// See [Session::interact]
#[cfg(windows)]
pub fn interact(
&mut self,
session: &mut Session,
) -> Result<(), Error> {
pub fn interact(&mut self, session: &mut Session) -> Result<(), Error> {
match self.input_from {
InputFrom::Terminal => interact_in_terminal(session, self),
InputFrom::Other => interact(session, self),
Expand All @@ -341,7 +338,7 @@ where
#[cfg(feature = "async")]
impl<R, W, C> InteractOptions<R, W, C>
where
R: Read + std::marker::Unpin,
R: futures_lite::AsyncRead + std::marker::Unpin,
W: Write,
{
/// Runs interact interactively.
Expand All @@ -353,7 +350,14 @@ where
InputFrom::Other => interact(session, self).await,
}
}
}

#[cfg(feature = "async")]
impl<R, W, C> InteractOptions<R, W, C>
where
R: Read + std::marker::Unpin,
W: Write,
{
/// Runs interact interactively.
/// See [Session::interact]
#[cfg(windows)]
Expand Down Expand Up @@ -816,7 +820,6 @@ where
}
}


#[cfg(windows)]
#[cfg(feature = "async")]
async fn interact_in_terminal<R, W, C>(
Expand Down Expand Up @@ -886,7 +889,7 @@ where
options.output.flush()?;
}
Some(Err(err)) => return Err(err.into()),
None => {},
None => {}
}

// We dont't print user input back to the screen.
Expand Down
2 changes: 1 addition & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -182,4 +182,4 @@ mod tests {
}
}
}
}
}
18 changes: 12 additions & 6 deletions src/repl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -147,15 +147,21 @@ pub async fn spawn_powershell() -> Result<ReplSession, Error> {
powershell.is_echo_on = true;

// https://stackoverflow.com/questions/5725888/windows-powershell-changing-the-command-prompt
powershell.execute(format!(
r#"function prompt {{ "{}"; return " " }}"#,
DEFAULT_PROMPT
)).await?;
powershell
.execute(format!(
r#"function prompt {{ "{}"; return " " }}"#,
DEFAULT_PROMPT
))
.await?;

// https://stackoverflow.com/questions/69063656/is-it-possible-to-stop-powershell-wrapping-output-in-ansi-sequences/69063912#69063912
// https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_ansi_terminals?view=powershell-7.2#disabling-ansi-output
powershell.execute(r#"[System.Environment]::SetEnvironmentVariable("TERM", "dumb")"#).await?;
powershell.execute(r#"[System.Environment]::SetEnvironmentVariable("TERM", "NO_COLOR")"#).await?;
powershell
.execute(r#"[System.Environment]::SetEnvironmentVariable("TERM", "dumb")"#)
.await?;
powershell
.execute(r#"[System.Environment]::SetEnvironmentVariable("TERM", "NO_COLOR")"#)
.await?;

Ok(powershell)
}
Expand Down
30 changes: 22 additions & 8 deletions src/session/async_session.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,21 +3,26 @@ use std::{
io,
ops::{Deref, DerefMut},
pin::Pin,
process::Command,
task::{Context, Poll},
time::Duration,
};

use futures_lite::{AsyncBufRead, AsyncRead, AsyncWrite, AsyncWriteExt};

use crate::{stream::log::LoggedStream, ControlCode, Error, Found, Needle};
use super::async_stream::Stream;
use crate::{stream::log::LoggedStream, ControlCode, Error, Found, Needle};

#[cfg(unix)]
pub type Session = PtySession<ptyprocess::PtyProcess, AsyncStream<LoggedStream<'static, crate::stream::unix::PtyStream>>>;
pub type Session = PtySession<
ptyprocess::PtyProcess,
AsyncStream<LoggedStream<'static, crate::stream::unix::PtyStream>>,
>;

#[cfg(windows)]
pub type Session = PtySession<conpty::Process, AsyncStream<LoggedStream<'static, crate::stream::windows::ProcessStream>>>;
pub type Session = PtySession<
conpty::Process,
AsyncStream<LoggedStream<'static, crate::stream::windows::ProcessStream>>,
>;

#[cfg(unix)]
type AsyncStream<S> = async_io::Async<S>;
Expand All @@ -31,16 +36,17 @@ impl Session {
let process = ptyprocess::PtyProcess::spawn(command)?;
let stream = crate::stream::unix::PtyStream::new(process.get_pty_stream()?);
let logged_stream = LoggedStream::new(stream, io::sink());
let async_logged_stream = AsyncStream::new(logged_stream);
let session = Self::new(process, async_logged_stream)?;
let async_logged_stream = AsyncStream::new(logged_stream)?;
let session = Self::new(process, async_logged_stream);

Ok(session)
}

#[cfg(windows)]
pub fn spawn(attr: conpty::ProcAttr) -> Result<Self, Error> {
let process = attr.spawn()?;
let stream = crate::stream::windows::ProcessStream::new(process.output()?, process.input()?);
let stream =
crate::stream::windows::ProcessStream::new(process.output()?, process.input()?);
let logged_stream = LoggedStream::new(stream, io::sink());
let async_logged_stream = AsyncStream::new(logged_stream);
let session = Self::new(process, async_logged_stream);
Expand Down Expand Up @@ -96,7 +102,10 @@ impl Session {

/// Set logger.
pub async fn set_log<W: io::Write + Send + 'static>(&mut self, logger: W) -> io::Result<()> {
#[cfg(windows)]
self.stream.get_mut().get_mut().await.set_logger(logger);
#[cfg(unix)]
self.stream.get_mut().get_mut().set_logger(logger);
Ok(())
}
}
Expand All @@ -112,7 +121,12 @@ pub struct PtySession<P, S> {
// GEt back to the solution where Logger is just dyn Write instead of all these magic with type system.....

impl<P, S> PtySession<P, S> {
pub fn new(process: P, stream: S) -> Self { Self { process, stream: Stream::new(stream) } }
pub fn new(process: P, stream: S) -> Self {
Self {
process,
stream: Stream::new(stream),
}
}

/// Set the pty session's expect timeout.
pub fn set_expect_timeout(&mut self, expect_timeout: Option<Duration>) {
Expand Down
6 changes: 5 additions & 1 deletion src/session/async_stream.rs
Original file line number Diff line number Diff line change
Expand Up @@ -190,7 +190,11 @@ impl<S: AsyncWrite + Unpin> AsyncWrite for Stream<S> {
Pin::new(&mut *self.stream.get_mut()).poll_close(cx)
}

fn poll_write_vectored(mut self: Pin<&mut Self>, cx: &mut Context<'_>, bufs: &[io::IoSlice<'_>]) -> Poll<io::Result<usize>> {
fn poll_write_vectored(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
bufs: &[io::IoSlice<'_>],
) -> Poll<io::Result<usize>> {
Pin::new(&mut *self.stream.get_mut()).poll_write_vectored(cx, bufs)
}
}
Expand Down
17 changes: 8 additions & 9 deletions src/session/session.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,20 +8,18 @@ use std::{
};

use crate::{
control_code::ControlCode,
error::Error,
needle::Needle,
stream::log::LoggedStream,
Found,
control_code::ControlCode, error::Error, needle::Needle, stream::log::LoggedStream, Found,
};

use super::stream::{TryStream, NonBlocking};
use super::stream::{NonBlocking, TryStream};

#[cfg(unix)]
pub type Session = PtySession<ptyprocess::PtyProcess, LoggedStream<'static, crate::stream::unix::PtyStream>>;
pub type Session =
PtySession<ptyprocess::PtyProcess, LoggedStream<'static, crate::stream::unix::PtyStream>>;

#[cfg(windows)]
pub type Session = PtySession<conpty::Process, LoggedStream<'static, crate::stream::windows::ProcessStream>>;
pub type Session =
PtySession<conpty::Process, LoggedStream<'static, crate::stream::windows::ProcessStream>>;

impl Session {
#[cfg(unix)]
Expand All @@ -37,7 +35,8 @@ impl Session {
#[cfg(windows)]
pub fn spawn(attr: conpty::ProcAttr) -> Result<Self, Error> {
let process = attr.spawn()?;
let stream = crate::stream::windows::ProcessStream::new(process.output()?, process.input()?);
let stream =
crate::stream::windows::ProcessStream::new(process.output()?, process.input()?);
let logged_stream = LoggedStream::new(stream, io::sink());
let session = Self::new(process, logged_stream)?;

Expand Down
2 changes: 1 addition & 1 deletion src/session/stream.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ impl<S: Read> TryStream<S> {
pub fn get_mut(&mut self) -> &mut S {
self.stream.get_mut()
}

pub fn get_available(&mut self) -> &[u8] {
self.stream.get_available()
}
Expand Down
4 changes: 3 additions & 1 deletion src/stream/log.rs
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,9 @@ impl<S: std::os::unix::prelude::AsRawFd> std::os::unix::prelude::AsRawFd for Log
}

#[cfg(windows)]
impl<S: std::os::windows::io::AsRawSocket> std::os::windows::io::AsRawSocket for LoggedStream<'_, S> {
impl<S: std::os::windows::io::AsRawSocket> std::os::windows::io::AsRawSocket
for LoggedStream<'_, S>
{
fn as_raw_socket(&self) -> std::os::windows::prelude::RawSocket {
self.stream.as_raw_socket()
}
Expand Down
2 changes: 1 addition & 1 deletion src/stream/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,4 @@ pub mod log;
#[cfg(unix)]
pub mod unix;
#[cfg(windows)]
pub mod windows;
pub mod windows;
14 changes: 6 additions & 8 deletions tests/expect.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ fn expect_str() {
session.send_line("Hello World").unwrap();
session.expect("Hello World").unwrap();
}

#[cfg(feature = "async")]
{
futures_lite::future::block_on(async {
Expand Down Expand Up @@ -82,7 +82,6 @@ fn expect_regex() {
// give shell some time
std::thread::sleep(Duration::from_millis(300));


#[cfg(not(feature = "async"))]
{
let m = session.expect(Regex("lo.*")).unwrap();
Expand All @@ -92,7 +91,7 @@ fn expect_regex() {
);
assert_eq!(m.first(), b"lo");
}

#[cfg(feature = "async")]
{
futures_lite::future::block_on(async {
Expand Down Expand Up @@ -133,7 +132,7 @@ fn expect_n_bytes() {
#[cfg(windows)]
#[test]
fn expect_n_bytes() {
use expectrl::{ProcAttr, session::Session};
use expectrl::{session::Session, ProcAttr};

let mut session = Session::spawn(ProcAttr::cmd(r#"echo Hello World"#.to_string())).unwrap();

Expand All @@ -147,7 +146,7 @@ fn expect_n_bytes() {
assert_eq!(m.first(), "\u{1b}[2J\u{1b}[m\u{1b}[HHell".as_bytes());
assert_eq!(m.before(), b"");
}

#[cfg(feature = "async")]
{
futures_lite::future::block_on(async {
Expand Down Expand Up @@ -198,7 +197,7 @@ fn expect_eof() {
assert_eq!(m.first(), b"'Hello World'\r\n");
assert_eq!(m.before(), b"");
}

#[cfg(feature = "async")]
{
futures_lite::future::block_on(async {
Expand Down Expand Up @@ -303,15 +302,14 @@ fn expect_eof_timeout() {
let mut p = spawn("sleep 3").expect("cannot run sleep 3");
p.set_expect_timeout(Some(Duration::from_millis(100)));


#[cfg(not(feature = "async"))]
{
match p.expect(Eof) {
Err(expectrl::Error::ExpectTimeout) => {}
r => panic!("should raise TimeOut {:?}", r),
}
}

#[cfg(feature = "async")]
{
futures_lite::future::block_on(async {
Expand Down

0 comments on commit c7ca22c

Please sign in to comment.