Skip to content

Commit

Permalink
Merge pull request #78 from tertsdiepraam/remove-try-parse
Browse files Browse the repository at this point in the history
Make API simpler and smaller
  • Loading branch information
tertsdiepraam authored Dec 22, 2023
2 parents db5a87e + 9229791 commit fc29ec5
Show file tree
Hide file tree
Showing 24 changed files with 470 additions and 266 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
16 changes: 8 additions & 8 deletions derive/src/help.rs
Original file line number Diff line number Diff line change
Expand Up @@ -74,27 +74,27 @@ pub fn help_string(
}

let options = if !options.is_empty() {
quote!(::uutils_args::internal::print_flags(&mut w, #indent, #width, [#(#options),*])?;)
quote!(::uutils_args::internal::print_flags(&mut w, #indent, #width, [#(#options),*]);)
} else {
quote!()
};

quote!(
let mut w = ::std::io::stdout();
use ::std::io::Write;
let mut w = String::new();
use ::std::fmt::Write;
writeln!(w, "{} {}",
option_env!("CARGO_BIN_NAME").unwrap_or(env!("CARGO_PKG_NAME")),
env!("CARGO_PKG_VERSION"),
)?;
).unwrap();

writeln!(w, "{}", #summary)?;
writeln!(w, "{}", #summary).unwrap();

writeln!(w, "\nUsage:\n {}", format!(#usage, bin_name))?;
writeln!(w, "\nUsage:\n {}", format!(#usage, bin_name)).unwrap();

#options

writeln!(w, "{}", #after_options)?;
Ok(())
writeln!(w, "{}", #after_options).unwrap();
w
)
}

Expand Down
13 changes: 8 additions & 5 deletions derive/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ pub fn arguments(input: TokenStream) -> TokenStream {
}
}

fn help(bin_name: &str) -> ::std::io::Result<()> {
fn help(bin_name: &str) -> String {
#help_string
}

Expand Down Expand Up @@ -150,16 +150,18 @@ pub fn value(input: TokenStream) -> TokenStream {
options.push(quote!(&[#(#keys),*]));

let stmt = if let Some(v) = value {
quote!(#(| #keys)* => #v)
quote!(#(| #keys)* => #v,)
} else {
let mut v = variant.clone();
v.attrs = vec![];
quote!(#(| #keys)* => Self::#v)
quote!(#(| #keys)* => Self::#v,)
};
match_arms.push(stmt);
}
}

let keys_len = all_keys.len();

let expanded = quote!(
impl #impl_generics Value for #name #ty_generics #where_clause {
fn from_value(value: &::std::ffi::OsStr) -> ::uutils_args::ValueResult<Self> {
Expand Down Expand Up @@ -191,15 +193,16 @@ pub fn value(input: TokenStream) -> TokenStream {
};

Ok(match opt {
#(#match_arms),*,
#(#match_arms)*
_ => unreachable!("Should be caught by (None, []) case above.")
})
}

#[cfg(feature = "complete")]
fn value_hint() -> ::uutils_args_complete::ValueHint {
let keys: [&str; #keys_len] = [#(#all_keys),*];
::uutils_args_complete::ValueHint::Strings(
[#(#all_keys),*]
keys
.into_iter()
.map(ToString::to_string)
.collect()
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);
}
17 changes: 8 additions & 9 deletions src/internal.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ use crate::error::ErrorKind;
use crate::value::Value;
use std::{
ffi::{OsStr, OsString},
io::Write,
fmt::Write,
};

/// Parses an echo-style positional argument
Expand Down Expand Up @@ -118,33 +118,32 @@ pub fn print_flags(
indent_size: usize,
width: usize,
options: impl IntoIterator<Item = (&'static str, &'static str)>,
) -> std::io::Result<()> {
) {
let indent = " ".repeat(indent_size);
writeln!(w, "\nOptions:")?;
writeln!(w, "\nOptions:").unwrap();
for (flags, help_string) in options {
let mut help_lines = help_string.lines();
write!(w, "{}{}", &indent, &flags)?;
write!(w, "{}{}", &indent, &flags).unwrap();

if flags.len() <= width {
let line = match help_lines.next() {
Some(line) => line,
None => {
writeln!(w)?;
writeln!(w).unwrap();
continue;
}
};
let help_indent = " ".repeat(width - flags.len() + 2);
writeln!(w, "{}{}", help_indent, line)?;
writeln!(w, "{}{}", help_indent, line).unwrap();
} else {
writeln!(w)?;
writeln!(w).unwrap();
}

let help_indent = " ".repeat(width + indent_size + 2);
for line in help_lines {
writeln!(w, "{}{}", help_indent, line)?;
writeln!(w, "{}{}", help_indent, line).unwrap();
}
}
Ok(())
}

#[cfg(test)]
Expand Down
Loading

0 comments on commit fc29ec5

Please sign in to comment.