Moved factor to use clap

Issue: https://github.com/uutils/coreutils/issues/2121
This commit is contained in:
Gilad Naaman 2021-05-28 18:28:00 +03:00
parent 222bd81190
commit 6a9ffee548
4 changed files with 34 additions and 16 deletions

1
Cargo.lock generated
View file

@ -2054,6 +2054,7 @@ dependencies = [
name = "uu_factor"
version = "0.0.6"
dependencies = [
"clap",
"coz",
"num-traits",
"paste",

View file

@ -21,6 +21,7 @@ rand = { version = "0.7", features = ["small_rng"] }
smallvec = { version = "0.6.14, < 1.0" }
uucore = { version = ">=0.0.8", package = "uucore", path = "../../uucore" }
uucore_procs = { version = ">=0.0.5", package = "uucore_procs", path = "../../uucore_procs" }
clap = "2.33"
[dev-dependencies]
paste = "0.1.18"

View file

@ -13,18 +13,21 @@ use std::error::Error;
use std::io::{self, stdin, stdout, BufRead, Write};
mod factor;
use clap::{App, Arg};
pub use factor::*;
use uucore::InvalidEncodingHandling;
mod miller_rabin;
pub mod numeric;
mod rho;
pub mod table;
static SYNTAX: &str = "[OPTION] [NUMBER]...";
static SUMMARY: &str = "Print the prime factors of the given number(s).
If none are specified, read from standard input.";
static LONG_HELP: &str = "";
static VERSION: &str = env!("CARGO_PKG_VERSION");
static SUMMARY: &str = "Print the prime factors of the given NUMBER(s).
If none are specified, read from standard input.";
mod options {
pub static NUMBER: &str = "NUMBER";
}
fn print_factors_str(num_str: &str, w: &mut impl io::Write) -> Result<(), Box<dyn Error>> {
num_str
@ -34,14 +37,21 @@ fn print_factors_str(num_str: &str, w: &mut impl io::Write) -> Result<(), Box<dy
}
pub fn uumain(args: impl uucore::Args) -> i32 {
let matches = app!(SYNTAX, SUMMARY, LONG_HELP).parse(
args.collect_str(InvalidEncodingHandling::Ignore)
.accept_any(),
);
let matches = App::new(executable!())
.version(VERSION)
.about(SUMMARY)
.arg(Arg::with_name(options::NUMBER).multiple(true))
.get_matches_from(args);
let stdout = stdout();
let mut w = io::BufWriter::new(stdout.lock());
if matches.free.is_empty() {
if let Some(values) = matches.values_of(options::NUMBER) {
for number in values {
if let Err(e) = print_factors_str(number, &mut w) {
show_warning!("{}: {}", number, e);
}
}
} else {
let stdin = stdin();
for line in stdin.lock().lines() {
@ -51,12 +61,6 @@ pub fn uumain(args: impl uucore::Args) -> i32 {
}
}
}
} else {
for number in &matches.free {
if let Err(e) = print_factors_str(number, &mut w) {
show_warning!("{}: {}", number, e);
}
}
}
if let Err(e) = w.flush() {

View file

@ -39,6 +39,18 @@ fn test_first_100000_integers() {
assert_eq!(hash_check, "4ed2d8403934fa1c76fe4b84c5d4b8850299c359");
}
#[test]
fn test_cli_args() {
// Make sure that factor works with CLI arguments as well.
new_ucmd!().args(&["3"]).succeeds().stdout_contains("3: 3");
new_ucmd!()
.args(&["3", "6"])
.succeeds()
.stdout_contains("3: 3")
.stdout_contains("6: 2 3");
}
#[test]
fn test_random() {
use conv::prelude::*;