Skip to content

Commit 9e7e5f9

Browse files
Merge #57
57: Add clippy r=matthiasbeyer a=matthiasbeyer This PR adds `cargo-clippy` and cleans up all warnings. Co-authored-by: Matthias Beyer <[email protected]>
2 parents be11064 + 8a9a7d9 commit 9e7e5f9

File tree

5 files changed

+68
-68
lines changed

5 files changed

+68
-68
lines changed

.github/workflows/ci.yml

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,21 @@ jobs:
7171
args: -- --check
7272

7373

74+
clippy:
75+
name: clippy
76+
runs-on: ubuntu-latest
77+
steps:
78+
- uses: actions/checkout@v3
79+
- uses: actions-rs/toolchain@v1
80+
with:
81+
toolchain: 1.60.0
82+
override: true
83+
- uses: swatinem/rust-cache@v1
84+
- run: rustup component add clippy
85+
- name: cargo-clippy
86+
run: cargo clippy --all --all-targets --all-features
87+
88+
7489
# We need some "accummulation" job here because bors fails (timeouts) to
7590
# listen on matrix builds.
7691
# Hence, we have some kind of dummy here that bors can listen on
@@ -81,6 +96,7 @@ jobs:
8196
- check
8297
- deny
8398
- fmt
99+
- clippy
84100
runs-on: ubuntu-latest
85101
steps:
86102
- name: CI succeeded

src/lib.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -107,7 +107,7 @@ pub mod errors {
107107
description("The process didn't end within the given timeout")
108108
display("Timeout Error: Expected {} but got \"{}\" (after waiting {} ms)",
109109
expected, got, (timeout.as_secs() * 1000) as u32
110-
+ timeout.subsec_nanos() / 1_000_000)
110+
+ timeout.subsec_millis())
111111
}
112112
EmptyProgramName {
113113
description("The provided program name is empty.")

src/process.rs

Lines changed: 5 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -123,7 +123,7 @@ impl PtyProcess {
123123
}
124124
ForkResult::Parent { child: child_pid } => Ok(PtyProcess {
125125
pty: master_fd,
126-
child_pid: child_pid,
126+
child_pid,
127127
kill_timeout: None,
128128
}),
129129
}
@@ -142,7 +142,7 @@ impl PtyProcess {
142142
/// the process does not react to a normal kill. If kill_timeout is set the process is
143143
/// `kill -9`ed after duration
144144
pub fn set_kill_timeout(&mut self, timeout_ms: Option<u64>) {
145-
self.kill_timeout = timeout_ms.and_then(|millis| Some(time::Duration::from_millis(millis)));
145+
self.kill_timeout = timeout_ms.map(time::Duration::from_millis);
146146
}
147147

148148
/// Get status of child process, non-blocking.
@@ -228,11 +228,8 @@ impl PtyProcess {
228228

229229
impl Drop for PtyProcess {
230230
fn drop(&mut self) {
231-
match self.status() {
232-
Some(wait::WaitStatus::StillAlive) => {
233-
self.exit().expect("cannot exit");
234-
}
235-
_ => {}
231+
if let Some(wait::WaitStatus::StillAlive) = self.status() {
232+
self.exit().expect("cannot exit");
236233
}
237234
}
238235
}
@@ -253,7 +250,7 @@ mod tests {
253250
let f = process.get_file_handle();
254251
let mut writer = LineWriter::new(&f);
255252
let mut reader = BufReader::new(&f);
256-
writer.write(b"hello cat\n")?;
253+
let _ = writer.write(b"hello cat\n")?;
257254
let mut buf = String::new();
258255
reader.read_line(&mut buf)?;
259256
assert_eq!(buf, "hello cat\r\n");

src/reader.rs

Lines changed: 24 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ enum PipeError {
1414
}
1515

1616
#[derive(Debug)]
17+
#[allow(clippy::upper_case_acronyms)]
1718
enum PipedChar {
1819
Char(u8),
1920
EOF,
@@ -30,13 +31,13 @@ pub enum ReadUntil {
3031
impl fmt::Display for ReadUntil {
3132
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3233
let printable = match self {
33-
&ReadUntil::String(ref s) if s == "\n" => "\\n (newline)".to_string(),
34-
&ReadUntil::String(ref s) if s == "\r" => "\\r (carriage return)".to_string(),
35-
&ReadUntil::String(ref s) => format!("\"{}\"", s),
36-
&ReadUntil::Regex(ref r) => format!("Regex: \"{}\"", r),
37-
&ReadUntil::EOF => "EOF (End of File)".to_string(),
38-
&ReadUntil::NBytes(n) => format!("reading {} bytes", n),
39-
&ReadUntil::Any(ref v) => {
34+
ReadUntil::String(ref s) if s == "\n" => "\\n (newline)".to_string(),
35+
ReadUntil::String(ref s) if s == "\r" => "\\r (carriage return)".to_string(),
36+
ReadUntil::String(ref s) => format!("\"{}\"", s),
37+
ReadUntil::Regex(ref r) => format!("Regex: \"{}\"", r),
38+
ReadUntil::EOF => "EOF (End of File)".to_string(),
39+
ReadUntil::NBytes(n) => format!("reading {} bytes", n),
40+
ReadUntil::Any(ref v) => {
4041
let mut res = Vec::new();
4142
for r in v {
4243
res.push(r.to_string());
@@ -62,35 +63,29 @@ impl fmt::Display for ReadUntil {
6263
/// 2. position after match
6364
pub fn find(needle: &ReadUntil, buffer: &str, eof: bool) -> Option<(usize, usize)> {
6465
match needle {
65-
&ReadUntil::String(ref s) => buffer.find(s).and_then(|pos| Some((pos, pos + s.len()))),
66-
&ReadUntil::Regex(ref pattern) => {
67-
if let Some(mat) = pattern.find(buffer) {
68-
Some((mat.start(), mat.end()))
69-
} else {
70-
None
71-
}
72-
}
73-
&ReadUntil::EOF => {
66+
ReadUntil::String(ref s) => buffer.find(s).map(|pos| (pos, pos + s.len())),
67+
ReadUntil::Regex(ref pattern) => pattern.find(buffer).map(|mat| (mat.start(), mat.end())),
68+
ReadUntil::EOF => {
7469
if eof {
7570
Some((0, buffer.len()))
7671
} else {
7772
None
7873
}
7974
}
80-
&ReadUntil::NBytes(n) => {
81-
if n <= buffer.len() {
82-
Some((0, n))
83-
} else if eof && buffer.len() > 0 {
75+
ReadUntil::NBytes(n) => {
76+
if *n <= buffer.len() {
77+
Some((0, *n))
78+
} else if eof && buffer.is_empty() {
8479
// reached almost end of buffer, return string, even though it will be
8580
// smaller than the wished n bytes
8681
Some((0, buffer.len()))
8782
} else {
8883
None
8984
}
9085
}
91-
&ReadUntil::Any(ref any) => {
86+
ReadUntil::Any(ref any) => {
9287
for read_until in any {
93-
if let Some(pos_tuple) = find(&read_until, buffer, eof) {
88+
if let Some(pos_tuple) = find(read_until, buffer, eof) {
9489
return Some(pos_tuple);
9590
}
9691
}
@@ -131,7 +126,7 @@ impl NBReader {
131126
loop {
132127
match reader.read(&mut byte) {
133128
Ok(0) => {
134-
let _ = tx.send(Ok(PipedChar::EOF)).chain_err(|| "cannot send")?;
129+
tx.send(Ok(PipedChar::EOF)).chain_err(|| "cannot send")?;
135130
break;
136131
}
137132
Ok(_) => {
@@ -155,7 +150,7 @@ impl NBReader {
155150
reader: rx,
156151
buffer: String::with_capacity(1024),
157152
eof: false,
158-
timeout: timeout.and_then(|millis| Some(time::Duration::from_millis(millis))),
153+
timeout: timeout.map(time::Duration::from_millis),
159154
}
160155
}
161156

@@ -252,8 +247,8 @@ impl NBReader {
252247
needle.to_string(),
253248
self.buffer
254249
.clone()
255-
.replace("\n", "`\\n`\n")
256-
.replace("\r", "`\\r`")
250+
.replace('\n', "`\\n`\n")
251+
.replace('\r', "`\\r`")
257252
.replace('\u{1b}', "`^`"),
258253
timeout,
259254
)
@@ -270,7 +265,7 @@ impl NBReader {
270265
pub fn try_read(&mut self) -> Option<char> {
271266
// discard eventual errors, EOF will be handled in read_until correctly
272267
let _ = self.read_into_buffer();
273-
if self.buffer.len() > 0 {
268+
if self.buffer.is_empty() {
274269
self.buffer.drain(..1).last()
275270
} else {
276271
None
@@ -293,9 +288,9 @@ mod tests {
293288
);
294289
// check for EOF
295290
match r.read_until(&ReadUntil::NBytes(10)) {
296-
Ok(_) => assert!(false),
291+
Ok(_) => panic!(),
297292
Err(Error(ErrorKind::EOF(_, _, _), _)) => {}
298-
Err(Error(_, _)) => assert!(false),
293+
Err(Error(_, _)) => panic!(),
299294
}
300295
}
301296

src/session.rs

Lines changed: 22 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ impl<W: Write> StreamSession<W> {
3232
let mut len = self.send(line)?;
3333
len += self
3434
.writer
35-
.write(&['\n' as u8])
35+
.write(&[b'\n'])
3636
.chain_err(|| "cannot write newline")?;
3737
Ok(len)
3838
}
@@ -53,8 +53,8 @@ impl<W: Write> StreamSession<W> {
5353
/// E.g. `send_control('c')` sends ctrl-c. Upper/smaller case does not matter.
5454
pub fn send_control(&mut self, c: char) -> Result<()> {
5555
let code = match c {
56-
'a'..='z' => c as u8 + 1 - 'a' as u8,
57-
'A'..='Z' => c as u8 + 1 - 'A' as u8,
56+
'a'..='z' => c as u8 + 1 - b'a',
57+
'A'..='Z' => c as u8 + 1 - b'A',
5858
'[' => 27,
5959
'\\' => 28,
6060
']' => 29,
@@ -105,7 +105,7 @@ impl<W: Write> StreamSession<W> {
105105
/// Wait until we see EOF (i.e. child process has terminated)
106106
/// Return all the yet unread output
107107
pub fn exp_eof(&mut self) -> Result<String> {
108-
self.exp(&ReadUntil::EOF).and_then(|(_, s)| Ok(s))
108+
self.exp(&ReadUntil::EOF).map(|(_, s)| s)
109109
}
110110

111111
/// Wait until provided regex is seen on stdout of child process.
@@ -116,26 +116,23 @@ impl<W: Write> StreamSession<W> {
116116
/// Note that `exp_regex("^foo")` matches the start of the yet consumed output.
117117
/// For matching the start of the line use `exp_regex("\nfoo")`
118118
pub fn exp_regex(&mut self, regex: &str) -> Result<(String, String)> {
119-
let res = self
120-
.exp(&ReadUntil::Regex(
121-
Regex::new(regex).chain_err(|| "invalid regex")?,
122-
))
123-
.and_then(|s| Ok(s));
124-
res
119+
self.exp(&ReadUntil::Regex(
120+
Regex::new(regex).chain_err(|| "invalid regex")?,
121+
))
125122
}
126123

127124
/// Wait until provided string is seen on stdout of child process.
128125
/// Return the yet unread output (without the matched string)
129126
pub fn exp_string(&mut self, needle: &str) -> Result<String> {
130127
self.exp(&ReadUntil::String(needle.to_string()))
131-
.and_then(|(s, _)| Ok(s))
128+
.map(|(s, _)| s)
132129
}
133130

134131
/// Wait until provided char is seen on stdout of child process.
135132
/// Return the yet unread output (without the matched char)
136133
pub fn exp_char(&mut self, needle: char) -> Result<String> {
137134
self.exp(&ReadUntil::String(needle.to_string()))
138-
.and_then(|(s, _)| Ok(s))
135+
.map(|(s, _)| s)
139136
}
140137

141138
/// Wait until any of the provided needles is found.
@@ -362,7 +359,7 @@ impl Drop for PtyReplSession {
362359
fn drop(&mut self) {
363360
if let Some(ref cmd) = self.quit_command {
364361
self.pty_session
365-
.send_line(&cmd)
362+
.send_line(cmd)
366363
.expect("could not run `exit` on bash process");
367364
}
368365
}
@@ -399,7 +396,7 @@ pub fn spawn_bash(timeout: Option<u64>) -> Result<PtyReplSession> {
399396
// would set as PS1 and we cannot know when is the right time
400397
// to set the new PS1
401398
let mut rcfile = tempfile::NamedTempFile::new().unwrap();
402-
rcfile
399+
let _ = rcfile
403400
.write(
404401
b"include () { [[ -f \"$1\" ]] && source \"$1\"; }\n\
405402
include /etc/bash.bashrc\n\
@@ -411,10 +408,7 @@ pub fn spawn_bash(timeout: Option<u64>) -> Result<PtyReplSession> {
411408
let mut c = Command::new("bash");
412409
c.args(&[
413410
"--rcfile",
414-
rcfile
415-
.path()
416-
.to_str()
417-
.unwrap_or_else(|| return "temp file does not exist".into()),
411+
rcfile.path().to_str().unwrap_or("temp file does not exist"),
418412
]);
419413
spawn_command(c, timeout).and_then(|p| {
420414
let new_prompt = "[REXPECT_PROMPT>";
@@ -439,13 +433,11 @@ pub fn spawn_bash(timeout: Option<u64>) -> Result<PtyReplSession> {
439433
///
440434
/// This is just a proof of concept implementation (and serves for documentation purposes)
441435
pub fn spawn_python(timeout: Option<u64>) -> Result<PtyReplSession> {
442-
spawn_command(Command::new("python"), timeout).and_then(|p| {
443-
Ok(PtyReplSession {
444-
prompt: ">>> ".to_string(),
445-
pty_session: p,
446-
quit_command: Some("exit()".to_string()),
447-
echo_on: true,
448-
})
436+
spawn_command(Command::new("python"), timeout).map(|p| PtyReplSession {
437+
prompt: ">>> ".to_string(),
438+
pty_session: p,
439+
quit_command: Some("exit()".to_string()),
440+
echo_on: true,
449441
})
450442
}
451443

@@ -484,9 +476,9 @@ mod tests {
484476
|| -> Result<()> {
485477
let mut p = spawn("sleep 3", Some(1000)).expect("cannot run sleep 3");
486478
match p.exp_eof() {
487-
Ok(_) => assert!(false, "should raise Timeout"),
479+
Ok(_) => panic!("should raise Timeout"),
488480
Err(Error(ErrorKind::Timeout(_, _, _), _)) => {}
489-
Err(_) => assert!(false, "should raise TimeOut"),
481+
Err(_) => panic!("should raise TimeOut"),
490482
}
491483
Ok(())
492484
}()
@@ -533,7 +525,7 @@ mod tests {
533525
ReadUntil::String("Hi".to_string()),
534526
]) {
535527
Ok(s) => assert_eq!(("".to_string(), "Hi\r".to_string()), s),
536-
Err(e) => assert!(false, format!("got error: {}", e)),
528+
Err(e) => panic!("got error: {}", e),
537529
}
538530
Ok(())
539531
}()
@@ -544,9 +536,9 @@ mod tests {
544536
fn test_expect_empty_command_error() {
545537
let p = spawn("", Some(1000));
546538
match p {
547-
Ok(_) => assert!(false, "should raise an error"),
539+
Ok(_) => panic!("should raise an error"),
548540
Err(Error(ErrorKind::EmptyProgramName, _)) => {}
549-
Err(_) => assert!(false, "should raise EmptyProgramName"),
541+
Err(_) => panic!("should raise EmptyProgramName"),
550542
}
551543
}
552544

0 commit comments

Comments
 (0)