Skip to content

edition: Upgrade to Rust 2021 edition #56

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -9,4 +9,4 @@ categories = ["command-line-interface"]
homepage = "http://github.com/tailhook/rust-argparse"
version = "0.2.2"
authors = ["Paul Colomiets <paul@colomiets.name>"]

edition = "2021"
11 changes: 5 additions & 6 deletions src/action.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,16 +8,15 @@ pub enum ParseResult {
Error(String),
}


pub enum Action<'a> {
Flag(Box<IFlagAction + 'a>),
Single(Box<IArgAction + 'a>),
Push(Box<IArgsAction + 'a>),
Many(Box<IArgsAction + 'a>),
Flag(Box<dyn IFlagAction + 'a>),
Single(Box<dyn IArgAction + 'a>),
Push(Box<dyn IArgsAction + 'a>),
Many(Box<dyn IArgsAction + 'a>),
}

pub trait TypedAction<T> {
fn bind<'x>(&self, Rc<RefCell<&'x mut T>>) -> Action<'x>;
fn bind<'x>(&self, _: Rc<RefCell<&'x mut T>>) -> Action<'x>;
}

pub trait IFlagAction {
Expand Down
12 changes: 6 additions & 6 deletions src/help.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand All @@ -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(());
Expand Down
138 changes: 79 additions & 59 deletions src/parser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};

Expand Down Expand Up @@ -81,7 +81,7 @@ struct GenericOption<'parser> {
struct EnvVar<'parser> {
varid: usize,
name: &'parser str,
action: Box<IArgAction + 'parser>,
action: Box<dyn IArgAction + 'parser>,
}

impl<'a> Hash for GenericOption<'a> {
Expand Down Expand Up @@ -139,7 +139,7 @@ struct Context<'ctx, 'parser: 'ctx> {
list_arguments: HashMap<Rc<GenericArgument<'parser>>, Vec<&'ctx str>>,
arguments: Vec<&'ctx str>,
iter: Peekable<Iter<'ctx, String>>,
stderr: &'ctx mut (Write + 'ctx),
stderr: &'ctx mut (dyn Write + 'ctx),
}

impl<'a, 'b> Context<'a, 'b> {
Expand Down Expand Up @@ -459,8 +459,11 @@ impl<'a, 'b> Context<'a, 'b> {
return Parsed;
}

fn parse(parser: &ArgumentParser, args: &Vec<String>, stderr: &mut Write)
-> ParseResult
fn parse(
parser: &ArgumentParser,
args: &Vec<String>,
stderr: &mut dyn Write,
) -> ParseResult
{
let mut ctx = Context {
parser: parser,
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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);
}
Expand All @@ -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<String>,
stdout: &mut Write, stderr: &mut Write)
-> Result<(), i32>
pub fn parse(
&self,
args: Vec<String>,
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) {
Expand All @@ -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();
}
Expand Down Expand Up @@ -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();
Expand All @@ -836,131 +857,130 @@ 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 => {}
}
}
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(());
}

Expand Down
4 changes: 2 additions & 2 deletions src/print.rs
Original file line number Diff line number Diff line change
@@ -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 {
Expand Down
6 changes: 3 additions & 3 deletions src/test_bool.rs
Original file line number Diff line number Diff line change
@@ -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;
Expand Down
Loading