Skip to content

Commit

Permalink
Merge #52
Browse files Browse the repository at this point in the history
52: cargo-fmt in CI and format code r=matthiasbeyer a=matthiasbeyer

This PR adds cargo-fmt in the actions workflows and formats the code, so the lint succeeds.

cargo-fmt configuration is set to default.

Co-authored-by: Matthias Beyer <[email protected]>
  • Loading branch information
bors[bot] and matthiasbeyer authored Sep 11, 2022
2 parents 089150f + 0d2812f commit 19c8a0b
Show file tree
Hide file tree
Showing 12 changed files with 163 additions and 111 deletions.
19 changes: 19 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,24 @@ jobs:
with:
command: check


fmt:
name: format
runs-on: ubuntu-latest

steps:
- uses: actions/checkout@v3
- uses: actions-rs/toolchain@v1
with:
toolchain: 1.60.0
- run: rustup component add rustfmt
- name: cargo-fmt
uses: actions-rs/cargo@v1
with:
command: fmt
args: -- --check


# We need some "accummulation" job here because bors fails (timeouts) to
# listen on matrix builds.
# Hence, we have some kind of dummy here that bors can listen on
Expand All @@ -41,6 +59,7 @@ jobs:
if: ${{ success() }}
needs:
- check
- fmt
runs-on: ubuntu-latest
steps:
- name: CI succeeded
Expand Down
2 changes: 1 addition & 1 deletion examples/bash.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
extern crate rexpect;
use rexpect::spawn_bash;
use rexpect::errors::*;
use rexpect::spawn_bash;

fn run() -> Result<()> {
let mut p = spawn_bash(Some(1000))?;
Expand Down
8 changes: 5 additions & 3 deletions examples/bash_read.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
extern crate rexpect;
use rexpect::spawn_bash;
use rexpect::errors::*;

use rexpect::spawn_bash;

fn run() -> Result<()> {
let mut p = spawn_bash(Some(2000))?;
Expand All @@ -19,7 +18,10 @@ fn run() -> Result<()> {
let (_, words) = p.exp_regex("[0-9]+")?;
let (_, bytes) = p.exp_regex("[0-9]+")?;
p.wait_for_prompt()?; // go sure `wc` is really done
println!("/etc/passwd has {} lines, {} words, {} chars", lines, words, bytes);
println!(
"/etc/passwd has {} lines, {} words, {} chars",
lines, words, bytes
);

// case 3: read while program is still executing
p.execute("ping 8.8.8.8", "bytes of data")?; // returns when it sees "bytes of data" in output
Expand Down
7 changes: 2 additions & 5 deletions examples/exit_code.rs
Original file line number Diff line number Diff line change
@@ -1,16 +1,14 @@
extern crate rexpect;

use rexpect::spawn;
use rexpect::errors::*;
use rexpect::process::wait;

use rexpect::spawn;

/// The following code emits:
/// cat exited with code 0, all good!
/// cat exited with code 1
/// Output (stdout and stderr): cat: /this/does/not/exist: No such file or directory
fn exit_code_fun() -> Result<()> {

let p = spawn("cat /etc/passwd", Some(2000))?;
match p.process.wait() {
Ok(wait::WaitStatus::Exited(_, 0)) => println!("cat exited with code 0, all good!"),
Expand All @@ -23,7 +21,7 @@ fn exit_code_fun() -> Result<()> {
Ok(wait::WaitStatus::Exited(_, c)) => {
println!("Cat failed with exit code {}", c);
println!("Output (stdout and stderr): {}", p.exp_eof()?);
},
}
// for other possible return types of wait()
// see here: https://tailhook.github.io/rotor/nix/sys/wait/enum.WaitStatus.html
_ => println!("cat was probably killed"),
Expand All @@ -32,7 +30,6 @@ fn exit_code_fun() -> Result<()> {
Ok(())
}


fn main() {
exit_code_fun().unwrap_or_else(|e| panic!("cat function failed with {}", e));
}
3 changes: 1 addition & 2 deletions examples/ftp.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
extern crate rexpect;

use rexpect::spawn;
use rexpect::errors::*;
use rexpect::spawn;

fn do_ftp() -> Result<()> {
let mut p = spawn("ftp speedtest.tele2.net", Some(2000))?;
Expand All @@ -19,7 +19,6 @@ fn do_ftp() -> Result<()> {
Ok(())
}


fn main() {
do_ftp().unwrap_or_else(|e| panic!("ftp job failed with {}", e));
}
6 changes: 3 additions & 3 deletions examples/repl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@
extern crate rexpect;

use rexpect::spawn;
use rexpect::session::PtyReplSession;
use rexpect::errors::*;
use rexpect::session::PtyReplSession;
use rexpect::spawn;

fn ed_session() -> Result<PtyReplSession> {
let mut ed = PtyReplSession {
Expand Down Expand Up @@ -40,4 +40,4 @@ fn do_ed_repl() -> Result<()> {

fn main() {
do_ed_repl().unwrap_or_else(|e| panic!("ed session failed with {}", e));
}
}
7 changes: 3 additions & 4 deletions examples/tcp.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
use rexpect::spawn_stream;
use std::net::TcpStream;
use std::error::Error;
use std::net::TcpStream;

fn main() -> Result<(), Box<dyn Error>>
{
fn main() -> Result<(), Box<dyn Error>> {
let tcp = TcpStream::connect("www.google.com:80")?;
let tcp_w = tcp.try_clone()?;
let mut session = spawn_stream(tcp, tcp_w, Some(2000));
Expand All @@ -13,4 +12,4 @@ fn main() -> Result<(), Box<dyn Error>>
session.send_line("")?;
session.exp_string("HTTP/1.1 200 OK")?;
Ok(())
}
}
1 change: 1 addition & 0 deletions rustfmt.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
# default
6 changes: 3 additions & 3 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -79,16 +79,16 @@
//! ```
pub mod process;
pub mod session;
pub mod reader;
pub mod session;

pub use session::{spawn, spawn_bash, spawn_python, spawn_stream};
pub use reader::ReadUntil;
pub use session::{spawn, spawn_bash, spawn_python, spawn_stream};

pub mod errors {
use std::time;
// Create the Error, ErrorKind, ResultExt, and Result types
error_chain::error_chain!{
error_chain::error_chain! {
errors {
EOF(expected:String, got:String, exit_code:Option<String>) {
description("End of filestream (usually stdout) occurred, most probably\
Expand Down
57 changes: 27 additions & 30 deletions src/process.rs
Original file line number Diff line number Diff line change
@@ -1,19 +1,19 @@
//! Start a process via pty
use crate::errors::*;
use nix;
use nix::fcntl::{open, OFlag};
use nix::libc::{STDERR_FILENO, STDIN_FILENO, STDOUT_FILENO};
use nix::pty::{grantpt, posix_openpt, unlockpt, PtyMaster};
pub use nix::sys::{signal, wait};
use nix::sys::{stat, termios};
use nix::unistd::{dup, dup2, fork, setsid, ForkResult, Pid};
use std;
use std::fs::File;
use std::process::Command;
use std::os::unix::io::{AsRawFd, FromRawFd};
use std::os::unix::process::CommandExt;
use std::os::unix::io::{FromRawFd, AsRawFd};
use std::{thread, time};
use nix::pty::{posix_openpt, grantpt, unlockpt, PtyMaster};
use nix::fcntl::{OFlag, open};
use nix;
use nix::sys::{stat, termios};
use nix::unistd::{fork, ForkResult, setsid, dup, dup2, Pid};
use nix::libc::{STDIN_FILENO, STDOUT_FILENO, STDERR_FILENO};
pub use nix::sys::{wait, signal};
use crate::errors::*; // load error-chain
use std::process::Command;
use std::{thread, time}; // load error-chain

/// Start a process in a forked tty so you can interact with it the same as you would
/// within a terminal
Expand Down Expand Up @@ -60,7 +60,6 @@ pub struct PtyProcess {
kill_timeout: Option<time::Duration>,
}


#[cfg(target_os = "linux")]
use nix::pty::ptsname_r;

Expand All @@ -69,8 +68,8 @@ use nix::pty::ptsname_r;
/// instead of using a static mutex this calls ioctl with TIOCPTYGNAME directly
/// based on https://blog.tarq.io/ptsname-on-osx-with-rust/
fn ptsname_r(fd: &PtyMaster) -> nix::Result<String> {
use std::ffi::CStr;
use nix::libc::{ioctl, TIOCPTYGNAME};
use std::ffi::CStr;

// the buffer size on OSX is 128, defined by sys/ttycom.h
let mut buf: [i8; 128] = [0; 128];
Expand Down Expand Up @@ -103,9 +102,11 @@ impl PtyProcess {
match fork()? {
ForkResult::Child => {
setsid()?; // create new session with child as session leader
let slave_fd = open(std::path::Path::new(&slave_name),
OFlag::O_RDWR,
stat::Mode::empty())?;
let slave_fd = open(
std::path::Path::new(&slave_name),
OFlag::O_RDWR,
stat::Mode::empty(),
)?;

// assign stdin, stdout, stderr to the tty, just like a terminal does
dup2(slave_fd, STDIN_FILENO)?;
Expand All @@ -120,16 +121,14 @@ impl PtyProcess {
command.exec();
Err(nix::Error::last())
}
ForkResult::Parent { child: child_pid } => {
Ok(PtyProcess {
pty: master_fd,
child_pid: child_pid,
kill_timeout: None,
})
}
ForkResult::Parent { child: child_pid } => Ok(PtyProcess {
pty: master_fd,
child_pid: child_pid,
kill_timeout: None,
}),
}
}()
.chain_err(|| format!("could not execute {:?}", command))
.chain_err(|| format!("could not execute {:?}", command))
}

/// Get handle to pty fork for reading/writing
Expand Down Expand Up @@ -189,8 +188,7 @@ impl PtyProcess {

/// Non-blocking variant of `kill()` (doesn't wait for process to be killed)
pub fn signal(&mut self, sig: signal::Signal) -> Result<()> {
signal::kill(self.child_pid, sig)
.chain_err(|| "failed to send signal to process")?;
signal::kill(self.child_pid, sig).chain_err(|| "failed to send signal to process")?;
Ok(())
}

Expand All @@ -214,7 +212,6 @@ impl PtyProcess {
Err(e) => return Err(format!("kill resulted in error: {:?}", e).into()),
}


match self.status() {
Some(status) if status != wait::WaitStatus::StillAlive => return Ok(status),
Some(_) | None => thread::sleep(time::Duration::from_millis(100)),
Expand Down Expand Up @@ -243,9 +240,9 @@ impl Drop for PtyProcess {
#[cfg(test)]
mod tests {
use super::*;
use std::io::{BufReader, LineWriter};
use nix::sys::{wait, signal};
use nix::sys::{signal, wait};
use std::io::prelude::*;
use std::io::{BufReader, LineWriter};

#[test]
/// Open cat, write string, read back string twice, send Ctrl^C and check that cat exited
Expand All @@ -271,6 +268,6 @@ mod tests {
assert_eq!(should, wait::waitpid(process.child_pid, None).unwrap());
Ok(())
}()
.unwrap_or_else(|e| panic!("test_cat failed: {}", e));
.unwrap_or_else(|e| panic!("test_cat failed: {}", e));
}
}
Loading

0 comments on commit 19c8a0b

Please sign in to comment.