From 4122828932b4ebddcbdf91e035d900abca916cc3 Mon Sep 17 00:00:00 2001 From: Stephen Fox Date: Sun, 19 Jan 2025 10:11:36 -0500 Subject: [PATCH] edition: Upgrade to Rust 2021 edition This commit applies the minimum required changes to support Rust 2021 Edition. I limited my changes to issues that "cargo test" and "cargo run" complained about. I also tried to limit formatting changes where possible. --- Cargo.toml | 2 +- src/action.rs | 11 ++-- src/help.rs | 12 ++-- src/parser.rs | 138 +++++++++++++++++++++++++------------------ src/print.rs | 4 +- src/test_bool.rs | 6 +- src/test_const.rs | 7 +-- src/test_enum.rs | 4 +- src/test_env.rs | 5 +- src/test_float.rs | 6 +- src/test_help.rs | 4 +- src/test_int.rs | 4 +- src/test_many.rs | 6 +- src/test_optional.rs | 4 +- src/test_parser.rs | 12 ++-- src/test_path.rs | 6 +- src/test_pos.rs | 6 +- src/test_str.rs | 4 +- src/test_usage.rs | 4 +- 19 files changed, 131 insertions(+), 114 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index dfaaf50..0428363 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -9,4 +9,4 @@ categories = ["command-line-interface"] homepage = "http://github.com/tailhook/rust-argparse" version = "0.2.2" authors = ["Paul Colomiets "] - +edition = "2021" diff --git a/src/action.rs b/src/action.rs index c3a0aff..44c3789 100644 --- a/src/action.rs +++ b/src/action.rs @@ -8,16 +8,15 @@ pub enum ParseResult { Error(String), } - pub enum Action<'a> { - Flag(Box), - Single(Box), - Push(Box), - Many(Box), + Flag(Box), + Single(Box), + Push(Box), + Many(Box), } pub trait TypedAction { - fn bind<'x>(&self, Rc>) -> Action<'x>; + fn bind<'x>(&self, _: Rc>) -> Action<'x>; } pub trait IFlagAction { diff --git a/src/help.rs b/src/help.rs index 59ca3f9..cd70ab9 100644 --- a/src/help.rs +++ b/src/help.rs @@ -61,7 +61,7 @@ impl<'a> Iterator for WordsIter<'a> { } } -pub fn wrap_text(buf: &mut Write, data: &str, width: usize, indent: usize) +pub fn wrap_text(buf: &mut dyn Write, data: &str, width: usize, indent: usize) -> IoResult<()> { let mut witer = WordsIter::new(data); @@ -71,22 +71,22 @@ pub fn wrap_text(buf: &mut Write, data: &str, width: usize, indent: usize) return Ok(()); } Some(word) => { - try!(buf.write_all(word.as_bytes())); + buf.write_all(word.as_bytes())?; off += word.len(); } } for word in witer { if off + word.len() + 1 > width { - try!(buf.write_all(b"\n")); + buf.write_all(b"\n")?; for _ in 0..indent { - try!(buf.write_all(b" ")); + buf.write_all(b" ")?; } off = indent; } else { - try!(buf.write_all(b" ")); + buf.write_all(b" ")?; off += 1; } - try!(buf.write_all(word.as_bytes())); + buf.write_all(word.as_bytes())?; off += word.len(); } return Ok(()); diff --git a/src/parser.rs b/src/parser.rs index 10edc14..01f4397 100644 --- a/src/parser.rs +++ b/src/parser.rs @@ -25,7 +25,7 @@ use super::action::Action::{Flag, Single, Push, Many}; use super::action::IArgAction; use super::generic::StoreAction; use super::help::{HelpAction, wrap_text}; -use action::IFlagAction; +use crate::action::IFlagAction; use self::ArgumentKind::{Positional, ShortOption, LongOption, Delimiter}; @@ -81,7 +81,7 @@ struct GenericOption<'parser> { struct EnvVar<'parser> { varid: usize, name: &'parser str, - action: Box, + action: Box, } impl<'a> Hash for GenericOption<'a> { @@ -139,7 +139,7 @@ struct Context<'ctx, 'parser: 'ctx> { list_arguments: HashMap>, Vec<&'ctx str>>, arguments: Vec<&'ctx str>, iter: Peekable>, - stderr: &'ctx mut (Write + 'ctx), + stderr: &'ctx mut (dyn Write + 'ctx), } impl<'a, 'b> Context<'a, 'b> { @@ -459,8 +459,11 @@ impl<'a, 'b> Context<'a, 'b> { return Parsed; } - fn parse(parser: &ArgumentParser, args: &Vec, stderr: &mut Write) - -> ParseResult + fn parse( + parser: &ArgumentParser, + args: &Vec, + stderr: &mut dyn Write, + ) -> ParseResult { let mut ctx = Context { parser: parser, @@ -552,9 +555,9 @@ impl<'parser, 'refer, T> Ref<'parser, 'refer, T> { Flag(_) => panic!("Flag arguments can't be positional"), Many(_) | Push(_) => { match self.parser.catchall_argument { - Some(ref y) => panic!(format!( + Some(ref y) => panic!( "Option {} conflicts with option {}", - name, y.name)), + name, y.name), None => {}, } self.parser.catchall_argument = Some(opt); @@ -720,14 +723,23 @@ impl<'parser> ArgumentParser<'parser> { /// /// Usually command-line option is used for printing help, /// this is here for any awkward cases - pub fn print_help(&self, name: &str, writer: &mut Write) -> IoResult<()> { + pub fn print_help( + &self, + name: &str, + writer: &mut dyn Write, + ) -> IoResult<()> + { return HelpFormatter::print_help(self, name, writer); } /// Print usage /// /// Usually printed into stderr on error of command-line parsing - pub fn print_usage(&self, name: &str, writer: &mut Write) -> IoResult<()> + pub fn print_usage( + &self, + name: &str, + writer: &mut dyn Write, + ) -> IoResult<()> { return HelpFormatter::print_usage(self, name, writer); } @@ -736,9 +748,12 @@ impl<'parser> ArgumentParser<'parser> { /// /// This is most powerful method. Usually you need `parse_args` /// or `parse_args_or_exit` instead - pub fn parse(&self, args: Vec, - stdout: &mut Write, stderr: &mut Write) - -> Result<(), i32> + pub fn parse( + &self, + args: Vec, + stdout: &mut dyn Write, + stderr: &mut dyn Write, + ) -> Result<(), i32> { let name = if !args.is_empty() { &args[0][..] } else { "unknown" }; match Context::parse(self, &args, stderr) { @@ -759,7 +774,7 @@ impl<'parser> ArgumentParser<'parser> { /// /// Only needed if you like to do some argument validation that is out /// of scope of the argparse - pub fn error(&self, command: &str, message: &str, writer: &mut Write) { + pub fn error(&self, command: &str, message: &str, writer: &mut dyn Write) { self.print_usage(command, writer).unwrap(); writeln!(writer, "{}: {}", command, message).ok(); } @@ -814,19 +829,25 @@ impl<'parser> ArgumentParser<'parser> { struct HelpFormatter<'a, 'b: 'a> { name: &'a str, parser: &'a ArgumentParser<'b>, - buf: &'a mut (Write + 'a), + buf: &'a mut (dyn Write + 'a), } impl<'a, 'b> HelpFormatter<'a, 'b> { - pub fn print_usage(parser: &ArgumentParser, name: &str, writer: &mut Write) - -> IoResult<()> + pub fn print_usage( + parser: &ArgumentParser, + name: &str, + writer: &mut dyn Write, + ) -> IoResult<()> { return HelpFormatter { parser: parser, name: name, buf: writer } .write_usage(); } - pub fn print_help(parser: &ArgumentParser, name: &str, writer: &mut Write) - -> IoResult<()> + pub fn print_help( + parser: &ArgumentParser, + name: &str, + writer: &mut dyn Write, + ) -> IoResult<()> { return HelpFormatter { parser: parser, name: name, buf: writer } .write_help(); @@ -836,76 +857,76 @@ impl<'a, 'b> HelpFormatter<'a, 'b> { -> IoResult<()> { let mut num = 2; - try!(write!(self.buf, " {}", arg.name)); + write!(self.buf, " {}", arg.name)?; num += arg.name.len(); if num >= OPTION_WIDTH { - try!(write!(self.buf, "\n")); + write!(self.buf, "\n")?; for _ in 0..OPTION_WIDTH { - try!(write!(self.buf, " ")); + write!(self.buf, " ")?; } } else { for _ in num..OPTION_WIDTH { - try!(write!(self.buf, " ")); + write!(self.buf, " ")?; } } - try!(wrap_text(self.buf, arg.help, TOTAL_WIDTH, OPTION_WIDTH)); - try!(write!(self.buf, "\n")); + wrap_text(self.buf, arg.help, TOTAL_WIDTH, OPTION_WIDTH)?; + write!(self.buf, "\n")?; return Ok(()); } pub fn print_option(&mut self, opt: &GenericOption<'b>) -> IoResult<()> { let mut num = 2; - try!(write!(self.buf, " ")); + write!(self.buf, " ")?; let mut niter = opt.names.iter(); let name = niter.next().unwrap(); - try!(write!(self.buf, "{}", name)); + write!(self.buf, "{}", name)?; num += name.len(); for name in niter { - try!(write!(self.buf, ",")); - try!(write!(self.buf, "{}", name)); + write!(self.buf, ",")?; + write!(self.buf, "{}", name)?; num += name.len() + 1; } match opt.action { Flag(_) => {} Single(_) | Push(_) | Many(_) => { - try!(write!(self.buf, " ")); + write!(self.buf, " ")?; let var = &self.parser.vars[opt.varid.unwrap()]; - try!(write!(self.buf, "{}", &var.metavar[..])); + write!(self.buf, "{}", &var.metavar[..])?; num += var.metavar.len() + 1; } } if num >= OPTION_WIDTH { - try!(write!(self.buf, "\n")); + write!(self.buf, "\n")?; for _ in 0..OPTION_WIDTH { - try!(write!(self.buf, " ")); + write!(self.buf, " ")?; } } else { for _ in num..OPTION_WIDTH { - try!(write!(self.buf, " ")); + write!(self.buf, " ")?; } } - try!(wrap_text(self.buf, opt.help, TOTAL_WIDTH, OPTION_WIDTH)); - try!(write!(self.buf, "\n")); + wrap_text(self.buf, opt.help, TOTAL_WIDTH, OPTION_WIDTH)?; + write!(self.buf, "\n")?; return Ok(()); } fn write_help(&mut self) -> IoResult<()> { - try!(self.write_usage()); - try!(write!(self.buf, "\n")); + self.write_usage()?; + write!(self.buf, "\n")?; if !self.parser.description.is_empty() { - try!(wrap_text(self.buf, self.parser.description,TOTAL_WIDTH, 0)); - try!(write!(self.buf, "\n")); + wrap_text(self.buf, self.parser.description, TOTAL_WIDTH, 0)?; + write!(self.buf, "\n")?; } if !self.parser.arguments.is_empty() || self.parser.catchall_argument.is_some() { - try!(write!(self.buf, "\nPositional arguments:\n")); + write!(self.buf, "\nPositional arguments:\n")?; for arg in self.parser.arguments.iter() { - try!(self.print_argument(&**arg)); + self.print_argument(&**arg)?; } match self.parser.catchall_argument { Some(ref opt) => { - try!(self.print_argument(&**opt)); + self.print_argument(&**opt)?; } None => {} } @@ -913,54 +934,53 @@ impl<'a, 'b> HelpFormatter<'a, 'b> { if !self.parser.short_options.is_empty() || !self.parser.long_options.is_empty() { - try!(write!(self.buf, "\nOptional arguments:\n")); + write!(self.buf, "\nOptional arguments:\n")?; for opt in self.parser.options.iter() { - try!(self.print_option(&**opt)); + self.print_option(&**opt)?; } } return Ok(()); } fn write_usage(&mut self) -> IoResult<()> { - try!(write!(self.buf, "Usage:\n ")); - try!(write!(self.buf, "{}", self.name)); + write!(self.buf, "Usage:\n ")?; + write!(self.buf, "{}", self.name)?; if !self.parser.options.is_empty() { if self.parser.short_options.len() > 1 || self.parser.long_options.len() > 1 { - try!(write!(self.buf, " [OPTIONS]")); + write!(self.buf, " [OPTIONS]")?; } for opt in self.parser.arguments.iter() { let var = &self.parser.vars[opt.varid]; - try!(write!(self.buf, " ")); + write!(self.buf, " ")?; if !var.required { - try!(write!(self.buf, "[")); + write!(self.buf, "[")?; } - try!(write!(self.buf, "{}", - &opt.name.to_ascii_uppercase()[..])); + write!(self.buf, "{}", &opt.name.to_ascii_uppercase()[..])?; if !var.required { - try!(write!(self.buf, "]")); + write!(self.buf, "]")?; } } match self.parser.catchall_argument { Some(ref opt) => { let var = &self.parser.vars[opt.varid]; - try!(write!(self.buf, " ")); + write!(self.buf, " ")?; if !var.required { - try!(write!(self.buf, "[")); + write!(self.buf, "[")?; } - try!(write!(self.buf, "{}", - &opt.name.to_ascii_uppercase()[..])); + write!(self.buf, "{}", + &opt.name.to_ascii_uppercase()[..])?; if !var.required { - try!(write!(self.buf, " ...]")); + write!(self.buf, " ...]")?; } else { - try!(write!(self.buf, " [...]")); + write!(self.buf, " [...]")?; } } None => {} } } - try!(write!(self.buf, "\n")); + writeln!(self.buf)?; return Ok(()); } diff --git a/src/print.rs b/src/print.rs index c832cf0..ba704d5 100644 --- a/src/print.rs +++ b/src/print.rs @@ -1,5 +1,5 @@ -use Print; -use action::{IFlagAction, ParseResult}; +use crate::Print; +use crate::action::{IFlagAction, ParseResult}; impl IFlagAction for Print { fn parse_flag(&self) -> ParseResult { diff --git a/src/test_bool.rs b/src/test_bool.rs index a30cf3c..871f910 100644 --- a/src/test_bool.rs +++ b/src/test_bool.rs @@ -1,7 +1,7 @@ -use parser::ArgumentParser; use super::Store; -use super::{StoreTrue, StoreFalse}; -use test_parser::{check_ok}; +use super::{StoreFalse, StoreTrue}; +use crate::parser::ArgumentParser; +use crate::test_parser::check_ok; fn store_true(args: &[&str]) -> bool { let mut verbose = false; diff --git a/src/test_const.rs b/src/test_const.rs index b12e3d8..a8b030b 100644 --- a/src/test_const.rs +++ b/src/test_const.rs @@ -1,7 +1,6 @@ -use parser::ArgumentParser; -use super::{PushConst}; -use test_parser::{check_ok}; - +use super::PushConst; +use crate::parser::ArgumentParser; +use crate::test_parser::check_ok; fn push_const(args: &[&str]) -> Vec { let mut res = vec!(); diff --git a/src/test_enum.rs b/src/test_enum.rs index 5205738..7c089ad 100644 --- a/src/test_enum.rs +++ b/src/test_enum.rs @@ -1,8 +1,8 @@ use std::str::FromStr; -use parser::ArgumentParser; use super::Store; -use test_parser::{check_ok}; +use crate::parser::ArgumentParser; +use crate::test_parser::check_ok; use self::Greeting::{Hello, Hi, NoGreeting}; diff --git a/src/test_env.rs b/src/test_env.rs index 2e1b649..d5ccf2b 100644 --- a/src/test_env.rs +++ b/src/test_env.rs @@ -1,9 +1,8 @@ use std::env; -use parser::ArgumentParser; use super::Store; -use test_parser::{check_ok}; - +use crate::parser::ArgumentParser; +use crate::test_parser::check_ok; fn required(args: &[&str]) -> (isize, isize) { let mut val1 = 1isize; diff --git a/src/test_float.rs b/src/test_float.rs index 9ef0f56..2ce61d1 100644 --- a/src/test_float.rs +++ b/src/test_float.rs @@ -1,7 +1,7 @@ -use parser::ArgumentParser; -use super::{IncrBy,DecrBy}; use super::Store; -use test_parser::{check_ok}; +use super::{DecrBy, IncrBy}; +use crate::parser::ArgumentParser; +use crate::test_parser::check_ok; fn incr_decr(args: &[&str]) -> f32 { let mut val = 0f32; diff --git a/src/test_help.rs b/src/test_help.rs index f23b14b..cee5779 100644 --- a/src/test_help.rs +++ b/src/test_help.rs @@ -1,7 +1,7 @@ use std::str::from_utf8; -use parser::ArgumentParser; -use super::{Store, List}; +use super::{List, Store}; +use crate::parser::ArgumentParser; #[test] fn test_empty() { diff --git a/src/test_int.rs b/src/test_int.rs index 1826eaf..21a458a 100644 --- a/src/test_int.rs +++ b/src/test_int.rs @@ -1,7 +1,7 @@ -use parser::ArgumentParser; +use crate::parser::ArgumentParser; use super::{IncrBy,DecrBy}; use super::Store; -use test_parser::{check_ok}; +use crate::test_parser::{check_ok}; fn incr_int(args: &[&str]) -> usize { let mut val = 0; diff --git a/src/test_many.rs b/src/test_many.rs index 68e2cec..27ae81b 100644 --- a/src/test_many.rs +++ b/src/test_many.rs @@ -1,6 +1,6 @@ -use parser::ArgumentParser; -use super::{List, Store, Collect}; -use test_parser::{check_ok}; +use super::{Collect, List, Store}; +use crate::parser::ArgumentParser; +use crate::test_parser::check_ok; fn pos_list(args: &[&str]) -> (isize, Vec) { let mut val1 = 1; diff --git a/src/test_optional.rs b/src/test_optional.rs index 5f4c35e..c12a717 100644 --- a/src/test_optional.rs +++ b/src/test_optional.rs @@ -1,6 +1,6 @@ -use parser::ArgumentParser; +use crate::parser::ArgumentParser; use super::StoreOption; -use test_parser::{check_ok}; +use crate::test_parser::{check_ok}; fn opt(args: &[&str]) -> Option { let mut val = None; diff --git a/src/test_parser.rs b/src/test_parser.rs index f60aa64..5280408 100644 --- a/src/test_parser.rs +++ b/src/test_parser.rs @@ -1,5 +1,5 @@ -use parser::ArgumentParser; +use crate::parser::ArgumentParser; pub fn check_ok(ap: &ArgumentParser, args: &[&str]) { let mut stdout = Vec::::new(); @@ -11,7 +11,7 @@ pub fn check_ok(ap: &ArgumentParser, args: &[&str]) { let res = ap.parse(owned_args, &mut stdout, &mut stderr); match res { Ok(()) => return, - Err(x) => panic!( + Err(x) => panic!("{}", String::from_utf8(stderr).unwrap() + &format!("Expected ok, but found Exit({})", x)[..]), } @@ -27,8 +27,8 @@ pub fn check_exit(ap: &ArgumentParser, args: &[&str]) { let res = ap.parse(owned_args, &mut stdout, &mut stderr); match res { Err(0) => return, - Err(x) => panic!(format!("Expected code {} got {}", 0usize, x)), - Ok(()) => panic!(format!("Expected failure, got success")), + Err(x) => panic!("Expected code {} got {}", 0usize, x), + Ok(()) => panic!("Expected failure, got success"), } } @@ -42,8 +42,8 @@ pub fn check_err(ap: &ArgumentParser, args: &[&str]) { let res = ap.parse(owned_args, &mut stdout, &mut stderr); match res { Err(2) => return, - Err(x) => panic!(format!("Expected code {} got {}", 2usize, x)), - Ok(()) => panic!(format!("Expected failure, got success")), + Err(x) => panic!("Expected code {} got {}", 2usize, x), + Ok(()) => panic!("Expected failure, got success"), } } diff --git a/src/test_path.rs b/src/test_path.rs index 868ae8c..86f81de 100644 --- a/src/test_path.rs +++ b/src/test_path.rs @@ -1,7 +1,7 @@ -use std::path::PathBuf; -use parser::ArgumentParser; use super::Parse; -use test_parser::{check_ok}; +use crate::parser::ArgumentParser; +use crate::test_parser::check_ok; +use std::path::PathBuf; fn parse_str(args: &[&str]) -> PathBuf { let mut val: PathBuf = From::from(""); diff --git a/src/test_pos.rs b/src/test_pos.rs index 2542050..8278eaa 100644 --- a/src/test_pos.rs +++ b/src/test_pos.rs @@ -1,6 +1,6 @@ -use parser::ArgumentParser; -use super::{Store, List}; -use test_parser::{check_ok}; +use super::{List, Store}; +use crate::parser::ArgumentParser; +use crate::test_parser::check_ok; fn parse_pos(args: &[&str]) -> isize { let mut val = 0; diff --git a/src/test_str.rs b/src/test_str.rs index 42db286..9ccb600 100644 --- a/src/test_str.rs +++ b/src/test_str.rs @@ -1,6 +1,6 @@ -use parser::ArgumentParser; +use crate::parser::ArgumentParser; use super::Store; -use test_parser::{check_ok}; +use crate::test_parser::{check_ok}; fn parse_str(args: &[&str]) -> String { let mut val: String = "".to_string(); diff --git a/src/test_usage.rs b/src/test_usage.rs index efe89fe..7708f38 100644 --- a/src/test_usage.rs +++ b/src/test_usage.rs @@ -1,7 +1,7 @@ use std::str::from_utf8; -use parser::ArgumentParser; -use super::{Store, List}; +use super::{List, Store}; +use crate::parser::ArgumentParser; #[test] fn test_empty() {