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

watch: implement interval #48

Merged
merged 5 commits into from
Apr 1, 2024
Merged
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
112 changes: 110 additions & 2 deletions src/uu/watch/src/watch.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@

use clap::crate_version;
use clap::{Arg, Command};
use std::io::{Error, ErrorKind};
use std::num::ParseIntError;
use std::process::{Command as SystemCommand, Stdio};
use std::thread::sleep;
use std::time::Duration;
Expand All @@ -13,14 +15,65 @@
const ABOUT: &str = help_about!("watch.md");
const USAGE: &str = help_usage!("watch.md");

fn parse_interval(input: &str) -> Result<Duration, ParseIntError> {
// Find index where to split string into seconds and nanos
let index = match input.find(|c: char| c == ',' || c == '.') {
Some(index) => index,

Check warning on line 21 in src/uu/watch/src/watch.rs

View check run for this annotation

Codecov / codecov/patch

src/uu/watch/src/watch.rs#L21

Added line #L21 was not covered by tests
None => {
let seconds: u64 = input.parse()?;
return Ok(Duration::new(seconds, 0));

Check warning on line 24 in src/uu/watch/src/watch.rs

View check run for this annotation

Codecov / codecov/patch

src/uu/watch/src/watch.rs#L24

Added line #L24 was not covered by tests
}
};

// If the seconds string is empty, set seconds to 0
let seconds: u64 = if index > 0 {
input[..index].parse()?
} else {
0

Check warning on line 32 in src/uu/watch/src/watch.rs

View check run for this annotation

Codecov / codecov/patch

src/uu/watch/src/watch.rs#L32

Added line #L32 was not covered by tests
};

let nanos_string = &input[index + 1..];

Check warning on line 35 in src/uu/watch/src/watch.rs

View check run for this annotation

Codecov / codecov/patch

src/uu/watch/src/watch.rs#L35

Added line #L35 was not covered by tests
let nanos: u32 = match nanos_string.len() {
// If nanos string is empty, set nanos to 0
0 => 0,

Check warning on line 38 in src/uu/watch/src/watch.rs

View check run for this annotation

Codecov / codecov/patch

src/uu/watch/src/watch.rs#L38

Added line #L38 was not covered by tests
1..=9 => {
let nanos: u32 = nanos_string.parse()?;
nanos * 10u32.pow((9 - nanos_string.len()) as u32)
}

Check warning on line 42 in src/uu/watch/src/watch.rs

View check run for this annotation

Codecov / codecov/patch

src/uu/watch/src/watch.rs#L41-L42

Added lines #L41 - L42 were not covered by tests
_ => {
// This parse is used to validate if the rest of the string is indeed numeric
if nanos_string.find(|c: char| !c.is_numeric()).is_some() {
"a".parse::<u8>()?;
}
// We can have only 9 digits of accuracy, trim the rest
nanos_string[..9].parse()?
}

Check warning on line 50 in src/uu/watch/src/watch.rs

View check run for this annotation

Codecov / codecov/patch

src/uu/watch/src/watch.rs#L50

Added line #L50 was not covered by tests
};

let duration = Duration::new(seconds, nanos);

Check warning on line 53 in src/uu/watch/src/watch.rs

View check run for this annotation

Codecov / codecov/patch

src/uu/watch/src/watch.rs#L53

Added line #L53 was not covered by tests
// Minimum duration of sleep to 0.1 s
Ok(std::cmp::max(duration, Duration::from_millis(100)))

Check warning on line 55 in src/uu/watch/src/watch.rs

View check run for this annotation

Codecov / codecov/patch

src/uu/watch/src/watch.rs#L55

Added line #L55 was not covered by tests
}

#[uucore::main]
pub fn uumain(args: impl uucore::Args) -> UResult<()> {
let matches = uu_app().try_get_matches_from(args)?;

let command_to_watch = matches
.get_one::<String>("command")
.expect("required argument");
let interval = 2; // TODO matches.get_one::<u64>("interval").map_or(2, |&v| v);
let interval = match matches.get_one::<String>("interval") {
None => Duration::from_secs(2),

Check warning on line 66 in src/uu/watch/src/watch.rs

View check run for this annotation

Codecov / codecov/patch

src/uu/watch/src/watch.rs#L66

Added line #L66 was not covered by tests
Some(input) => match parse_interval(input) {
Ok(interval) => interval,

Check warning on line 68 in src/uu/watch/src/watch.rs

View check run for this annotation

Codecov / codecov/patch

src/uu/watch/src/watch.rs#L68

Added line #L68 was not covered by tests
Err(_) => {
return Err(Box::from(Error::new(
ErrorKind::InvalidInput,
format!("watch: failed to parse argument: '{input}': Invalid argument"),
)));
}
},

Check warning on line 75 in src/uu/watch/src/watch.rs

View check run for this annotation

Codecov / codecov/patch

src/uu/watch/src/watch.rs#L75

Added line #L75 was not covered by tests
};

loop {
let output = SystemCommand::new("sh")
Expand All @@ -35,12 +88,67 @@
break;
}

sleep(Duration::from_secs(interval));
sleep(interval);

Check warning on line 91 in src/uu/watch/src/watch.rs

View check run for this annotation

Codecov / codecov/patch

src/uu/watch/src/watch.rs#L91

Added line #L91 was not covered by tests
}

Ok(())
}

#[cfg(test)]
mod parse_interval_tests {
use super::*;

#[test]
fn test_comma_parse() {
let interval = parse_interval("1,5");
assert_eq!(Ok(Duration::from_millis(1500)), interval);
}

#[test]
fn test_different_nanos_length() {
let interval = parse_interval("1.12345");
assert_eq!(Ok(Duration::new(1, 123450000)), interval);
let interval = parse_interval("1.1234");
assert_eq!(Ok(Duration::new(1, 123400000)), interval);
}

#[test]
fn test_period_parse() {
let interval = parse_interval("1.5");
assert_eq!(Ok(Duration::from_millis(1500)), interval);
}

#[test]
fn test_empty_seconds_interval() {
let interval = parse_interval(".5");
assert_eq!(Ok(Duration::from_millis(500)), interval);
}

#[test]
fn test_seconds_only() {
let interval = parse_interval("7");
assert_eq!(Ok(Duration::from_secs(7)), interval);
}

#[test]
fn test_empty_nanoseconds_interval() {
let interval = parse_interval("1.");
assert_eq!(Ok(Duration::from_millis(1000)), interval);
}

#[test]
fn test_too_many_nanos() {
let interval = parse_interval("1.00000000009");
assert_eq!(Ok(Duration::from_secs(1)), interval);
}

#[test]
fn test_invalid_nano() {
let interval = parse_interval("1.00000000000a");
assert!(interval.is_err())
}
}

pub fn uu_app() -> Command {
Command::new(uucore::util_name())
.version(crate_version!())
Expand Down
44 changes: 44 additions & 0 deletions tests/by-util/test_watch.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,3 +10,47 @@ use crate::common::util::TestScenario;
fn test_invalid_arg() {
new_ucmd!().arg("--definitely-invalid").fails().code_is(1);
}

#[test]
fn test_invalid_interval() {
let args = vec!["-n", "definitely-not-valid", "true"];
new_ucmd!()
.args(&args)
.fails()
.stderr_contains("Invalid argument");
}

#[test]
fn test_no_interval() {
let mut p = new_ucmd!().arg("true").run_no_wait();
p.make_assertion_with_delay(500).is_alive();
p.kill()
.make_assertion()
.with_all_output()
.no_stderr()
.no_stdout();
}

#[test]
fn test_valid_interval() {
let args = vec!["-n", "1.5", "true"];
let mut p = new_ucmd!().args(&args).run_no_wait();
p.make_assertion_with_delay(500).is_alive();
p.kill()
.make_assertion()
.with_all_output()
.no_stderr()
.no_stdout();
}

#[test]
fn test_valid_interval_comma() {
let args = vec!["-n", "1,5", "true"];
let mut p = new_ucmd!().args(&args).run_no_wait();
p.make_assertion_with_delay(1000).is_alive();
p.kill()
.make_assertion()
.with_all_output()
.no_stderr()
.no_stdout();
}
Loading