Replace deprecated value_of() with get_one()

This commit is contained in:
Daniel Hofstetter 2022-08-16 13:41:45 +02:00
parent b43bbe9e98
commit 9e8daf92dd
60 changed files with 380 additions and 247 deletions

View file

@ -152,7 +152,7 @@ fn gen_completions<T: uucore::Args>(
) )
.get_matches_from(std::iter::once(OsString::from("completion")).chain(args)); .get_matches_from(std::iter::once(OsString::from("completion")).chain(args));
let utility = matches.value_of("utility").unwrap(); let utility = matches.get_one::<String>("utility").unwrap();
let shell = matches.get_one::<Shell>("shell").unwrap().to_owned(); let shell = matches.get_one::<Shell>("shell").unwrap().to_owned();
let mut command = if utility == "coreutils" { let mut command = if utility == "coreutils" {

View file

@ -65,7 +65,7 @@ impl Config {
}; };
let cols = options let cols = options
.value_of(options::WRAP) .get_one::<String>(options::WRAP)
.map(|num| { .map(|num| {
num.parse::<usize>().map_err(|_| { num.parse::<usize>().map_err(|_| {
USimpleError::new( USimpleError::new(

View file

@ -82,7 +82,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
} }
let suffix = if opt_suffix { let suffix = if opt_suffix {
matches.value_of(options::SUFFIX).unwrap() matches.get_one::<String>(options::SUFFIX).unwrap()
} else if !opt_multiple && name_args_count > 1 { } else if !opt_multiple && name_args_count > 1 {
matches matches
.get_many::<String>(options::NAME) .get_many::<String>(options::NAME)

View file

@ -26,12 +26,15 @@ const USAGE: &str = "\
{} [OPTION]... --reference=RFILE FILE..."; {} [OPTION]... --reference=RFILE FILE...";
fn parse_gid_and_uid(matches: &ArgMatches) -> UResult<(Option<u32>, Option<u32>, IfFrom)> { fn parse_gid_and_uid(matches: &ArgMatches) -> UResult<(Option<u32>, Option<u32>, IfFrom)> {
let dest_gid = if let Some(file) = matches.value_of(options::REFERENCE) { let dest_gid = if let Some(file) = matches.get_one::<String>(options::REFERENCE) {
fs::metadata(&file) fs::metadata(&file)
.map(|meta| Some(meta.gid())) .map(|meta| Some(meta.gid()))
.map_err_context(|| format!("failed to get attributes of {}", file.quote()))? .map_err_context(|| format!("failed to get attributes of {}", file.quote()))?
} else { } else {
let group = matches.value_of(options::ARG_GROUP).unwrap_or_default(); let group = matches
.get_one::<String>(options::ARG_GROUP)
.map(|s| s.as_str())
.unwrap_or_default();
if group.is_empty() { if group.is_empty() {
None None
} else { } else {

View file

@ -62,7 +62,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
let verbose = matches.contains_id(options::VERBOSE); let verbose = matches.contains_id(options::VERBOSE);
let preserve_root = matches.contains_id(options::PRESERVE_ROOT); let preserve_root = matches.contains_id(options::PRESERVE_ROOT);
let recursive = matches.contains_id(options::RECURSIVE); let recursive = matches.contains_id(options::RECURSIVE);
let fmode = match matches.value_of(options::REFERENCE) { let fmode = match matches.get_one::<String>(options::REFERENCE) {
Some(fref) => match fs::metadata(fref) { Some(fref) => match fs::metadata(fref) {
Ok(meta) => Some(meta.mode()), Ok(meta) => Some(meta.mode()),
Err(err) => { Err(err) => {
@ -74,7 +74,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
}, },
None => None, None => None,
}; };
let modes = matches.value_of(options::MODE).unwrap(); // should always be Some because required let modes = matches.get_one::<String>(options::MODE).unwrap(); // should always be Some because required
let cmode = if mode_had_minus_prefix { let cmode = if mode_had_minus_prefix {
// clap parsing is finished, now put prefix back // clap parsing is finished, now put prefix back
format!("-{}", modes) format!("-{}", modes)

View file

@ -26,7 +26,7 @@ const USAGE: &str = "\
{} [OPTION]... --reference=RFILE FILE..."; {} [OPTION]... --reference=RFILE FILE...";
fn parse_gid_uid_and_filter(matches: &ArgMatches) -> UResult<(Option<u32>, Option<u32>, IfFrom)> { fn parse_gid_uid_and_filter(matches: &ArgMatches) -> UResult<(Option<u32>, Option<u32>, IfFrom)> {
let filter = if let Some(spec) = matches.value_of(options::FROM) { let filter = if let Some(spec) = matches.get_one::<String>(options::FROM) {
match parse_spec(spec, ':')? { match parse_spec(spec, ':')? {
(Some(uid), None) => IfFrom::User(uid), (Some(uid), None) => IfFrom::User(uid),
(None, Some(gid)) => IfFrom::Group(gid), (None, Some(gid)) => IfFrom::Group(gid),
@ -39,13 +39,13 @@ fn parse_gid_uid_and_filter(matches: &ArgMatches) -> UResult<(Option<u32>, Optio
let dest_uid: Option<u32>; let dest_uid: Option<u32>;
let dest_gid: Option<u32>; let dest_gid: Option<u32>;
if let Some(file) = matches.value_of(options::REFERENCE) { if let Some(file) = matches.get_one::<String>(options::REFERENCE) {
let meta = fs::metadata(&file) let meta = fs::metadata(&file)
.map_err_context(|| format!("failed to get attributes of {}", file.quote()))?; .map_err_context(|| format!("failed to get attributes of {}", file.quote()))?;
dest_gid = Some(meta.gid()); dest_gid = Some(meta.gid());
dest_uid = Some(meta.uid()); dest_uid = Some(meta.uid());
} else { } else {
let (u, g) = parse_spec(matches.value_of(options::ARG_OWNER).unwrap(), ':')?; let (u, g) = parse_spec(matches.get_one::<String>(options::ARG_OWNER).unwrap(), ':')?;
dest_uid = u; dest_uid = u;
dest_gid = g; dest_gid = g;
} }

View file

@ -43,7 +43,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
let default_option: &'static str = "-i"; let default_option: &'static str = "-i";
let user_shell = std::env::var("SHELL"); let user_shell = std::env::var("SHELL");
let newroot: &Path = match matches.value_of(options::NEWROOT) { let newroot: &Path = match matches.get_one::<String>(options::NEWROOT) {
Some(v) => Path::new(v), Some(v) => Path::new(v),
None => return Err(ChrootError::MissingNewRoot.into()), None => return Err(ChrootError::MissingNewRoot.into()),
}; };
@ -165,10 +165,19 @@ pub fn uu_app<'a>() -> Command<'a> {
} }
fn set_context(root: &Path, options: &clap::ArgMatches) -> UResult<()> { fn set_context(root: &Path, options: &clap::ArgMatches) -> UResult<()> {
let userspec_str = options.value_of(options::USERSPEC); let userspec_str = options.get_one::<String>(options::USERSPEC);
let user_str = options.value_of(options::USER).unwrap_or_default(); let user_str = options
let group_str = options.value_of(options::GROUP).unwrap_or_default(); .get_one::<String>(options::USER)
let groups_str = options.value_of(options::GROUPS).unwrap_or_default(); .map(|s| s.as_str())
.unwrap_or_default();
let group_str = options
.get_one::<String>(options::GROUP)
.map(|s| s.as_str())
.unwrap_or_default();
let groups_str = options
.get_one::<String>(options::GROUPS)
.map(|s| s.as_str())
.unwrap_or_default();
let skip_chdir = options.contains_id(options::SKIP_CHDIR); let skip_chdir = options.contains_id(options::SKIP_CHDIR);
let userspec = match userspec_str { let userspec = match userspec_str {
Some(u) => { Some(u) => {

View file

@ -33,7 +33,7 @@ mod options {
fn mkdelim(col: usize, opts: &ArgMatches) -> String { fn mkdelim(col: usize, opts: &ArgMatches) -> String {
let mut s = String::new(); let mut s = String::new();
let delim = match opts.value_of(options::DELIMITER).unwrap() { let delim = match opts.get_one::<String>(options::DELIMITER).unwrap().as_str() {
"" => "\0", "" => "\0",
delim => delim, delim => delim,
}; };
@ -135,8 +135,8 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
let args = args.collect_lossy(); let args = args.collect_lossy();
let matches = uu_app().try_get_matches_from(args)?; let matches = uu_app().try_get_matches_from(args)?;
let filename1 = matches.value_of(options::FILE_1).unwrap(); let filename1 = matches.get_one::<String>(options::FILE_1).unwrap();
let filename2 = matches.value_of(options::FILE_2).unwrap(); let filename2 = matches.get_one::<String>(options::FILE_2).unwrap();
let mut f1 = open_file(filename1).map_err_context(|| filename1.to_string())?; let mut f1 = open_file(filename1).map_err_context(|| filename1.to_string())?;
let mut f2 = open_file(filename2).map_err_context(|| filename2.to_string())?; let mut f2 = open_file(filename2).map_err_context(|| filename2.to_string())?;

View file

@ -722,7 +722,7 @@ impl Options {
// Parse target directory options // Parse target directory options
let no_target_dir = matches.contains_id(options::NO_TARGET_DIRECTORY); let no_target_dir = matches.contains_id(options::NO_TARGET_DIRECTORY);
let target_dir = matches let target_dir = matches
.value_of(options::TARGET_DIRECTORY) .get_one::<String>(options::TARGET_DIRECTORY)
.map(ToString::to_string); .map(ToString::to_string);
// Parse attributes to preserve // Parse attributes to preserve
@ -775,8 +775,8 @@ impl Options {
verbose: matches.contains_id(options::VERBOSE), verbose: matches.contains_id(options::VERBOSE),
strip_trailing_slashes: matches.contains_id(options::STRIP_TRAILING_SLASHES), strip_trailing_slashes: matches.contains_id(options::STRIP_TRAILING_SLASHES),
reflink_mode: { reflink_mode: {
if let Some(reflink) = matches.value_of(options::REFLINK) { if let Some(reflink) = matches.get_one::<String>(options::REFLINK) {
match reflink { match reflink.as_str() {
"always" => ReflinkMode::Always, "always" => ReflinkMode::Always,
"auto" => ReflinkMode::Auto, "auto" => ReflinkMode::Auto,
"never" => ReflinkMode::Never, "never" => ReflinkMode::Never,
@ -802,17 +802,22 @@ impl Options {
} }
} }
}, },
sparse_mode: match matches.value_of(options::SPARSE) { sparse_mode: {
Some("always") => SparseMode::Always, if let Some(val) = matches.get_one::<String>(options::SPARSE) {
Some("auto") => SparseMode::Auto, match val.as_str() {
Some("never") => SparseMode::Never, "always" => SparseMode::Always,
Some(val) => { "auto" => SparseMode::Auto,
"never" => SparseMode::Never,
_ => {
return Err(Error::InvalidArgument(format!( return Err(Error::InvalidArgument(format!(
"invalid argument {} for \'sparse\'", "invalid argument {} for \'sparse\'",
val val
))); )))
}
}
} else {
SparseMode::Auto
} }
None => SparseMode::Auto,
}, },
backup: backup_mode, backup: backup_mode,
backup_suffix, backup_suffix,

View file

@ -61,9 +61,15 @@ impl CsplitOptions {
split_name: crash_if_err!( split_name: crash_if_err!(
1, 1,
SplitName::new( SplitName::new(
matches.value_of(options::PREFIX).map(str::to_string), matches
matches.value_of(options::SUFFIX_FORMAT).map(str::to_string), .get_one::<String>(options::PREFIX)
matches.value_of(options::DIGITS).map(str::to_string) .map(|s| s.to_owned()),
matches
.get_one::<String>(options::SUFFIX_FORMAT)
.map(|s| s.to_owned()),
matches
.get_one::<String>(options::DIGITS)
.map(|s| s.to_owned())
) )
), ),
keep_files, keep_files,
@ -718,7 +724,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
let matches = uu_app().try_get_matches_from(args)?; let matches = uu_app().try_get_matches_from(args)?;
// get the file to split // get the file to split
let file_name = matches.value_of(options::FILE).unwrap(); let file_name = matches.get_one::<String>(options::FILE).unwrap();
// get the patterns to split on // get the patterns to split on
let patterns: Vec<String> = matches let patterns: Vec<String> = matches

View file

@ -406,9 +406,9 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
let complement = matches.contains_id(options::COMPLEMENT); let complement = matches.contains_id(options::COMPLEMENT);
let mode_parse = match ( let mode_parse = match (
matches.value_of(options::BYTES), matches.get_one::<String>(options::BYTES),
matches.value_of(options::CHARACTERS), matches.get_one::<String>(options::CHARACTERS),
matches.value_of(options::FIELDS), matches.get_one::<String>(options::FIELDS),
) { ) {
(Some(byte_ranges), None, None) => list_to_ranges(byte_ranges, complement).map(|ranges| { (Some(byte_ranges), None, None) => list_to_ranges(byte_ranges, complement).map(|ranges| {
Mode::Bytes( Mode::Bytes(
@ -416,7 +416,8 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
Options { Options {
out_delim: Some( out_delim: Some(
matches matches
.value_of(options::OUTPUT_DELIMITER) .get_one::<String>(options::OUTPUT_DELIMITER)
.map(|s| s.as_str())
.unwrap_or_default() .unwrap_or_default()
.to_owned(), .to_owned(),
), ),
@ -430,7 +431,8 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
Options { Options {
out_delim: Some( out_delim: Some(
matches matches
.value_of(options::OUTPUT_DELIMITER) .get_one::<String>(options::OUTPUT_DELIMITER)
.map(|s| s.as_str())
.unwrap_or_default() .unwrap_or_default()
.to_owned(), .to_owned(),
), ),
@ -440,7 +442,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
}), }),
(None, None, Some(field_ranges)) => { (None, None, Some(field_ranges)) => {
list_to_ranges(field_ranges, complement).and_then(|ranges| { list_to_ranges(field_ranges, complement).and_then(|ranges| {
let out_delim = match matches.value_of(options::OUTPUT_DELIMITER) { let out_delim = match matches.get_one::<String>(options::OUTPUT_DELIMITER) {
Some(s) => { Some(s) => {
if s.is_empty() { if s.is_empty() {
Some("\0".to_owned()) Some("\0".to_owned())
@ -454,7 +456,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
let only_delimited = matches.contains_id(options::ONLY_DELIMITED); let only_delimited = matches.contains_id(options::ONLY_DELIMITED);
let zero_terminated = matches.contains_id(options::ZERO_TERMINATED); let zero_terminated = matches.contains_id(options::ZERO_TERMINATED);
match matches.value_of(options::DELIMITER) { match matches.get_one::<String>(options::DELIMITER).map(|s| s.as_str()) {
Some(mut delim) => { Some(mut delim) => {
// GNU's `cut` supports `-d=` to set the delimiter to `=`. // GNU's `cut` supports `-d=` to set the delimiter to `=`.
// Clap parsing is limited in this situation, see: // Clap parsing is limited in this situation, see:

View file

@ -146,7 +146,7 @@ impl<'a> From<&'a str> for Rfc3339Format {
pub fn uumain(args: impl uucore::Args) -> UResult<()> { pub fn uumain(args: impl uucore::Args) -> UResult<()> {
let matches = uu_app().try_get_matches_from(args)?; let matches = uu_app().try_get_matches_from(args)?;
let format = if let Some(form) = matches.value_of(OPT_FORMAT) { let format = if let Some(form) = matches.get_one::<String>(OPT_FORMAT) {
if !form.starts_with('+') { if !form.starts_with('+') {
return Err(USimpleError::new( return Err(USimpleError::new(
1, 1,
@ -162,21 +162,24 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
Format::Iso8601(fmt) Format::Iso8601(fmt)
} else if matches.contains_id(OPT_RFC_EMAIL) { } else if matches.contains_id(OPT_RFC_EMAIL) {
Format::Rfc5322 Format::Rfc5322
} else if let Some(fmt) = matches.value_of(OPT_RFC_3339).map(Into::into) { } else if let Some(fmt) = matches
.get_one::<String>(OPT_RFC_3339)
.map(|s| s.as_str().into())
{
Format::Rfc3339(fmt) Format::Rfc3339(fmt)
} else { } else {
Format::Default Format::Default
}; };
let date_source = if let Some(date) = matches.value_of(OPT_DATE) { let date_source = if let Some(date) = matches.get_one::<String>(OPT_DATE) {
DateSource::Custom(date.into()) DateSource::Custom(date.into())
} else if let Some(file) = matches.value_of(OPT_FILE) { } else if let Some(file) = matches.get_one::<String>(OPT_FILE) {
DateSource::File(file.into()) DateSource::File(file.into())
} else { } else {
DateSource::Now DateSource::Now
}; };
let set_to = match matches.value_of(OPT_SET).map(parse_date) { let set_to = match matches.get_one::<String>(OPT_SET).map(parse_date) {
None => None, None => None,
Some(Err((input, _err))) => { Some(Err((input, _err))) => {
return Err(USimpleError::new( return Err(USimpleError::new(

View file

@ -164,7 +164,7 @@ impl Default for BlockSize {
pub(crate) fn read_block_size(matches: &ArgMatches) -> Result<BlockSize, ParseSizeError> { pub(crate) fn read_block_size(matches: &ArgMatches) -> Result<BlockSize, ParseSizeError> {
if matches.contains_id(OPT_BLOCKSIZE) { if matches.contains_id(OPT_BLOCKSIZE) {
let s = matches.value_of(OPT_BLOCKSIZE).unwrap(); let s = matches.get_one::<String>(OPT_BLOCKSIZE).unwrap();
let bytes = parse_size(s)?; let bytes = parse_size(s)?;
if bytes > 0 { if bytes > 0 {

View file

@ -188,7 +188,10 @@ impl Options {
block_size: read_block_size(matches).map_err(|e| match e { block_size: read_block_size(matches).map_err(|e| match e {
ParseSizeError::InvalidSuffix(s) => OptionsError::InvalidSuffix(s), ParseSizeError::InvalidSuffix(s) => OptionsError::InvalidSuffix(s),
ParseSizeError::SizeTooBig(_) => OptionsError::BlockSizeTooLarge( ParseSizeError::SizeTooBig(_) => OptionsError::BlockSizeTooLarge(
matches.value_of(OPT_BLOCKSIZE).unwrap().to_string(), matches
.get_one::<String>(OPT_BLOCKSIZE)
.unwrap()
.to_string(),
), ),
ParseSizeError::ParseFailure(s) => OptionsError::InvalidBlockSize(s), ParseSizeError::ParseFailure(s) => OptionsError::InvalidBlockSize(s),
})?, })?,

View file

@ -521,7 +521,12 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
let summarize = matches.contains_id(options::SUMMARIZE); let summarize = matches.contains_id(options::SUMMARIZE);
let max_depth = parse_depth(matches.value_of(options::MAX_DEPTH), summarize)?; let max_depth = parse_depth(
matches
.get_one::<String>(options::MAX_DEPTH)
.map(|s| s.as_str()),
summarize,
)?;
let options = Options { let options = Options {
all: matches.contains_id(options::ALL), all: matches.contains_id(options::ALL),
@ -534,7 +539,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
verbose: matches.contains_id(options::VERBOSE), verbose: matches.contains_id(options::VERBOSE),
}; };
let files = match matches.value_of(options::FILE) { let files = match matches.get_one::<String>(options::FILE) {
Some(_) => matches Some(_) => matches
.get_many::<String>(options::FILE) .get_many::<String>(options::FILE)
.unwrap() .unwrap()
@ -549,9 +554,13 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
show_warning!("options --apparent-size and -b are ineffective with --inodes"); show_warning!("options --apparent-size and -b are ineffective with --inodes");
} }
let block_size = read_block_size(matches.value_of(options::BLOCK_SIZE)); let block_size = read_block_size(
matches
.get_one::<String>(options::BLOCK_SIZE)
.map(|s| s.as_str()),
);
let threshold = matches.value_of(options::THRESHOLD).map(|s| { let threshold = matches.get_one::<String>(options::THRESHOLD).map(|s| {
Threshold::from_str(s) Threshold::from_str(s)
.unwrap_or_else(|e| crash!(1, "{}", format_error_message(&e, s, options::THRESHOLD))) .unwrap_or_else(|e| crash!(1, "{}", format_error_message(&e, s, options::THRESHOLD)))
}); });
@ -582,7 +591,8 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
} }
}; };
let time_format_str = parse_time_style(matches.value_of("time-style"))?; let time_format_str =
parse_time_style(matches.get_one::<String>("time-style").map(|s| s.as_str()))?;
let line_separator = if matches.contains_id(options::NULL) { let line_separator = if matches.contains_id(options::NULL) {
"\0" "\0"
@ -630,8 +640,8 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
if matches.is_present(options::TIME) { if matches.is_present(options::TIME) {
let tm = { let tm = {
let secs = { let secs = {
match matches.value_of(options::TIME) { match matches.get_one::<String>(options::TIME) {
Some(s) => match s { Some(s) => match s.as_str() {
"ctime" | "status" => stat.modified, "ctime" | "status" => stat.modified,
"access" | "atime" | "use" => stat.accessed, "access" | "atime" | "use" => stat.accessed,
"birth" | "creation" => stat "birth" | "creation" => stat

View file

@ -177,7 +177,7 @@ fn run_env(args: impl uucore::Args) -> UResult<()> {
let ignore_env = matches.contains_id("ignore-environment"); let ignore_env = matches.contains_id("ignore-environment");
let null = matches.contains_id("null"); let null = matches.contains_id("null");
let running_directory = matches.value_of("chdir"); let running_directory = matches.get_one::<String>("chdir").map(|s| s.as_str());
let files = match matches.get_many::<String>("file") { let files = match matches.get_many::<String>("file") {
Some(v) => v.map(|s| s.as_str()).collect(), Some(v) => v.map(|s| s.as_str()).collect(),
None => Vec::with_capacity(0), None => Vec::with_capacity(0),

View file

@ -108,17 +108,17 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
fmt_opts.xprefix = matches.contains_id(OPT_EXACT_PREFIX); fmt_opts.xprefix = matches.contains_id(OPT_EXACT_PREFIX);
fmt_opts.xanti_prefix = matches.contains_id(OPT_SKIP_PREFIX); fmt_opts.xanti_prefix = matches.contains_id(OPT_SKIP_PREFIX);
if let Some(s) = matches.value_of(OPT_PREFIX).map(String::from) { if let Some(s) = matches.get_one::<String>(OPT_PREFIX).map(String::from) {
fmt_opts.prefix = s; fmt_opts.prefix = s;
fmt_opts.use_prefix = true; fmt_opts.use_prefix = true;
}; };
if let Some(s) = matches.value_of(OPT_SKIP_PREFIX).map(String::from) { if let Some(s) = matches.get_one::<String>(OPT_SKIP_PREFIX).map(String::from) {
fmt_opts.anti_prefix = s; fmt_opts.anti_prefix = s;
fmt_opts.use_anti_prefix = true; fmt_opts.use_anti_prefix = true;
}; };
if let Some(s) = matches.value_of(OPT_WIDTH) { if let Some(s) = matches.get_one::<String>(OPT_WIDTH) {
fmt_opts.width = match s.parse::<usize>() { fmt_opts.width = match s.parse::<usize>() {
Ok(t) => t, Ok(t) => t,
Err(e) => { Err(e) => {
@ -140,7 +140,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
fmt_opts.goal = cmp::min(fmt_opts.width * 94 / 100, fmt_opts.width - 3); fmt_opts.goal = cmp::min(fmt_opts.width * 94 / 100, fmt_opts.width - 3);
}; };
if let Some(s) = matches.value_of(OPT_GOAL) { if let Some(s) = matches.get_one::<String>(OPT_GOAL) {
fmt_opts.goal = match s.parse::<usize>() { fmt_opts.goal = match s.parse::<usize>() {
Ok(t) => t, Ok(t) => t,
Err(e) => { Err(e) => {
@ -157,7 +157,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
} }
}; };
if let Some(s) = matches.value_of(OPT_TAB_WIDTH) { if let Some(s) = matches.get_one::<String>(OPT_TAB_WIDTH) {
fmt_opts.tabwidth = match s.parse::<usize>() { fmt_opts.tabwidth = match s.parse::<usize>() {
Ok(t) => t, Ok(t) => t,
Err(e) => { Err(e) => {

View file

@ -38,7 +38,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
let bytes = matches.contains_id(options::BYTES); let bytes = matches.contains_id(options::BYTES);
let spaces = matches.contains_id(options::SPACES); let spaces = matches.contains_id(options::SPACES);
let poss_width = match matches.value_of(options::WIDTH) { let poss_width = match matches.get_one::<String>(options::WIDTH) {
Some(v) => Some(v.to_owned()), Some(v) => Some(v.to_owned()),
None => obs_width, None => obs_width,
}; };

View file

@ -80,7 +80,7 @@ fn detect_algo(
Box::new(blake3::Hasher::new()) as Box<dyn Digest>, Box::new(blake3::Hasher::new()) as Box<dyn Digest>,
256, 256,
), ),
"sha3sum" => match matches.value_of("bits") { "sha3sum" => match matches.get_one::<String>("bits") {
Some(bits_str) => match (bits_str).parse::<usize>() { Some(bits_str) => match (bits_str).parse::<usize>() {
Ok(224) => ( Ok(224) => (
"SHA3-224", "SHA3-224",
@ -130,7 +130,7 @@ fn detect_algo(
Box::new(Sha3_512::new()) as Box<dyn Digest>, Box::new(Sha3_512::new()) as Box<dyn Digest>,
512, 512,
), ),
"shake128sum" => match matches.value_of("bits") { "shake128sum" => match matches.get_one::<String>("bits") {
Some(bits_str) => match (bits_str).parse::<usize>() { Some(bits_str) => match (bits_str).parse::<usize>() {
Ok(bits) => ( Ok(bits) => (
"SHAKE128", "SHAKE128",
@ -141,7 +141,7 @@ fn detect_algo(
}, },
None => crash!(1, "--bits required for SHAKE-128"), None => crash!(1, "--bits required for SHAKE-128"),
}, },
"shake256sum" => match matches.value_of("bits") { "shake256sum" => match matches.get_one::<String>("bits") {
Some(bits_str) => match (bits_str).parse::<usize>() { Some(bits_str) => match (bits_str).parse::<usize>() {
Ok(bits) => ( Ok(bits) => (
"SHAKE256", "SHAKE256",
@ -187,7 +187,7 @@ fn detect_algo(
set_or_crash("BLAKE3", Box::new(blake3::Hasher::new()), 256); set_or_crash("BLAKE3", Box::new(blake3::Hasher::new()), 256);
} }
if matches.contains_id("sha3") { if matches.contains_id("sha3") {
match matches.value_of("bits") { match matches.get_one::<String>("bits") {
Some(bits_str) => match (bits_str).parse::<usize>() { Some(bits_str) => match (bits_str).parse::<usize>() {
Ok(224) => set_or_crash( Ok(224) => set_or_crash(
"SHA3-224", "SHA3-224",
@ -231,7 +231,7 @@ fn detect_algo(
set_or_crash("SHA3-512", Box::new(Sha3_512::new()), 512); set_or_crash("SHA3-512", Box::new(Sha3_512::new()), 512);
} }
if matches.contains_id("shake128") { if matches.contains_id("shake128") {
match matches.value_of("bits") { match matches.get_one::<String>("bits") {
Some(bits_str) => match (bits_str).parse::<usize>() { Some(bits_str) => match (bits_str).parse::<usize>() {
Ok(bits) => set_or_crash("SHAKE128", Box::new(Shake128::new()), bits), Ok(bits) => set_or_crash("SHAKE128", Box::new(Shake128::new()), bits),
Err(err) => crash!(1, "{}", err), Err(err) => crash!(1, "{}", err),
@ -240,7 +240,7 @@ fn detect_algo(
} }
} }
if matches.contains_id("shake256") { if matches.contains_id("shake256") {
match matches.value_of("bits") { match matches.get_one::<String>("bits") {
Some(bits_str) => match (bits_str).parse::<usize>() { Some(bits_str) => match (bits_str).parse::<usize>() {
Ok(bits) => set_or_crash("SHAKE256", Box::new(Shake256::new()), bits), Ok(bits) => set_or_crash("SHAKE256", Box::new(Shake256::new()), bits),
Err(err) => crash!(1, "{}", err), Err(err) => crash!(1, "{}", err),

View file

@ -130,7 +130,7 @@ impl Default for Mode {
impl Mode { impl Mode {
fn from(matches: &ArgMatches) -> Result<Self, String> { fn from(matches: &ArgMatches) -> Result<Self, String> {
if let Some(v) = matches.value_of(options::BYTES_NAME) { if let Some(v) = matches.get_one::<String>(options::BYTES_NAME) {
let (n, all_but_last) = let (n, all_but_last) =
parse::parse_num(v).map_err(|err| format!("invalid number of bytes: {}", err))?; parse::parse_num(v).map_err(|err| format!("invalid number of bytes: {}", err))?;
if all_but_last { if all_but_last {
@ -138,7 +138,7 @@ impl Mode {
} else { } else {
Ok(Self::FirstBytes(n)) Ok(Self::FirstBytes(n))
} }
} else if let Some(v) = matches.value_of(options::LINES_NAME) { } else if let Some(v) = matches.get_one::<String>(options::LINES_NAME) {
let (n, all_but_last) = let (n, all_but_last) =
parse::parse_num(v).map_err(|err| format!("invalid number of lines: {}", err))?; parse::parse_num(v).map_err(|err| format!("invalid number of lines: {}", err))?;
if all_but_last { if all_but_last {

View file

@ -357,7 +357,7 @@ fn behavior(matches: &ArgMatches) -> UResult<Behavior> {
let considering_dir: bool = MainFunction::Directory == main_function; let considering_dir: bool = MainFunction::Directory == main_function;
let specified_mode: Option<u32> = if matches.contains_id(OPT_MODE) { let specified_mode: Option<u32> = if matches.contains_id(OPT_MODE) {
let x = matches.value_of(OPT_MODE).ok_or(1)?; let x = matches.get_one::<String>(OPT_MODE).ok_or(1)?;
Some(mode::parse(x, considering_dir, get_umask()).map_err(|err| { Some(mode::parse(x, considering_dir, get_umask()).map_err(|err| {
show_error!("Invalid mode string: {}", err); show_error!("Invalid mode string: {}", err);
1 1
@ -367,7 +367,9 @@ fn behavior(matches: &ArgMatches) -> UResult<Behavior> {
}; };
let backup_mode = backup_control::determine_backup_mode(matches)?; let backup_mode = backup_control::determine_backup_mode(matches)?;
let target_dir = matches.value_of(OPT_TARGET_DIRECTORY).map(|d| d.to_owned()); let target_dir = matches
.get_one::<String>(OPT_TARGET_DIRECTORY)
.map(|d| d.to_owned());
let preserve_timestamps = matches.contains_id(OPT_PRESERVE_TIMESTAMPS); let preserve_timestamps = matches.contains_id(OPT_PRESERVE_TIMESTAMPS);
let compare = matches.contains_id(OPT_COMPARE); let compare = matches.contains_id(OPT_COMPARE);
@ -385,15 +387,24 @@ fn behavior(matches: &ArgMatches) -> UResult<Behavior> {
specified_mode, specified_mode,
backup_mode, backup_mode,
suffix: backup_control::determine_backup_suffix(matches), suffix: backup_control::determine_backup_suffix(matches),
owner: matches.value_of(OPT_OWNER).unwrap_or("").to_string(), owner: matches
group: matches.value_of(OPT_GROUP).unwrap_or("").to_string(), .get_one::<String>(OPT_OWNER)
.map(|s| s.as_str())
.unwrap_or("")
.to_string(),
group: matches
.get_one::<String>(OPT_GROUP)
.map(|s| s.as_str())
.unwrap_or("")
.to_string(),
verbose: matches.contains_id(OPT_VERBOSE), verbose: matches.contains_id(OPT_VERBOSE),
preserve_timestamps, preserve_timestamps,
compare, compare,
strip, strip,
strip_program: String::from( strip_program: String::from(
matches matches
.value_of(OPT_STRIP_PROGRAM) .get_one::<String>(OPT_STRIP_PROGRAM)
.map(|s| s.as_str())
.unwrap_or(DEFAULT_STRIP_PROGRAM), .unwrap_or(DEFAULT_STRIP_PROGRAM),
), ),
create_leading: matches.contains_id(OPT_CREATE_LEADING), create_leading: matches.contains_id(OPT_CREATE_LEADING),

View file

@ -604,9 +604,9 @@ impl<'a> State<'a> {
pub fn uumain(args: impl uucore::Args) -> UResult<()> { pub fn uumain(args: impl uucore::Args) -> UResult<()> {
let matches = uu_app().try_get_matches_from(args)?; let matches = uu_app().try_get_matches_from(args)?;
let keys = parse_field_number_option(matches.value_of("j"))?; let keys = parse_field_number_option(matches.get_one::<String>("j").map(|s| s.as_str()))?;
let key1 = parse_field_number_option(matches.value_of("1"))?; let key1 = parse_field_number_option(matches.get_one::<String>("1").map(|s| s.as_str()))?;
let key2 = parse_field_number_option(matches.value_of("2"))?; let key2 = parse_field_number_option(matches.get_one::<String>("2").map(|s| s.as_str()))?;
let mut settings: Settings = Default::default(); let mut settings: Settings = Default::default();
@ -655,7 +655,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
}; };
} }
if let Some(format) = matches.value_of("o") { if let Some(format) = matches.get_one::<String>("o") {
if format == "auto" { if format == "auto" {
settings.autoformat = true; settings.autoformat = true;
} else { } else {
@ -667,7 +667,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
} }
} }
if let Some(empty) = matches.value_of("e") { if let Some(empty) = matches.get_one::<String>("e") {
settings.empty = empty.as_bytes().to_vec(); settings.empty = empty.as_bytes().to_vec();
} }
@ -687,8 +687,8 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
settings.line_ending = LineEnding::Nul; settings.line_ending = LineEnding::Nul;
} }
let file1 = matches.value_of("file1").unwrap(); let file1 = matches.get_one::<String>("file1").unwrap();
let file2 = matches.value_of("file2").unwrap(); let file2 = matches.get_one::<String>("file2").unwrap();
if file1 == "-" && file2 == "-" { if file1 == "-" && file2 == "-" {
return Err(USimpleError::new(1, "both files cannot be standard input")); return Err(USimpleError::new(1, "both files cannot be standard input"));

View file

@ -60,7 +60,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
Mode::Kill => { Mode::Kill => {
let sig = if let Some(signal) = obs_signal { let sig = if let Some(signal) = obs_signal {
signal signal
} else if let Some(signal) = matches.value_of(options::SIGNAL) { } else if let Some(signal) = matches.get_one::<String>(options::SIGNAL) {
parse_signal_value(signal)? parse_signal_value(signal)?
} else { } else {
15_usize //SIGTERM 15_usize //SIGTERM

View file

@ -170,7 +170,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
logical, logical,
relative: matches.contains_id(options::RELATIVE), relative: matches.contains_id(options::RELATIVE),
target_dir: matches target_dir: matches
.value_of(options::TARGET_DIRECTORY) .get_one::<String>(options::TARGET_DIRECTORY)
.map(String::from), .map(String::from),
no_target_dir: matches.contains_id(options::NO_TARGET_DIRECTORY), no_target_dir: matches.contains_id(options::NO_TARGET_DIRECTORY),
no_dereference: matches.contains_id(options::NO_DEREFERENCE), no_dereference: matches.contains_id(options::NO_DEREFERENCE),

View file

@ -374,9 +374,9 @@ impl Config {
#[allow(clippy::cognitive_complexity)] #[allow(clippy::cognitive_complexity)]
pub fn from(options: &clap::ArgMatches) -> UResult<Self> { pub fn from(options: &clap::ArgMatches) -> UResult<Self> {
let context = options.contains_id(options::CONTEXT); let context = options.contains_id(options::CONTEXT);
let (mut format, opt) = if let Some(format_) = options.value_of(options::FORMAT) { let (mut format, opt) = if let Some(format_) = options.get_one::<String>(options::FORMAT) {
( (
match format_ { match format_.as_str() {
"long" | "verbose" => Format::Long, "long" | "verbose" => Format::Long,
"single-column" => Format::OneLine, "single-column" => Format::OneLine,
"columns" | "vertical" => Format::Columns, "columns" | "vertical" => Format::Columns,
@ -447,8 +447,8 @@ impl Config {
Files::Normal Files::Normal
}; };
let sort = if let Some(field) = options.value_of(options::SORT) { let sort = if let Some(field) = options.get_one::<String>(options::SORT) {
match field { match field.as_str() {
"none" => Sort::None, "none" => Sort::None,
"name" => Sort::Name, "name" => Sort::Name,
"time" => Sort::Time, "time" => Sort::Time,
@ -472,8 +472,8 @@ impl Config {
Sort::Name Sort::Name
}; };
let time = if let Some(field) = options.value_of(options::TIME) { let time = if let Some(field) = options.get_one::<String>(options::TIME) {
match field { match field.as_str() {
"ctime" | "status" => Time::Change, "ctime" | "status" => Time::Change,
"access" | "atime" | "use" => Time::Access, "access" | "atime" | "use" => Time::Access,
"birth" | "creation" => Time::Birth, "birth" | "creation" => Time::Birth,
@ -488,25 +488,25 @@ impl Config {
Time::Modification Time::Modification
}; };
let mut needs_color = match options.value_of(options::COLOR) { let mut needs_color = match options.get_one::<String>(options::COLOR) {
None => options.contains_id(options::COLOR), None => options.contains_id(options::COLOR),
Some(val) => match val { Some(val) => match val.as_str() {
"" | "always" | "yes" | "force" => true, "" | "always" | "yes" | "force" => true,
"auto" | "tty" | "if-tty" => atty::is(atty::Stream::Stdout), "auto" | "tty" | "if-tty" => atty::is(atty::Stream::Stdout),
/* "never" | "no" | "none" | */ _ => false, /* "never" | "no" | "none" | */ _ => false,
}, },
}; };
let cmd_line_bs = options.value_of(options::size::BLOCK_SIZE); let cmd_line_bs = options.get_one::<String>(options::size::BLOCK_SIZE);
let opt_si = cmd_line_bs.is_some() let opt_si = cmd_line_bs.is_some()
&& options && options
.value_of(options::size::BLOCK_SIZE) .get_one::<String>(options::size::BLOCK_SIZE)
.unwrap() .unwrap()
.eq("si") .eq("si")
|| options.contains_id(options::size::SI); || options.contains_id(options::size::SI);
let opt_hr = (cmd_line_bs.is_some() let opt_hr = (cmd_line_bs.is_some()
&& options && options
.value_of(options::size::BLOCK_SIZE) .get_one::<String>(options::size::BLOCK_SIZE)
.unwrap() .unwrap()
.eq("human-readable")) .eq("human-readable"))
|| options.contains_id(options::size::HUMAN_READABLE); || options.contains_id(options::size::HUMAN_READABLE);
@ -574,7 +574,7 @@ impl Config {
} }
}; };
let width = match options.value_of(options::WIDTH) { let width = match options.get_one::<String>(options::WIDTH) {
Some(x) => { Some(x) => {
if x.starts_with('0') && x.len() > 1 { if x.starts_with('0') && x.len() > 1 {
// Read number as octal // Read number as octal
@ -617,7 +617,7 @@ impl Config {
}; };
let opt_quoting_style = options let opt_quoting_style = options
.value_of(options::QUOTING_STYLE) .get_one::<String>(options::QUOTING_STYLE)
.map(|cmd_line_qs| cmd_line_qs.to_owned()); .map(|cmd_line_qs| cmd_line_qs.to_owned());
let mut quoting_style = if let Some(style) = opt_quoting_style { let mut quoting_style = if let Some(style) = opt_quoting_style {
@ -670,16 +670,18 @@ impl Config {
} }
}; };
let indicator_style = if let Some(field) = options.value_of(options::INDICATOR_STYLE) { let indicator_style = if let Some(field) =
match field { options.get_one::<String>(options::INDICATOR_STYLE)
{
match field.as_str() {
"none" => IndicatorStyle::None, "none" => IndicatorStyle::None,
"file-type" => IndicatorStyle::FileType, "file-type" => IndicatorStyle::FileType,
"classify" => IndicatorStyle::Classify, "classify" => IndicatorStyle::Classify,
"slash" => IndicatorStyle::Slash, "slash" => IndicatorStyle::Slash,
&_ => IndicatorStyle::None, &_ => IndicatorStyle::None,
} }
} else if let Some(field) = options.value_of(options::indicator_style::CLASSIFY) { } else if let Some(field) = options.get_one::<String>(options::indicator_style::CLASSIFY) {
match field { match field.as_str() {
"never" | "no" | "none" => IndicatorStyle::None, "never" | "no" | "none" => IndicatorStyle::None,
"always" | "yes" | "force" => IndicatorStyle::Classify, "always" | "yes" | "force" => IndicatorStyle::Classify,
"auto" | "tty" | "if-tty" => { "auto" | "tty" | "if-tty" => {
@ -699,7 +701,7 @@ impl Config {
IndicatorStyle::None IndicatorStyle::None
}; };
let time_style = if let Some(field) = options.value_of(options::TIME_STYLE) { let time_style = if let Some(field) = options.get_one::<String>(options::TIME_STYLE) {
//If both FULL_TIME and TIME_STYLE are present //If both FULL_TIME and TIME_STYLE are present
//The one added last is dominant //The one added last is dominant
if options.contains_id(options::FULL_TIME) if options.contains_id(options::FULL_TIME)
@ -709,7 +711,7 @@ impl Config {
TimeStyle::FullIso TimeStyle::FullIso
} else { } else {
//Clap handles the env variable "TIME_STYLE" //Clap handles the env variable "TIME_STYLE"
match field { match field.as_str() {
"full-iso" => TimeStyle::FullIso, "full-iso" => TimeStyle::FullIso,
"long-iso" => TimeStyle::LongIso, "long-iso" => TimeStyle::LongIso,
"iso" => TimeStyle::Iso, "iso" => TimeStyle::Iso,

View file

@ -50,7 +50,7 @@ fn get_mode(matches: &ArgMatches, mode_had_minus_prefix: bool) -> Result<u32, St
// Translate a ~str in octal form to u16, default to 755 // Translate a ~str in octal form to u16, default to 755
// Not tested on Windows // Not tested on Windows
let mut new_mode = DEFAULT_PERM; let mut new_mode = DEFAULT_PERM;
match matches.value_of(options::MODE) { match matches.get_one::<String>(options::MODE) {
Some(m) => { Some(m) => {
for mode in m.split(',') { for mode in m.split(',') {
if mode.contains(digits) { if mode.contains(digits) {

View file

@ -39,7 +39,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
return Err(USimpleError::new(1, "-Z is not implemented")); return Err(USimpleError::new(1, "-Z is not implemented"));
} }
let mode = match matches.value_of(options::MODE) { let mode = match matches.get_one::<String>(options::MODE) {
Some(m) => match usize::from_str_radix(m, 8) { Some(m) => match usize::from_str_radix(m, 8) {
Ok(m) => m, Ok(m) => m,
Err(e) => return Err(USimpleError::new(1, format!("invalid mode: {}", e))), Err(e) => return Err(USimpleError::new(1, format!("invalid mode: {}", e))),

View file

@ -90,12 +90,14 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
let mode = get_mode(&matches).map_err(|e| USimpleError::new(1, e))?; let mode = get_mode(&matches).map_err(|e| USimpleError::new(1, e))?;
let file_name = matches.value_of("name").expect("Missing argument 'NAME'"); let file_name = matches
.get_one::<String>("name")
.expect("Missing argument 'NAME'");
// Only check the first character, to allow mnemonic usage like // Only check the first character, to allow mnemonic usage like
// 'mknod /dev/rst0 character 18 0'. // 'mknod /dev/rst0 character 18 0'.
let ch = matches let ch = matches
.value_of("type") .get_one::<String>("type")
.expect("Missing argument 'TYPE'") .expect("Missing argument 'TYPE'")
.chars() .chars()
.next() .next()
@ -113,7 +115,10 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
Ok(()) Ok(())
} }
} else { } else {
match (matches.value_of("major"), matches.value_of("minor")) { match (
matches.get_one::<String>("major"),
matches.get_one::<String>("minor"),
) {
(None, None) | (_, None) | (None, _) => { (None, None) | (_, None) | (None, _) => {
return Err(UUsageError::new( return Err(UUsageError::new(
1, 1,
@ -188,7 +193,7 @@ pub fn uu_app<'a>() -> Command<'a> {
} }
fn get_mode(matches: &ArgMatches) -> Result<mode_t, String> { fn get_mode(matches: &ArgMatches) -> Result<mode_t, String> {
match matches.value_of("mode") { match matches.get_one::<String>("mode") {
None => Ok(MODE_RW_UGO), None => Ok(MODE_RW_UGO),
Some(str_mode) => uucore::mode::parse_mode(str_mode) Some(str_mode) => uucore::mode::parse_mode(str_mode)
.map_err(|e| format!("invalid mode ({})", e)) .map_err(|e| format!("invalid mode ({})", e))

View file

@ -158,7 +158,7 @@ struct Options {
/// in all other cases. /// in all other cases.
fn is_tmpdir_argument_actually_the_template(matches: &ArgMatches) -> bool { fn is_tmpdir_argument_actually_the_template(matches: &ArgMatches) -> bool {
if !matches.contains_id(ARG_TEMPLATE) { if !matches.contains_id(ARG_TEMPLATE) {
if let Some(tmpdir) = matches.value_of(OPT_TMPDIR) { if let Some(tmpdir) = matches.get_one::<String>(OPT_TMPDIR) {
if !Path::new(tmpdir).is_dir() && tmpdir.contains("XXX") { if !Path::new(tmpdir).is_dir() && tmpdir.contains("XXX") {
return true; return true;
} }
@ -177,13 +177,13 @@ impl Options {
// See https://github.com/clap-rs/clap/pull/1587 // See https://github.com/clap-rs/clap/pull/1587
let (tmpdir, template) = if is_tmpdir_argument_actually_the_template(matches) { let (tmpdir, template) = if is_tmpdir_argument_actually_the_template(matches) {
let tmpdir = Some(env::temp_dir().display().to_string()); let tmpdir = Some(env::temp_dir().display().to_string());
let template = matches.value_of(OPT_TMPDIR).unwrap().to_string(); let template = matches.get_one::<String>(OPT_TMPDIR).unwrap().to_string();
(tmpdir, template) (tmpdir, template)
} else { } else {
// If no template argument is given, `--tmpdir` is implied. // If no template argument is given, `--tmpdir` is implied.
match matches.value_of(ARG_TEMPLATE) { match matches.get_one::<String>(ARG_TEMPLATE) {
None => { None => {
let tmpdir = match matches.value_of(OPT_TMPDIR) { let tmpdir = match matches.get_one::<String>(OPT_TMPDIR) {
None => Some(env::temp_dir().display().to_string()), None => Some(env::temp_dir().display().to_string()),
Some(tmpdir) => Some(tmpdir.to_string()), Some(tmpdir) => Some(tmpdir.to_string()),
}; };
@ -191,7 +191,7 @@ impl Options {
(tmpdir, template.to_string()) (tmpdir, template.to_string())
} }
Some(template) => { Some(template) => {
let tmpdir = matches.value_of(OPT_TMPDIR).map(String::from); let tmpdir = matches.get_one::<String>(OPT_TMPDIR).map(String::from);
(tmpdir, template.to_string()) (tmpdir, template.to_string())
} }
} }
@ -201,7 +201,7 @@ impl Options {
dry_run: matches.contains_id(OPT_DRY_RUN), dry_run: matches.contains_id(OPT_DRY_RUN),
quiet: matches.contains_id(OPT_QUIET), quiet: matches.contains_id(OPT_QUIET),
tmpdir, tmpdir,
suffix: matches.value_of(OPT_SUFFIX).map(String::from), suffix: matches.get_one::<String>(OPT_SUFFIX).map(String::from),
treat_as_template: matches.contains_id(OPT_T), treat_as_template: matches.contains_id(OPT_T),
template, template,
} }

View file

@ -46,7 +46,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
)); ));
} }
let adjustment = match matches.value_of(options::ADJUSTMENT) { let adjustment = match matches.get_one::<String>(options::ADJUSTMENT) {
Some(nstr) => { Some(nstr) => {
if !matches.contains_id(options::COMMAND) { if !matches.contains_id(options::COMMAND) {
return Err(UUsageError::new( return Err(UUsageError::new(

View file

@ -29,15 +29,15 @@ pub fn parse_options(settings: &mut crate::Settings, opts: &clap::ArgMatches) ->
// This vector holds error messages encountered. // This vector holds error messages encountered.
let mut errs: Vec<String> = vec![]; let mut errs: Vec<String> = vec![];
settings.renumber = !opts.contains_id(options::NO_RENUMBER); settings.renumber = !opts.contains_id(options::NO_RENUMBER);
match opts.value_of(options::NUMBER_SEPARATOR) { match opts.get_one::<String>(options::NUMBER_SEPARATOR) {
None => {} None => {}
Some(val) => { Some(val) => {
settings.number_separator = val.to_owned(); settings.number_separator = val.to_owned();
} }
} }
match opts.value_of(options::NUMBER_FORMAT) { match opts.get_one::<String>(options::NUMBER_FORMAT) {
None => {} None => {}
Some(val) => match val { Some(val) => match val.as_str() {
"ln" => { "ln" => {
settings.number_format = crate::NumberFormat::Left; settings.number_format = crate::NumberFormat::Left;
} }
@ -52,7 +52,7 @@ pub fn parse_options(settings: &mut crate::Settings, opts: &clap::ArgMatches) ->
} }
}, },
} }
match opts.value_of(options::BODY_NUMBERING) { match opts.get_one::<String>(options::BODY_NUMBERING) {
None => {} None => {}
Some(val) => { Some(val) => {
let chars: Vec<char> = val.chars().collect(); let chars: Vec<char> = val.chars().collect();
@ -66,7 +66,7 @@ pub fn parse_options(settings: &mut crate::Settings, opts: &clap::ArgMatches) ->
} }
} }
} }
match opts.value_of(options::FOOTER_NUMBERING) { match opts.get_one::<String>(options::FOOTER_NUMBERING) {
None => {} None => {}
Some(val) => { Some(val) => {
let chars: Vec<char> = val.chars().collect(); let chars: Vec<char> = val.chars().collect();
@ -80,7 +80,7 @@ pub fn parse_options(settings: &mut crate::Settings, opts: &clap::ArgMatches) ->
} }
} }
} }
match opts.value_of(options::HEADER_NUMBERING) { match opts.get_one::<String>(options::HEADER_NUMBERING) {
None => {} None => {}
Some(val) => { Some(val) => {
let chars: Vec<char> = val.chars().collect(); let chars: Vec<char> = val.chars().collect();
@ -94,7 +94,7 @@ pub fn parse_options(settings: &mut crate::Settings, opts: &clap::ArgMatches) ->
} }
} }
} }
match opts.value_of(options::LINE_INCREMENT) { match opts.get_one::<String>(options::LINE_INCREMENT) {
None => {} None => {}
Some(val) => { Some(val) => {
let conv: Option<u64> = val.parse().ok(); let conv: Option<u64> = val.parse().ok();
@ -106,7 +106,7 @@ pub fn parse_options(settings: &mut crate::Settings, opts: &clap::ArgMatches) ->
} }
} }
} }
match opts.value_of(options::NUMBER_WIDTH) { match opts.get_one::<String>(options::NUMBER_WIDTH) {
None => {} None => {}
Some(val) => { Some(val) => {
let conv: Option<usize> = val.parse().ok(); let conv: Option<usize> = val.parse().ok();
@ -118,7 +118,7 @@ pub fn parse_options(settings: &mut crate::Settings, opts: &clap::ArgMatches) ->
} }
} }
} }
match opts.value_of(options::STARTING_LINE_NUMBER) { match opts.get_one::<String>(options::STARTING_LINE_NUMBER) {
None => {} None => {}
Some(val) => { Some(val) => {
let conv: Option<u64> = val.parse().ok(); let conv: Option<u64> = val.parse().ok();
@ -130,7 +130,7 @@ pub fn parse_options(settings: &mut crate::Settings, opts: &clap::ArgMatches) ->
} }
} }
} }
match opts.value_of(options::JOIN_BLANK_LINES) { match opts.get_one::<String>(options::JOIN_BLANK_LINES) {
None => {} None => {}
Some(val) => { Some(val) => {
let conv: Option<u64> = val.parse().ok(); let conv: Option<u64> = val.parse().ok();

View file

@ -34,7 +34,7 @@ const USAGE: &str = "{} [OPTIONS]...";
pub fn uumain(args: impl uucore::Args) -> UResult<()> { pub fn uumain(args: impl uucore::Args) -> UResult<()> {
let matches = uu_app().try_get_matches_from(args)?; let matches = uu_app().try_get_matches_from(args)?;
let ignore = match matches.value_of(OPT_IGNORE) { let ignore = match matches.get_one::<String>(OPT_IGNORE) {
Some(numstr) => match numstr.trim().parse() { Some(numstr) => match numstr.trim().parse() {
Ok(num) => num, Ok(num) => num,
Err(e) => { Err(e) => {

View file

@ -119,10 +119,10 @@ fn parse_unit_size_suffix(s: &str) -> Option<usize> {
} }
fn parse_options(args: &ArgMatches) -> Result<NumfmtOptions> { fn parse_options(args: &ArgMatches) -> Result<NumfmtOptions> {
let from = parse_unit(args.value_of(options::FROM).unwrap())?; let from = parse_unit(args.get_one::<String>(options::FROM).unwrap())?;
let to = parse_unit(args.value_of(options::TO).unwrap())?; let to = parse_unit(args.get_one::<String>(options::TO).unwrap())?;
let from_unit = parse_unit_size(args.value_of(options::FROM_UNIT).unwrap())?; let from_unit = parse_unit_size(args.get_one::<String>(options::FROM_UNIT).unwrap())?;
let to_unit = parse_unit_size(args.value_of(options::TO_UNIT).unwrap())?; let to_unit = parse_unit_size(args.get_one::<String>(options::TO_UNIT).unwrap())?;
let transform = TransformOptions { let transform = TransformOptions {
from, from,
@ -131,7 +131,7 @@ fn parse_options(args: &ArgMatches) -> Result<NumfmtOptions> {
to_unit, to_unit,
}; };
let padding = match args.value_of(options::PADDING) { let padding = match args.get_one::<String>(options::PADDING) {
Some(s) => s Some(s) => s
.parse::<isize>() .parse::<isize>()
.map_err(|_| s) .map_err(|_| s)
@ -144,7 +144,7 @@ fn parse_options(args: &ArgMatches) -> Result<NumfmtOptions> {
}?; }?;
let header = if args.value_source(options::HEADER) == Some(ValueSource::CommandLine) { let header = if args.value_source(options::HEADER) == Some(ValueSource::CommandLine) {
let value = args.value_of(options::HEADER).unwrap(); let value = args.get_one::<String>(options::HEADER).unwrap();
value value
.parse::<usize>() .parse::<usize>()
@ -158,7 +158,7 @@ fn parse_options(args: &ArgMatches) -> Result<NumfmtOptions> {
Ok(0) Ok(0)
}?; }?;
let fields = match args.value_of(options::FIELD).unwrap() { let fields = match args.get_one::<String>(options::FIELD).unwrap().as_str() {
"-" => vec![Range { "-" => vec![Range {
low: 1, low: 1,
high: std::usize::MAX, high: std::usize::MAX,
@ -166,7 +166,7 @@ fn parse_options(args: &ArgMatches) -> Result<NumfmtOptions> {
v => Range::from_list(v)?, v => Range::from_list(v)?,
}; };
let format = match args.value_of(options::FORMAT) { let format = match args.get_one::<String>(options::FORMAT) {
Some(s) => s.parse()?, Some(s) => s.parse()?,
None => FormatOptions::default(), None => FormatOptions::default(),
}; };
@ -175,7 +175,9 @@ fn parse_options(args: &ArgMatches) -> Result<NumfmtOptions> {
return Err("grouping cannot be combined with --to".to_string()); return Err("grouping cannot be combined with --to".to_string());
} }
let delimiter = args.value_of(options::DELIMITER).map_or(Ok(None), |arg| { let delimiter = args
.get_one::<String>(options::DELIMITER)
.map_or(Ok(None), |arg| {
if arg.len() == 1 { if arg.len() == 1 {
Ok(Some(arg.to_string())) Ok(Some(arg.to_string()))
} else { } else {
@ -184,7 +186,7 @@ fn parse_options(args: &ArgMatches) -> Result<NumfmtOptions> {
})?; })?;
// unwrap is fine because the argument has a default value // unwrap is fine because the argument has a default value
let round = match args.value_of(options::ROUND).unwrap() { let round = match args.get_one::<String>(options::ROUND).unwrap().as_str() {
"up" => RoundMethod::Up, "up" => RoundMethod::Up,
"down" => RoundMethod::Down, "down" => RoundMethod::Down,
"from-zero" => RoundMethod::FromZero, "from-zero" => RoundMethod::FromZero,
@ -193,7 +195,9 @@ fn parse_options(args: &ArgMatches) -> Result<NumfmtOptions> {
_ => unreachable!("Should be restricted by clap"), _ => unreachable!("Should be restricted by clap"),
}; };
let suffix = args.value_of(options::SUFFIX).map(|s| s.to_owned()); let suffix = args
.get_one::<String>(options::SUFFIX)
.map(|s| s.to_owned());
Ok(NumfmtOptions { Ok(NumfmtOptions {
transform, transform,

View file

@ -124,19 +124,22 @@ struct OdOptions {
impl OdOptions { impl OdOptions {
fn new(matches: &ArgMatches, args: &[String]) -> UResult<Self> { fn new(matches: &ArgMatches, args: &[String]) -> UResult<Self> {
let byte_order = match matches.value_of(options::ENDIAN) { let byte_order = if let Some(s) = matches.get_one::<String>(options::ENDIAN) {
None => ByteOrder::Native, match s.as_str() {
Some("little") => ByteOrder::Little, "little" => ByteOrder::Little,
Some("big") => ByteOrder::Big, "big" => ByteOrder::Big,
Some(s) => { _ => {
return Err(USimpleError::new( return Err(USimpleError::new(
1, 1,
format!("Invalid argument --endian={}", s), format!("Invalid argument --endian={}", s),
)); ))
} }
}
} else {
ByteOrder::Native
}; };
let mut skip_bytes = match matches.value_of(options::SKIP_BYTES) { let mut skip_bytes = match matches.get_one::<String>(options::SKIP_BYTES) {
None => 0, None => 0,
Some(s) => match parse_number_of_bytes(s) { Some(s) => match parse_number_of_bytes(s) {
Ok(n) => n, Ok(n) => n,
@ -164,7 +167,7 @@ impl OdOptions {
let formats = parse_format_flags(args).map_err(|e| USimpleError::new(1, e))?; let formats = parse_format_flags(args).map_err(|e| USimpleError::new(1, e))?;
let mut line_bytes = match matches.value_of(options::WIDTH) { let mut line_bytes = match matches.get_one::<String>(options::WIDTH) {
None => 16, None => 16,
Some(s) => { Some(s) => {
if matches.value_source(options::WIDTH) == Some(ValueSource::CommandLine) { if matches.value_source(options::WIDTH) == Some(ValueSource::CommandLine) {
@ -194,7 +197,7 @@ impl OdOptions {
let output_duplicates = matches.contains_id(options::OUTPUT_DUPLICATES); let output_duplicates = matches.contains_id(options::OUTPUT_DUPLICATES);
let read_bytes = match matches.value_of(options::READ_BYTES) { let read_bytes = match matches.get_one::<String>(options::READ_BYTES) {
None => None, None => None,
Some(s) => match parse_number_of_bytes(s) { Some(s) => match parse_number_of_bytes(s) {
Ok(n) => Some(n), Ok(n) => Some(n),
@ -207,7 +210,7 @@ impl OdOptions {
}, },
}; };
let radix = match matches.value_of(options::ADDRESS_RADIX) { let radix = match matches.get_one::<String>(options::ADDRESS_RADIX) {
None => Radix::Octal, None => Radix::Octal,
Some(s) => { Some(s) => {
let st = s.as_bytes(); let st = s.as_bytes();

View file

@ -57,7 +57,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
let matches = uu_app().try_get_matches_from(args)?; let matches = uu_app().try_get_matches_from(args)?;
let serial = matches.contains_id(options::SERIAL); let serial = matches.contains_id(options::SERIAL);
let delimiters = matches.value_of(options::DELIMITER).unwrap(); let delimiters = matches.get_one::<String>(options::DELIMITER).unwrap();
let files = matches let files = matches
.get_many::<String>(options::FILE) .get_many::<String>(options::FILE)
.unwrap() .unwrap()

View file

@ -470,7 +470,7 @@ fn parse_usize(matches: &ArgMatches, opt: &str) -> Option<Result<usize, PrError>
}) })
}; };
matches matches
.value_of(opt) .get_one::<String>(opt)
.map(|i| (i.to_string(), format!("-{}", opt))) .map(|i| (i.to_string(), format!("-{}", opt)))
.map(from_parse_error_to_pr_error) .map(from_parse_error_to_pr_error)
} }
@ -501,7 +501,8 @@ fn build_options(
}; };
let header = matches let header = matches
.value_of(options::HEADER) .get_one::<String>(options::HEADER)
.map(|s| s.as_str())
.unwrap_or(if is_merge_mode || paths[0] == FILE_STDIN { .unwrap_or(if is_merge_mode || paths[0] == FILE_STDIN {
"" ""
} else { } else {
@ -514,7 +515,7 @@ fn build_options(
parse_usize(matches, options::FIRST_LINE_NUMBER).unwrap_or(Ok(default_first_number))?; parse_usize(matches, options::FIRST_LINE_NUMBER).unwrap_or(Ok(default_first_number))?;
let number = matches let number = matches
.value_of(options::NUMBER_LINES) .get_one::<String>(options::NUMBER_LINES)
.map(|i| { .map(|i| {
let parse_result = i.parse::<usize>(); let parse_result = i.parse::<usize>();
@ -596,7 +597,7 @@ fn build_options(
}; };
let invalid_pages_map = |i: String| { let invalid_pages_map = |i: String| {
let unparsed_value = matches.value_of(options::PAGES).unwrap(); let unparsed_value = matches.get_one::<String>(options::PAGES).unwrap();
i.parse::<usize>().map_err(|_e| { i.parse::<usize>().map_err(|_e| {
PrError::EncounteredErrors(format!( PrError::EncounteredErrors(format!(
"invalid --pages argument {}", "invalid --pages argument {}",
@ -606,7 +607,7 @@ fn build_options(
}; };
let start_page = match matches let start_page = match matches
.value_of(options::PAGES) .get_one::<String>(options::PAGES)
.map(|i| { .map(|i| {
let x: Vec<_> = i.split(':').collect(); let x: Vec<_> = i.split(':').collect();
x[0].to_string() x[0].to_string()
@ -618,7 +619,7 @@ fn build_options(
}; };
let end_page = match matches let end_page = match matches
.value_of(options::PAGES) .get_one::<String>(options::PAGES)
.filter(|i| i.contains(':')) .filter(|i| i.contains(':'))
.map(|i| { .map(|i| {
let x: Vec<_> = i.split(':').collect(); let x: Vec<_> = i.split(':').collect();
@ -668,9 +669,9 @@ fn build_options(
let across_mode = matches.contains_id(options::ACROSS); let across_mode = matches.contains_id(options::ACROSS);
let column_separator = match matches.value_of(options::COLUMN_STRING_SEPARATOR) { let column_separator = match matches.get_one::<String>(options::COLUMN_STRING_SEPARATOR) {
Some(x) => Some(x), Some(x) => Some(x),
None => matches.value_of(options::COLUMN_CHAR_SEPARATOR), None => matches.get_one::<String>(options::COLUMN_CHAR_SEPARATOR),
} }
.map(ToString::to_string) .map(ToString::to_string)
.unwrap_or_else(|| DEFAULT_COLUMN_SEPARATOR.to_string()); .unwrap_or_else(|| DEFAULT_COLUMN_SEPARATOR.to_string());

View file

@ -274,7 +274,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
let matches = uu_app().get_matches_from(args); let matches = uu_app().get_matches_from(args);
let format_string = matches let format_string = matches
.value_of(options::FORMATSTRING) .get_one::<String>(options::FORMATSTRING)
.ok_or_else(|| UUsageError::new(1, "missing operand"))?; .ok_or_else(|| UUsageError::new(1, "missing operand"))?;
let values: Vec<String> = match matches.get_many::<String>(options::ARGUMENT) { let values: Vec<String> = match matches.get_many::<String>(options::ARGUMENT) {
Some(s) => s.map(|s| s.to_string()).collect(), Some(s) => s.map(|s| s.to_string()).collect(),

View file

@ -78,7 +78,7 @@ fn read_word_filter_file(
option: &str, option: &str,
) -> std::io::Result<HashSet<String>> { ) -> std::io::Result<HashSet<String>> {
let filename = matches let filename = matches
.value_of(option) .get_one::<String>(option)
.expect("parsing options failed!") .expect("parsing options failed!")
.to_string(); .to_string();
let file = File::open(filename)?; let file = File::open(filename)?;
@ -95,7 +95,9 @@ fn read_char_filter_file(
matches: &clap::ArgMatches, matches: &clap::ArgMatches,
option: &str, option: &str,
) -> std::io::Result<HashSet<char>> { ) -> std::io::Result<HashSet<char>> {
let filename = matches.value_of(option).expect("parsing options failed!"); let filename = matches
.get_one::<String>(option)
.expect("parsing options failed!");
let mut reader = File::open(filename)?; let mut reader = File::open(filename)?;
let mut buffer = String::new(); let mut buffer = String::new();
reader.read_to_string(&mut buffer)?; reader.read_to_string(&mut buffer)?;
@ -146,7 +148,7 @@ impl WordFilter {
}; };
// Ignore empty string regex from cmd-line-args // Ignore empty string regex from cmd-line-args
let arg_reg: Option<String> = if matches.contains_id(options::WORD_REGEXP) { let arg_reg: Option<String> = if matches.contains_id(options::WORD_REGEXP) {
match matches.value_of(options::WORD_REGEXP) { match matches.get_one::<String>(options::WORD_REGEXP) {
Some(v) => { Some(v) => {
if v.is_empty() { if v.is_empty() {
None None
@ -244,26 +246,26 @@ fn get_config(matches: &clap::ArgMatches) -> UResult<Config> {
config.ignore_case = matches.contains_id(options::IGNORE_CASE); config.ignore_case = matches.contains_id(options::IGNORE_CASE);
if matches.contains_id(options::MACRO_NAME) { if matches.contains_id(options::MACRO_NAME) {
config.macro_name = matches config.macro_name = matches
.value_of(options::MACRO_NAME) .get_one::<String>(options::MACRO_NAME)
.expect(err_msg) .expect(err_msg)
.to_string(); .to_string();
} }
if matches.contains_id(options::FLAG_TRUNCATION) { if matches.contains_id(options::FLAG_TRUNCATION) {
config.trunc_str = matches config.trunc_str = matches
.value_of(options::FLAG_TRUNCATION) .get_one::<String>(options::FLAG_TRUNCATION)
.expect(err_msg) .expect(err_msg)
.to_string(); .to_string();
} }
if matches.contains_id(options::WIDTH) { if matches.contains_id(options::WIDTH) {
config.line_width = matches config.line_width = matches
.value_of(options::WIDTH) .get_one::<String>(options::WIDTH)
.expect(err_msg) .expect(err_msg)
.parse() .parse()
.map_err(PtxError::ParseError)?; .map_err(PtxError::ParseError)?;
} }
if matches.contains_id(options::GAP_SIZE) { if matches.contains_id(options::GAP_SIZE) {
config.gap_size = matches config.gap_size = matches
.value_of(options::GAP_SIZE) .get_one::<String>(options::GAP_SIZE)
.expect(err_msg) .expect(err_msg)
.parse() .parse()
.map_err(PtxError::ParseError)?; .map_err(PtxError::ParseError)?;

View file

@ -179,8 +179,12 @@ fn prepare_relative_options(
can_mode: MissingHandling, can_mode: MissingHandling,
resolve_mode: ResolveMode, resolve_mode: ResolveMode,
) -> UResult<(Option<PathBuf>, Option<PathBuf>)> { ) -> UResult<(Option<PathBuf>, Option<PathBuf>)> {
let relative_to = matches.value_of(OPT_RELATIVE_TO).map(PathBuf::from); let relative_to = matches
let relative_base = matches.value_of(OPT_RELATIVE_BASE).map(PathBuf::from); .get_one::<String>(OPT_RELATIVE_TO)
.map(PathBuf::from);
let relative_base = matches
.get_one::<String>(OPT_RELATIVE_BASE)
.map(PathBuf::from);
let relative_to = canonicalize_relative_option(relative_to, can_mode, resolve_mode)?; let relative_to = canonicalize_relative_option(relative_to, can_mode, resolve_mode)?;
let relative_base = canonicalize_relative_option(relative_base, can_mode, resolve_mode)?; let relative_base = canonicalize_relative_option(relative_base, can_mode, resolve_mode)?;
if let (Some(base), Some(to)) = (relative_base.as_deref(), relative_to.as_deref()) { if let (Some(base), Some(to)) = (relative_base.as_deref(), relative_to.as_deref()) {

View file

@ -31,8 +31,8 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
let matches = uu_app().get_matches_from(args); let matches = uu_app().get_matches_from(args);
let to = Path::new(matches.value_of(options::TO).unwrap()).to_path_buf(); // required let to = Path::new(matches.get_one::<String>(options::TO).unwrap()).to_path_buf(); // required
let from = match matches.value_of(options::FROM) { let from = match matches.get_one::<String>(options::FROM) {
Some(p) => Path::new(p).to_path_buf(), Some(p) => Path::new(p).to_path_buf(),
None => env::current_dir().unwrap(), None => env::current_dir().unwrap(),
}; };
@ -42,7 +42,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
.map_err_context(String::new)?; .map_err_context(String::new)?;
if matches.contains_id(options::DIR) { if matches.contains_id(options::DIR) {
let base = Path::new(&matches.value_of(options::DIR).unwrap()).to_path_buf(); let base = Path::new(&matches.get_one::<String>(options::DIR).unwrap()).to_path_buf();
let absbase = canonicalize(base, MissingHandling::Normal, ResolveMode::Logical) let absbase = canonicalize(base, MissingHandling::Normal, ResolveMode::Logical)
.map_err_context(String::new)?; .map_err_context(String::new)?;
if !absto.as_path().starts_with(absbase.as_path()) if !absto.as_path().starts_with(absbase.as_path())

View file

@ -105,7 +105,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
} else if matches.contains_id(OPT_PROMPT_MORE) { } else if matches.contains_id(OPT_PROMPT_MORE) {
InteractiveMode::Once InteractiveMode::Once
} else if matches.contains_id(OPT_INTERACTIVE) { } else if matches.contains_id(OPT_INTERACTIVE) {
match matches.value_of(OPT_INTERACTIVE).unwrap() { match matches.get_one::<String>(OPT_INTERACTIVE).unwrap().as_str() {
"never" => InteractiveMode::Never, "never" => InteractiveMode::Never,
"once" => InteractiveMode::Once, "once" => InteractiveMode::Once,
"always" => InteractiveMode::Always, "always" => InteractiveMode::Always,

View file

@ -67,10 +67,18 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
.collect::<Vec<_>>(); .collect::<Vec<_>>();
let options = SeqOptions { let options = SeqOptions {
separator: matches.value_of(OPT_SEPARATOR).unwrap_or("\n").to_string(), separator: matches
terminator: matches.value_of(OPT_TERMINATOR).unwrap_or("\n").to_string(), .get_one::<String>(OPT_SEPARATOR)
.map(|s| s.as_str())
.unwrap_or("\n")
.to_string(),
terminator: matches
.get_one::<String>(OPT_TERMINATOR)
.map(|s| s.as_str())
.unwrap_or("\n")
.to_string(),
widths: matches.contains_id(OPT_WIDTHS), widths: matches.contains_id(OPT_WIDTHS),
format: matches.value_of(OPT_FORMAT), format: matches.get_one::<String>(OPT_FORMAT).map(|s| s.as_str()),
}; };
let first = if numbers.len() > 1 { let first = if numbers.len() > 1 {

View file

@ -274,7 +274,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
return Err(UUsageError::new(1, "missing file operand")); return Err(UUsageError::new(1, "missing file operand"));
} }
let iterations = match matches.value_of(options::ITERATIONS) { let iterations = match matches.get_one::<String>(options::ITERATIONS) {
Some(s) => match s.parse::<usize>() { Some(s) => match s.parse::<usize>() {
Ok(u) => u, Ok(u) => u,
Err(_) => { Err(_) => {
@ -298,7 +298,9 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
let force = matches.contains_id(options::FORCE); let force = matches.contains_id(options::FORCE);
let remove = matches.contains_id(options::REMOVE); let remove = matches.contains_id(options::REMOVE);
let size_arg = matches.value_of(options::SIZE).map(|s| s.to_string()); let size_arg = matches
.get_one::<String>(options::SIZE)
.map(|s| s.to_string());
let size = get_size(size_arg); let size = get_size(size_arg);
let exact = matches.contains_id(options::EXACT) && size.is_none(); // if -s is given, ignore -x let exact = matches.contains_id(options::EXACT) && size.is_none(); // if -s is given, ignore -x
let zero = matches.contains_id(options::ZERO); let zero = matches.contains_id(options::ZERO);

View file

@ -62,7 +62,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
let mode = if let Some(args) = matches.get_many::<String>(options::ECHO) { let mode = if let Some(args) = matches.get_many::<String>(options::ECHO) {
Mode::Echo(args.map(String::from).collect()) Mode::Echo(args.map(String::from).collect())
} else if let Some(range) = matches.value_of(options::INPUT_RANGE) { } else if let Some(range) = matches.get_one::<String>(options::INPUT_RANGE) {
match parse_range(range) { match parse_range(range) {
Ok(m) => Mode::InputRange(m), Ok(m) => Mode::InputRange(m),
Err(msg) => { Err(msg) => {
@ -70,7 +70,13 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
} }
} }
} else { } else {
Mode::Default(matches.value_of(options::FILE).unwrap_or("-").to_string()) Mode::Default(
matches
.get_one::<String>(options::FILE)
.map(|s| s.as_str())
.unwrap_or("-")
.to_string(),
)
}; };
let options = Options { let options = Options {
@ -85,8 +91,10 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
Err(msg) => return Err(USimpleError::new(1, msg)), Err(msg) => return Err(USimpleError::new(1, msg)),
} }
}, },
output: matches.value_of(options::OUTPUT).map(String::from), output: matches.get_one::<String>(options::OUTPUT).map(String::from),
random_source: matches.value_of(options::RANDOM_SOURCE).map(String::from), random_source: matches
.get_one::<String>(options::RANDOM_SOURCE)
.map(String::from),
repeat: matches.contains_id(options::REPEAT), repeat: matches.contains_id(options::REPEAT),
sep: if matches.contains_id(options::ZERO_TERMINATED) { sep: if matches.contains_id(options::ZERO_TERMINATED) {
0x00_u8 0x00_u8

View file

@ -1104,27 +1104,45 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
}; };
settings.mode = if matches.contains_id(options::modes::HUMAN_NUMERIC) settings.mode = if matches.contains_id(options::modes::HUMAN_NUMERIC)
|| matches.value_of(options::modes::SORT) == Some("human-numeric") || matches
.get_one::<String>(options::modes::SORT)
.map(|s| s.as_str())
== Some("human-numeric")
{ {
SortMode::HumanNumeric SortMode::HumanNumeric
} else if matches.contains_id(options::modes::MONTH) } else if matches.contains_id(options::modes::MONTH)
|| matches.value_of(options::modes::SORT) == Some("month") || matches
.get_one::<String>(options::modes::SORT)
.map(|s| s.as_str())
== Some("month")
{ {
SortMode::Month SortMode::Month
} else if matches.contains_id(options::modes::GENERAL_NUMERIC) } else if matches.contains_id(options::modes::GENERAL_NUMERIC)
|| matches.value_of(options::modes::SORT) == Some("general-numeric") || matches
.get_one::<String>(options::modes::SORT)
.map(|s| s.as_str())
== Some("general-numeric")
{ {
SortMode::GeneralNumeric SortMode::GeneralNumeric
} else if matches.contains_id(options::modes::NUMERIC) } else if matches.contains_id(options::modes::NUMERIC)
|| matches.value_of(options::modes::SORT) == Some("numeric") || matches
.get_one::<String>(options::modes::SORT)
.map(|s| s.as_str())
== Some("numeric")
{ {
SortMode::Numeric SortMode::Numeric
} else if matches.contains_id(options::modes::VERSION) } else if matches.contains_id(options::modes::VERSION)
|| matches.value_of(options::modes::SORT) == Some("version") || matches
.get_one::<String>(options::modes::SORT)
.map(|s| s.as_str())
== Some("version")
{ {
SortMode::Version SortMode::Version
} else if matches.contains_id(options::modes::RANDOM) } else if matches.contains_id(options::modes::RANDOM)
|| matches.value_of(options::modes::SORT) == Some("random") || matches
.get_one::<String>(options::modes::SORT)
.map(|s| s.as_str())
== Some("random")
{ {
settings.salt = Some(get_rand_string()); settings.salt = Some(get_rand_string());
SortMode::Random SortMode::Random
@ -1137,7 +1155,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
if matches.contains_id(options::PARALLEL) { if matches.contains_id(options::PARALLEL) {
// "0" is default - threads = num of cores // "0" is default - threads = num of cores
settings.threads = matches settings.threads = matches
.value_of(options::PARALLEL) .get_one::<String>(options::PARALLEL)
.map(String::from) .map(String::from)
.unwrap_or_else(|| "0".to_string()); .unwrap_or_else(|| "0".to_string());
env::set_var("RAYON_NUM_THREADS", &settings.threads); env::set_var("RAYON_NUM_THREADS", &settings.threads);
@ -1145,7 +1163,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
settings.buffer_size = settings.buffer_size =
matches matches
.value_of(options::BUF_SIZE) .get_one::<String>(options::BUF_SIZE)
.map_or(Ok(DEFAULT_BUF_SIZE), |s| { .map_or(Ok(DEFAULT_BUF_SIZE), |s| {
GlobalSettings::parse_byte_count(s).map_err(|e| { GlobalSettings::parse_byte_count(s).map_err(|e| {
USimpleError::new(2, format_error_message(&e, s, options::BUF_SIZE)) USimpleError::new(2, format_error_message(&e, s, options::BUF_SIZE))
@ -1154,14 +1172,16 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
let mut tmp_dir = TmpDirWrapper::new( let mut tmp_dir = TmpDirWrapper::new(
matches matches
.value_of(options::TMP_DIR) .get_one::<String>(options::TMP_DIR)
.map(PathBuf::from) .map(PathBuf::from)
.unwrap_or_else(env::temp_dir), .unwrap_or_else(env::temp_dir),
); );
settings.compress_prog = matches.value_of(options::COMPRESS_PROG).map(String::from); settings.compress_prog = matches
.get_one::<String>(options::COMPRESS_PROG)
.map(String::from);
if let Some(n_merge) = matches.value_of(options::BATCH_SIZE) { if let Some(n_merge) = matches.get_one::<String>(options::BATCH_SIZE) {
settings.merge_batch_size = n_merge.parse().map_err(|_| { settings.merge_batch_size = n_merge.parse().map_err(|_| {
UUsageError::new( UUsageError::new(
2, 2,
@ -1176,7 +1196,9 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
settings.check = matches.contains_id(options::check::CHECK); settings.check = matches.contains_id(options::check::CHECK);
if matches.contains_id(options::check::CHECK_SILENT) if matches.contains_id(options::check::CHECK_SILENT)
|| matches!( || matches!(
matches.value_of(options::check::CHECK), matches
.get_one::<String>(options::check::CHECK)
.map(|s| s.as_str()),
Some(options::check::SILENT) | Some(options::check::QUIET) Some(options::check::SILENT) | Some(options::check::QUIET)
) )
{ {
@ -1262,7 +1284,11 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
open(file)?; open(file)?;
} }
let output = Output::new(matches.value_of(options::OUTPUT))?; let output = Output::new(
matches
.get_one::<String>(options::OUTPUT)
.map(|s| s.as_str()),
)?;
settings.init_precomputed(); settings.init_precomputed();

View file

@ -375,22 +375,22 @@ impl Strategy {
) { ) {
(false, false, false, false) => Ok(Self::Lines(1000)), (false, false, false, false) => Ok(Self::Lines(1000)),
(true, false, false, false) => { (true, false, false, false) => {
let s = matches.value_of(OPT_LINES).unwrap(); let s = matches.get_one::<String>(OPT_LINES).unwrap();
let n = parse_size(s).map_err(StrategyError::Lines)?; let n = parse_size(s).map_err(StrategyError::Lines)?;
Ok(Self::Lines(n)) Ok(Self::Lines(n))
} }
(false, true, false, false) => { (false, true, false, false) => {
let s = matches.value_of(OPT_BYTES).unwrap(); let s = matches.get_one::<String>(OPT_BYTES).unwrap();
let n = parse_size(s).map_err(StrategyError::Bytes)?; let n = parse_size(s).map_err(StrategyError::Bytes)?;
Ok(Self::Bytes(n)) Ok(Self::Bytes(n))
} }
(false, false, true, false) => { (false, false, true, false) => {
let s = matches.value_of(OPT_LINE_BYTES).unwrap(); let s = matches.get_one::<String>(OPT_LINE_BYTES).unwrap();
let n = parse_size(s).map_err(StrategyError::Bytes)?; let n = parse_size(s).map_err(StrategyError::Bytes)?;
Ok(Self::LineBytes(n)) Ok(Self::LineBytes(n))
} }
(false, false, false, true) => { (false, false, false, true) => {
let s = matches.value_of(OPT_NUMBER).unwrap(); let s = matches.get_one::<String>(OPT_NUMBER).unwrap();
let number_type = NumberType::from(s).map_err(StrategyError::NumberType)?; let number_type = NumberType::from(s).map_err(StrategyError::NumberType)?;
Ok(Self::Number(number_type)) Ok(Self::Number(number_type))
} }
@ -489,13 +489,16 @@ impl fmt::Display for SettingsError {
impl Settings { impl Settings {
/// Parse a strategy from the command-line arguments. /// Parse a strategy from the command-line arguments.
fn from(matches: &ArgMatches) -> Result<Self, SettingsError> { fn from(matches: &ArgMatches) -> Result<Self, SettingsError> {
let additional_suffix = matches.value_of(OPT_ADDITIONAL_SUFFIX).unwrap().to_string(); let additional_suffix = matches
.get_one::<String>(OPT_ADDITIONAL_SUFFIX)
.unwrap()
.to_string();
if additional_suffix.contains('/') { if additional_suffix.contains('/') {
return Err(SettingsError::SuffixContainsSeparator(additional_suffix)); return Err(SettingsError::SuffixContainsSeparator(additional_suffix));
} }
let strategy = Strategy::from(matches).map_err(SettingsError::Strategy)?; let strategy = Strategy::from(matches).map_err(SettingsError::Strategy)?;
let suffix_type = suffix_type_from(matches); let suffix_type = suffix_type_from(matches);
let suffix_length_str = matches.value_of(OPT_SUFFIX_LENGTH).unwrap(); let suffix_length_str = matches.get_one::<String>(OPT_SUFFIX_LENGTH).unwrap();
let suffix_length: usize = suffix_length_str let suffix_length: usize = suffix_length_str
.parse() .parse()
.map_err(|_| SettingsError::SuffixNotParsable(suffix_length_str.to_string()))?; .map_err(|_| SettingsError::SuffixNotParsable(suffix_length_str.to_string()))?;
@ -517,9 +520,9 @@ impl Settings {
additional_suffix, additional_suffix,
verbose: matches.value_source("verbose") == Some(ValueSource::CommandLine), verbose: matches.value_source("verbose") == Some(ValueSource::CommandLine),
strategy, strategy,
input: matches.value_of(ARG_INPUT).unwrap().to_owned(), input: matches.get_one::<String>(ARG_INPUT).unwrap().to_owned(),
prefix: matches.value_of(ARG_PREFIX).unwrap().to_owned(), prefix: matches.get_one::<String>(ARG_PREFIX).unwrap().to_owned(),
filter: matches.value_of(OPT_FILTER).map(|s| s.to_owned()), filter: matches.get_one::<String>(OPT_FILTER).map(|s| s.to_owned()),
elide_empty_files: matches.contains_id(OPT_ELIDE_EMPTY_FILES), elide_empty_files: matches.contains_id(OPT_ELIDE_EMPTY_FILES),
}; };
#[cfg(windows)] #[cfg(windows)]

View file

@ -512,10 +512,13 @@ impl Stater {
.unwrap_or_default(); .unwrap_or_default();
let format_str = if matches.contains_id(options::PRINTF) { let format_str = if matches.contains_id(options::PRINTF) {
matches matches
.value_of(options::PRINTF) .get_one::<String>(options::PRINTF)
.expect("Invalid format string") .expect("Invalid format string")
} else { } else {
matches.value_of(options::FORMAT).unwrap_or("") matches
.get_one::<String>(options::FORMAT)
.map(|s| s.as_str())
.unwrap_or("")
}; };
let use_printf = matches.contains_id(options::PRINTF); let use_printf = matches.contains_id(options::PRINTF);

View file

@ -105,8 +105,8 @@ fn preload_strings() -> (&'static str, &'static str) {
} }
fn check_option(matches: &ArgMatches, name: &str) -> Result<BufferType, ProgramOptionsError> { fn check_option(matches: &ArgMatches, name: &str) -> Result<BufferType, ProgramOptionsError> {
match matches.value_of(name) { match matches.get_one::<String>(name) {
Some(value) => match value { Some(value) => match value.as_str() {
"L" => { "L" => {
if name == options::INPUT { if name == options::INPUT {
Err(ProgramOptionsError( Err(ProgramOptionsError(

View file

@ -102,7 +102,7 @@ impl<'a> Options<'a> {
Ok(Self { Ok(Self {
all: matches.is_present(options::ALL), all: matches.is_present(options::ALL),
save: matches.is_present(options::SAVE), save: matches.is_present(options::SAVE),
file: match matches.value_of(options::FILE) { file: match matches.get_one::<String>(options::FILE) {
Some(_f) => todo!(), Some(_f) => todo!(),
None => stdout().as_raw_fd(), None => stdout().as_raw_fd(),
}, },

View file

@ -42,7 +42,10 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
let before = matches.contains_id(options::BEFORE); let before = matches.contains_id(options::BEFORE);
let regex = matches.contains_id(options::REGEX); let regex = matches.contains_id(options::REGEX);
let raw_separator = matches.value_of(options::SEPARATOR).unwrap_or("\n"); let raw_separator = matches
.get_one::<String>(options::SEPARATOR)
.map(|s| s.as_str())
.unwrap_or("\n");
let separator = if raw_separator.is_empty() { let separator = if raw_separator.is_empty() {
"\0" "\0"
} else { } else {

View file

@ -63,7 +63,7 @@ pub enum FilterMode {
impl FilterMode { impl FilterMode {
fn from(matches: &ArgMatches) -> UResult<Self> { fn from(matches: &ArgMatches) -> UResult<Self> {
let zero_term = matches.contains_id(options::ZERO_TERM); let zero_term = matches.contains_id(options::ZERO_TERM);
let mode = if let Some(arg) = matches.value_of(options::BYTES) { let mode = if let Some(arg) = matches.get_one::<String>(options::BYTES) {
match parse_num(arg) { match parse_num(arg) {
Ok(signum) => Self::Bytes(signum), Ok(signum) => Self::Bytes(signum),
Err(e) => { Err(e) => {
@ -73,7 +73,7 @@ impl FilterMode {
)) ))
} }
} }
} else if let Some(arg) = matches.value_of(options::LINES) { } else if let Some(arg) = matches.get_one::<String>(options::LINES) {
match parse_num(arg) { match parse_num(arg) {
Ok(signum) => { Ok(signum) => {
let delimiter = if zero_term { 0 } else { b'\n' }; let delimiter = if zero_term { 0 } else { b'\n' };
@ -138,7 +138,8 @@ impl Settings {
Some(FollowMode::Name) Some(FollowMode::Name)
} else if matches.value_source(options::FOLLOW) != Some(ValueSource::CommandLine) { } else if matches.value_source(options::FOLLOW) != Some(ValueSource::CommandLine) {
None None
} else if matches.value_of(options::FOLLOW) == Some("name") { } else if matches.get_one::<String>(options::FOLLOW) == Some(String::from("name")).as_ref()
{
Some(FollowMode::Name) Some(FollowMode::Name)
} else { } else {
Some(FollowMode::Descriptor) Some(FollowMode::Descriptor)
@ -151,7 +152,7 @@ impl Settings {
show_warning!("--retry ignored; --retry is useful only when following"); show_warning!("--retry ignored; --retry is useful only when following");
} }
if let Some(s) = matches.value_of(options::SLEEP_INT) { if let Some(s) = matches.get_one::<String>(options::SLEEP_INT) {
settings.sleep_sec = match s.parse::<f32>() { settings.sleep_sec = match s.parse::<f32>() {
Ok(s) => Duration::from_secs_f32(s), Ok(s) => Duration::from_secs_f32(s),
Err(_) => { Err(_) => {
@ -165,7 +166,7 @@ impl Settings {
settings.use_polling = matches.contains_id(options::USE_POLLING); settings.use_polling = matches.contains_id(options::USE_POLLING);
if let Some(s) = matches.value_of(options::MAX_UNCHANGED_STATS) { if let Some(s) = matches.get_one::<String>(options::MAX_UNCHANGED_STATS) {
settings.max_unchanged_stats = match s.parse::<u32>() { settings.max_unchanged_stats = match s.parse::<u32>() {
Ok(s) => s, Ok(s) => s,
Err(_) => { Err(_) => {
@ -180,7 +181,7 @@ impl Settings {
} }
} }
if let Some(pid_str) = matches.value_of(options::PID) { if let Some(pid_str) = matches.get_one::<String>(options::PID) {
match pid_str.parse() { match pid_str.parse() {
Ok(pid) => { Ok(pid) => {
// NOTE: on unix platform::Pid is i32, on windows platform::Pid is u32 // NOTE: on unix platform::Pid is i32, on windows platform::Pid is u32

View file

@ -64,8 +64,8 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
if matches.contains_id(options::IGNORE_PIPE_ERRORS) { if matches.contains_id(options::IGNORE_PIPE_ERRORS) {
Some(OutputErrorMode::WarnNoPipe) Some(OutputErrorMode::WarnNoPipe)
} else if matches.contains_id(options::OUTPUT_ERROR) { } else if matches.contains_id(options::OUTPUT_ERROR) {
if let Some(v) = matches.value_of(options::OUTPUT_ERROR) { if let Some(v) = matches.get_one::<String>(options::OUTPUT_ERROR) {
match v { match v.as_str() {
"warn" => Some(OutputErrorMode::Warn), "warn" => Some(OutputErrorMode::Warn),
"warn-nopipe" => Some(OutputErrorMode::WarnNoPipe), "warn-nopipe" => Some(OutputErrorMode::WarnNoPipe),
"exit" => Some(OutputErrorMode::Exit), "exit" => Some(OutputErrorMode::Exit),

View file

@ -52,7 +52,7 @@ struct Config {
impl Config { impl Config {
fn from(options: &clap::ArgMatches) -> UResult<Self> { fn from(options: &clap::ArgMatches) -> UResult<Self> {
let signal = match options.value_of(options::SIGNAL) { let signal = match options.get_one::<String>(options::SIGNAL) {
Some(signal_) => { Some(signal_) => {
let signal_result = signal_by_name_or_value(signal_); let signal_result = signal_by_name_or_value(signal_);
match signal_result { match signal_result {
@ -68,7 +68,7 @@ impl Config {
_ => uucore::signals::signal_by_name_or_value("TERM").unwrap(), _ => uucore::signals::signal_by_name_or_value("TERM").unwrap(),
}; };
let kill_after = match options.value_of(options::KILL_AFTER) { let kill_after = match options.get_one::<String>(options::KILL_AFTER) {
None => None, None => None,
Some(kill_after) => match uucore::parse_time::from_str(kill_after) { Some(kill_after) => match uucore::parse_time::from_str(kill_after) {
Ok(k) => Some(k), Ok(k) => Some(k),
@ -76,8 +76,9 @@ impl Config {
}, },
}; };
let duration = let duration = match uucore::parse_time::from_str(
match uucore::parse_time::from_str(options.value_of(options::DURATION).unwrap()) { options.get_one::<String>(options::DURATION).unwrap(),
) {
Ok(duration) => duration, Ok(duration) => duration,
Err(err) => return Err(UUsageError::new(ExitStatus::TimeoutFailed.into(), err)), Err(err) => return Err(UUsageError::new(ExitStatus::TimeoutFailed.into(), err)),
}; };

View file

@ -85,9 +85,9 @@ Try 'touch --help' for more information."##,
!matches.contains_id(options::NO_DEREF), !matches.contains_id(options::NO_DEREF),
)? )?
} else { } else {
let timestamp = if let Some(date) = matches.value_of(options::sources::DATE) { let timestamp = if let Some(date) = matches.get_one::<String>(options::sources::DATE) {
parse_date(date)? parse_date(date)?
} else if let Some(current) = matches.value_of(options::sources::CURRENT) { } else if let Some(current) = matches.get_one::<String>(options::sources::CURRENT) {
parse_timestamp(current)? parse_timestamp(current)?
} else { } else {
local_dt_to_filetime(time::OffsetDateTime::now_local().unwrap()) local_dt_to_filetime(time::OffsetDateTime::now_local().unwrap())
@ -143,7 +143,10 @@ Try 'touch --help' for more information."##,
|| matches.contains_id(options::TIME) || matches.contains_id(options::TIME)
{ {
let st = stat(path, !matches.contains_id(options::NO_DEREF))?; let st = stat(path, !matches.contains_id(options::NO_DEREF))?;
let time = matches.value_of(options::TIME).unwrap_or(""); let time = matches
.get_one::<String>(options::TIME)
.map(|s| s.as_str())
.unwrap_or("");
if !(matches.contains_id(options::ACCESS) if !(matches.contains_id(options::ACCESS)
|| time.contains(&"access".to_owned()) || time.contains(&"access".to_owned())

View file

@ -131,8 +131,10 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
} else { } else {
let io_blocks = matches.contains_id(options::IO_BLOCKS); let io_blocks = matches.contains_id(options::IO_BLOCKS);
let no_create = matches.contains_id(options::NO_CREATE); let no_create = matches.contains_id(options::NO_CREATE);
let reference = matches.value_of(options::REFERENCE).map(String::from); let reference = matches
let size = matches.value_of(options::SIZE).map(String::from); .get_one::<String>(options::REFERENCE)
.map(String::from);
let size = matches.get_one::<String>(options::SIZE).map(String::from);
truncate(no_create, io_blocks, reference, size, &files) truncate(no_create, io_blocks, reference, size, &files)
} }
} }

View file

@ -30,7 +30,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
let matches = uu_app().try_get_matches_from(args)?; let matches = uu_app().try_get_matches_from(args)?;
let input = matches let input = matches
.value_of(options::FILE) .get_one::<String>(options::FILE)
.expect("Value is required by clap"); .expect("Value is required by clap");
let mut stdin_buf; let mut stdin_buf;

View file

@ -113,7 +113,7 @@ impl Options {
&& !matches.contains_id(options::FIRST_ONLY); && !matches.contains_id(options::FIRST_ONLY);
let uflag = !matches.contains_id(options::NO_UTF8); let uflag = !matches.contains_id(options::NO_UTF8);
let files = match matches.value_of(options::FILE) { let files = match matches.get_one::<String>(options::FILE) {
Some(v) => vec![v.to_string()], Some(v) => vec![v.to_string()],
None => vec!["-".to_owned()], None => vec!["-".to_owned()],
}; };

View file

@ -229,7 +229,7 @@ fn get_line_string(io_line: io::Result<Vec<u8>>) -> UResult<String> {
} }
fn opt_parsed<T: FromStr>(opt_name: &str, matches: &ArgMatches) -> UResult<Option<T>> { fn opt_parsed<T: FromStr>(opt_name: &str, matches: &ArgMatches) -> UResult<Option<T>> {
Ok(match matches.value_of(opt_name) { Ok(match matches.get_one::<String>(opt_name) {
Some(arg_str) => Some(arg_str.parse().map_err(|_| { Some(arg_str) => Some(arg_str.parse().map_err(|_| {
USimpleError::new( USimpleError::new(
1, 1,
@ -408,8 +408,8 @@ pub fn uu_app<'a>() -> Command<'a> {
fn get_delimiter(matches: &ArgMatches) -> Delimiters { fn get_delimiter(matches: &ArgMatches) -> Delimiters {
let value = matches let value = matches
.value_of(options::ALL_REPEATED) .get_one::<String>(options::ALL_REPEATED)
.or_else(|| matches.value_of(options::GROUP)); .or_else(|| matches.get_one::<String>(options::GROUP));
if let Some(delimiter_arg) = value { if let Some(delimiter_arg) = value {
Delimiters::from_str(delimiter_arg).unwrap() // All possible values for ALL_REPEATED are Delimiters (of type `&str`) Delimiters::from_str(delimiter_arg).unwrap() // All possible values for ALL_REPEATED are Delimiters (of type `&str`)
} else if matches.contains_id(options::GROUP) { } else if matches.contains_id(options::GROUP) {

View file

@ -55,7 +55,7 @@ impl Settings {
show_control: false, show_control: false,
}; };
let files0_from_stdin_mode = match matches.value_of(options::FILES0_FROM) { let files0_from_stdin_mode = match matches.get_one::<String>(options::FILES0_FROM) {
Some(files_0_from) => files_0_from == STDIN_REPR, Some(files_0_from) => files_0_from == STDIN_REPR,
None => false, None => false,
}; };
@ -274,7 +274,7 @@ fn inputs(matches: &ArgMatches) -> UResult<Vec<Input>> {
Ok(os_values.map(|s| Input::from(s.as_os_str())).collect()) Ok(os_values.map(|s| Input::from(s.as_os_str())).collect())
} }
None => match matches.value_of(options::FILES0_FROM) { None => match matches.get_one::<String>(options::FILES0_FROM) {
Some(files_0_from) => create_paths_from_files0(files_0_from), Some(files_0_from) => create_paths_from_files0(files_0_from),
None => Ok(vec![Input::Stdin(StdinKind::Implicit)]), None => Ok(vec![Input::Stdin(StdinKind::Implicit)]),
}, },

View file

@ -245,7 +245,7 @@ pub mod arguments {
/// This function directly takes [`clap::ArgMatches`] as argument and looks for /// This function directly takes [`clap::ArgMatches`] as argument and looks for
/// the '-S' and '--suffix' arguments itself. /// the '-S' and '--suffix' arguments itself.
pub fn determine_backup_suffix(matches: &ArgMatches) -> String { pub fn determine_backup_suffix(matches: &ArgMatches) -> String {
let supplied_suffix = matches.value_of(arguments::OPT_SUFFIX); let supplied_suffix = matches.get_one::<String>(arguments::OPT_SUFFIX);
if let Some(suffix) = supplied_suffix { if let Some(suffix) = supplied_suffix {
String::from(suffix) String::from(suffix)
} else { } else {
@ -337,7 +337,7 @@ pub fn determine_backup_mode(matches: &ArgMatches) -> UResult<BackupMode> {
// is used but method is not specified, then the value of the // is used but method is not specified, then the value of the
// VERSION_CONTROL environment variable is used. And if VERSION_CONTROL // VERSION_CONTROL environment variable is used. And if VERSION_CONTROL
// is not set, the default backup type is 'existing'. // is not set, the default backup type is 'existing'.
if let Some(method) = matches.value_of(arguments::OPT_BACKUP) { if let Some(method) = matches.get_one::<String>(arguments::OPT_BACKUP) {
// Second argument is for the error string that is returned. // Second argument is for the error string that is returned.
match_method(method, "backup type") match_method(method, "backup type")
} else if let Ok(method) = env::var("VERSION_CONTROL") { } else if let Ok(method) = env::var("VERSION_CONTROL") {