Skip to content

Commit

Permalink
remove parse and rename try_parse to parse
Browse files Browse the repository at this point in the history
  • Loading branch information
tertsdiepraam committed Dec 19, 2023
1 parent 5cdae9b commit 43f792f
Show file tree
Hide file tree
Showing 21 changed files with 414 additions and 205 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ impl Options<Arg> for Settings {
}

fn run(args: &[&str]) -> String {
let (s, operands) = Settings::default().parse(args);
let (s, operands) = Settings::default().parse(args).unwrap();
let text = operands.iter().map(|s| s.to_string_lossy()).collect::<Vec<_>>().join(" ");
let mut output = if s.caps {
text.to_uppercase()
Expand Down
10 changes: 5 additions & 5 deletions docs/guide/port.md
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ impl Options<Arg> for Settings {
}
}

let a = Settings::default().parse(std::env::args_os()).0.a;
let a = Settings::default().parse(std::env::args_os()).unwrap().0.a;
```

### `ArgAction::SetFalse`
Expand Down Expand Up @@ -144,7 +144,7 @@ impl Options<Arg> for Settings {
}
}

let a = Settings::default().parse(std::env::args_os()).0.a;
let a = Settings::default().parse(std::env::args_os()).unwrap().0.a;
```

### `ArgAction::Count`
Expand Down Expand Up @@ -182,7 +182,7 @@ impl Options<Arg> for Settings {
}
}

let a = Settings::default().parse(std::env::args_os()).0.a;
let a = Settings::default().parse(std::env::args_os()).unwrap().0.a;
```

### `ArgAction::Set`
Expand Down Expand Up @@ -222,7 +222,7 @@ impl Options<Arg> for Settings {
}
}

let a = Settings::default().parse(std::env::args_os()).0.a;
let a = Settings::default().parse(std::env::args_os()).unwrap().0.a;
```

### `ArgAction::Append`
Expand Down Expand Up @@ -262,7 +262,7 @@ impl Options<Arg> for Settings {
}
}

let a = Settings::default().parse(std::env::args_os()).0.a;
let a = Settings::default().parse(std::env::args_os()).unwrap().0.a;
```

<div class="chapters">
Expand Down
35 changes: 17 additions & 18 deletions docs/guide/quick.md
Original file line number Diff line number Diff line change
Expand Up @@ -66,14 +66,14 @@ impl Options<Arg> for Settings {
}
}

let (settings, operands) = Settings::default().parse(["test"]);
let (settings, operands) = Settings::default().parse(["test"]).unwrap();
assert!(!settings.force);
assert_eq!(operands, Vec::<OsString>::new());

let (settings, operands) = Settings::default().parse(["test", "-f"]);
let (settings, operands) = Settings::default().parse(["test", "-f"]).unwrap();
assert!(settings.force);

let (settings, operands) = Settings::default().parse(["test", "foo"]);
let (settings, operands) = Settings::default().parse(["test", "foo"]).unwrap();
assert!(!settings.force);
assert_eq!(operands, vec![OsString::from("foo")]);
```
Expand Down Expand Up @@ -108,17 +108,16 @@ impl Options<Arg> for Settings {
}
}

let (settings, operands) = Settings::default().parse(["test"]);
let (settings, operands) = Settings::default().parse(["test"]).unwrap();
assert!(!settings.force);
assert_eq!(operands, Vec::<OsString>::new());

let (settings, operands) = Settings::default().parse(["test", "-f", "some-operand"]);
let (settings, operands) = Settings::default().parse(["test", "-f", "some-operand"]).unwrap();
assert!(settings.force);

assert_eq!(operands, vec!["some-operand"]);
let (settings, operands) = Settings::default().parse(["test", "-f", "-F", "some-other-operand"]);
assert!(!settings.force);

let (settings, operands) = Settings::default().parse(["test", "-f", "-F", "some-other-operand"]).unwrap();
assert!(!settings.force);
assert_eq!(operands, vec!["some-other-operand"]);
```

Expand Down Expand Up @@ -169,11 +168,11 @@ enum Arg {
# }
#
# assert_eq!(
# Settings::default().parse(["test"]).0.name,
# Settings::default().parse(["test"]).unwrap().0.name,
# OsString::new(),
# );
# assert_eq!(
# Settings::default().parse(["test", "--name=John"]).0.name,
# Settings::default().parse(["test", "--name=John"]).unwrap().0.name,
# OsString::from("John"),
# );
```
Expand Down Expand Up @@ -206,11 +205,11 @@ enum Arg {
# }
#
# assert_eq!(
# Settings::default().parse(["test", "--name"]).0.name,
# Settings::default().parse(["test", "--name"]).unwrap().0.name,
# OsString::from("anonymous"),
# );
# assert_eq!(
# Settings::default().parse(["test", "--name=John"]).0.name,
# Settings::default().parse(["test", "--name=John"]).unwrap().0.name,
# OsString::from("John"),
# );
```
Expand Down Expand Up @@ -242,9 +241,9 @@ enum Arg {
# }
# }
#
# assert!(!Settings::default().parse(["test"]).0.force);
# assert!(Settings::default().parse(["test", "-f"]).0.force);
# assert!(!Settings::default().parse(["test", "-F"]).0.force);
# assert!(!Settings::default().parse(["test"]).unwrap().0.force);
# assert!(Settings::default().parse(["test", "-f"]).unwrap().0.force);
# assert!(!Settings::default().parse(["test", "-F"]).unwrap().0.force);
```

This is particularly interesting for defining "shortcut" arguments. For example, `ls` takes a `--sort=WORD` argument, that defines how the files should be sorted. But it also has shorthands like `-t`, which is the same as `--sort=time`. All of these can be implemented on one variant:
Expand Down Expand Up @@ -277,9 +276,9 @@ enum Arg {
# }
# }
#
# assert_eq!(Settings::default().parse(["test"]).0.sort, String::new());
# assert_eq!(Settings::default().parse(["test", "--sort=time"]).0.sort, String::from("time"));
# assert_eq!(Settings::default().parse(["test", "-t"]).0.sort, String::from("time"));
# assert_eq!(Settings::default().parse(["test"]).unwrap().0.sort, String::new());
# assert_eq!(Settings::default().parse(["test", "--sort=time"]).unwrap().0.sort, String::from("time"));
# assert_eq!(Settings::default().parse(["test", "-t"]).unwrap().0.sort, String::from("time"));
```

<div class="chapters">
Expand Down
2 changes: 1 addition & 1 deletion examples/completion.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,5 +38,5 @@ impl Options<Arg> for Settings {
}

fn main() {
Settings.parse(std::env::args_os());
Settings.parse(std::env::args_os()).unwrap();
}
17 changes: 13 additions & 4 deletions examples/deprecated.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,8 +43,17 @@ impl Options<Arg> for Settings {
}

fn main() {
assert_eq!(Settings::default().parse(["test", "-10"]).0.n1, 10usize);
assert!(Settings::default().try_parse(["test", "--10"]).is_err());
assert_eq!(Settings::default().parse(["test", "+10"]).0.n2, 10isize);
assert_eq!(Settings::default().parse(["test", "+-10"]).0.n2, -10isize);
assert_eq!(
Settings::default().parse(["test", "-10"]).unwrap().0.n1,
10usize
);
assert!(Settings::default().parse(["test", "--10"]).is_err());
assert_eq!(
Settings::default().parse(["test", "+10"]).unwrap().0.n2,
10isize
);
assert_eq!(
Settings::default().parse(["test", "+-10"]).unwrap().0.n2,
-10isize
);
}
3 changes: 2 additions & 1 deletion examples/hello_world.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,8 @@ fn main() -> Result<(), uutils_args::Error> {
name: String::new(),
count: 1,
}
.parse(std::env::args_os());
.parse(std::env::args_os())
.unwrap();

for _ in 0..settings.count {
println!("Hello, {}!", settings.name);
Expand Down
2 changes: 1 addition & 1 deletion examples/value.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,6 @@ impl Options<Arg> for Settings {
}

fn main() {
let (settings, _operands) = Settings::default().parse(std::env::args_os());
let (settings, _operands) = Settings::default().parse(std::env::args_os()).unwrap();
println!("{:?}", settings.color);
}
37 changes: 3 additions & 34 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -67,16 +67,6 @@ pub enum Argument<T: Arguments> {
Custom(T),
}

fn exit_if_err<T>(res: Result<T, Error>) -> T {
match res {
Ok(v) => v,
Err(err) => {
eprintln!("{err}");
std::process::exit(err.exit_code);
}
}
}

/// Defines how the arguments are parsed.
///
/// If a type `T` implements this trait, we can construct an `ArgumentIter<T>`,
Expand Down Expand Up @@ -112,23 +102,11 @@ pub trait Arguments: Sized {
/// Get the version string for this command.
fn version() -> String;

/// Check all arguments immediately and exit on errors.
///
/// This is useful if you want to validate the arguments. This method will
/// exit if `--help` or `--version` are passed and if any errors are found.
fn check<I>(args: I)
where
I: IntoIterator,
I::Item: Into<OsString>,
{
exit_if_err(Self::try_check(args))
}

/// Check all arguments immediately and return any errors.
///
/// This is useful if you want to validate the arguments. This method will
/// exit if `--help` or `--version` are passed.
fn try_check<I>(args: I) -> Result<(), Error>
fn check<I>(args: I) -> Result<(), Error>
where
I: IntoIterator,
I::Item: Into<OsString>,
Expand All @@ -145,8 +123,7 @@ pub trait Arguments: Sized {
/// An iterator over arguments.
///
/// Can be constructed by calling [`Arguments::parse`]. Usually, this method
/// won't be used directly, but is used internally in [`Options::parse`] and
/// [`Options::try_parse`].
/// won't be used directly, but is used internally in [`Options::parse`].
pub struct ArgumentIter<T: Arguments> {
parser: lexopt::Parser,
positional_arguments: Vec<OsString>,
Expand Down Expand Up @@ -218,16 +195,8 @@ pub trait Options<Arg: Arguments>: Sized {
fn apply(&mut self, arg: Arg);

/// Parse an iterator of arguments into the options
fn parse<I>(self, args: I) -> (Self, Vec<OsString>)
where
I: IntoIterator,
I::Item: Into<OsString>,
{
exit_if_err(self.try_parse(args))
}

#[allow(unused_mut)]
fn try_parse<I>(mut self, args: I) -> Result<(Self, Vec<OsString>), Error>
fn parse<I>(mut self, args: I) -> Result<(Self, Vec<OsString>), Error>
where
I: IntoIterator,
I::Item: Into<OsString>,
Expand Down
6 changes: 3 additions & 3 deletions tests/coreutils/arch.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,11 @@ enum Arg {}

#[test]
fn no_args() {
assert!(Arg::try_check(["arch"]).is_ok());
assert!(Arg::check(["arch"]).is_ok());
}

#[test]
fn one_arg_fails() {
assert!(Arg::try_check(["arch", "-f"]).is_err());
assert!(Arg::try_check(["arch", "--foo"]).is_err());
assert!(Arg::check(["arch", "-f"]).is_err());
assert!(Arg::check(["arch", "--foo"]).is_err());
}
Loading

0 comments on commit 43f792f

Please sign in to comment.