Skip to content

Commit

Permalink
Merge pull request #3329 from DevSabb/shuf-gnu-test
Browse files Browse the repository at this point in the history
shuf: accept multiple occurances of head-count argument
  • Loading branch information
sylvestre authored Mar 28, 2022
2 parents d6fd701 + 36ec76e commit 746e35c
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 11 deletions.
30 changes: 19 additions & 11 deletions src/uu/shuf/src/shuf.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@

// spell-checker:ignore (ToDO) cmdline evec seps rvec fdata

use clap::{crate_version, Arg, Command};
use clap::{crate_version, Arg, Command, Values};
use rand::prelude::SliceRandom;
use rand::RngCore;
use std::fs::File;
Expand Down Expand Up @@ -75,17 +75,13 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
};

let options = Options {
head_count: match matches.value_of(options::HEAD_COUNT) {
Some(count) => match count.parse::<usize>() {
head_count: {
let mut headcounts: Values<'_> =
matches.values_of(options::HEAD_COUNT).unwrap_or_default();
match parse_head_count(&mut headcounts) {
Ok(val) => val,
Err(_) => {
return Err(USimpleError::new(
1,
format!("invalid line count: {}", count.quote()),
));
}
},
None => std::usize::MAX,
Err(msg) => return Err(USimpleError::new(1, msg)),
}
},
output: matches.value_of(options::OUTPUT).map(String::from),
random_source: matches.value_of(options::RANDOM_SOURCE).map(String::from),
Expand Down Expand Up @@ -152,6 +148,7 @@ pub fn uu_app<'a>() -> Command<'a> {
.short('n')
.long(options::HEAD_COUNT)
.takes_value(true)
.multiple_occurrences(true)
.value_name("COUNT")
.help("output at most COUNT lines"),
)
Expand Down Expand Up @@ -299,6 +296,17 @@ fn parse_range(input_range: &str) -> Result<(usize, usize), String> {
}
}

fn parse_head_count(headcounts: &mut Values<'_>) -> Result<usize, String> {
let mut result = std::usize::MAX;
for count in headcounts {
match count.parse::<usize>() {
Ok(pv) => result = std::cmp::min(result, pv),
Err(_) => return Err(format!("invalid line count: {}", count.quote())),
}
}
Ok(result)
}

enum WrappedRng {
RngFile(rand_read_adapter::ReadRng<File>),
RngDefault(rand::rngs::ThreadRng),
Expand Down
16 changes: 16 additions & 0 deletions tests/by-util/test_shuf.rs
Original file line number Diff line number Diff line change
Expand Up @@ -196,3 +196,19 @@ fn test_shuf_invalid_input_line_count() {
.fails()
.stderr_contains("invalid line count: 'a'");
}

#[test]
fn test_shuf_multiple_input_line_count() {
let result = new_ucmd!()
.args(&["-i10-200", "-n", "10", "-n", "5"])
.succeeds();

result.no_stderr();

let result_count = result
.stdout_str()
.split('\n')
.filter(|x| !x.is_empty())
.count();
assert_eq!(result_count, 5, "Output should have 5 items");
}

0 comments on commit 746e35c

Please sign in to comment.