Skip to content

Commit

Permalink
Merge branch 'master' into crate-path-helper
Browse files Browse the repository at this point in the history
  • Loading branch information
pacak authored Feb 6, 2024
2 parents e56204e + 5ee06be commit ad4cecd
Show file tree
Hide file tree
Showing 12 changed files with 54 additions and 23 deletions.
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ include = [
[dependencies]
bpaf_derive = { path = "./bpaf_derive", version = "=0.5.7", optional = true }
owo-colors = { version = ">=3.5, <5.0", default-features = false, optional = true }
supports-color = { version = "2.0.0", optional = true }
supports-color = { version = ">=2.0.0, <4.0", optional = true }

[dev-dependencies]
bpaf = { path = ".", features = ["derive", "extradocs", "autocomplete", "docgen", "batteries", "dull-color"] }
Expand Down
2 changes: 2 additions & 0 deletions Changelog.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
# Change Log

## bpaf [0.9.10] - unreleased
- due to dependency change colored output for legacy version is no longer supported

## bpaf [0.9.9] - 2024-01-17
- fix formatting in ambiguity error message
Expand Down
4 changes: 4 additions & 0 deletions bpaf_derive/src/td.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ pub(crate) struct OptionsCfg {
pub(crate) header: Option<Help>,
pub(crate) usage: Option<Box<Expr>>,
pub(crate) version: Option<Box<Expr>>,
pub(crate) max_width: Option<Box<Expr>>,
}

#[derive(Debug, Default)]
Expand Down Expand Up @@ -246,6 +247,9 @@ impl Parse for TopInfo {
with_command(&kw, command.as_mut(), |cfg| cfg.help = Some(help))?;
} else if kw == "bpaf_path" {
bpaf_path.replace(parse_name_value::<syn::Path>(input)?);
} else if kw == "max_width" {
let max_width = parse_arg(input)?;
with_options(&kw, options.as_mut(), |opt| opt.max_width = Some(max_width))?;
} else if let Some(pd) = PostDecor::parse(input, &kw)? {
attrs.push(pd);
} else {
Expand Down
7 changes: 7 additions & 0 deletions bpaf_derive/src/top.rs
Original file line number Diff line number Diff line change
Expand Up @@ -197,13 +197,15 @@ impl ToTokens for Top {
descr,
footer,
header,
max_width,
} = options;

let version = version.as_ref().map(|v| quote!(.version(#v)));
let usage = usage.as_ref().map(|v| quote!(.usage(#v)));
let descr = descr.as_ref().map(|v| quote!(.descr(#v)));
let footer = footer.as_ref().map(|v| quote!(.footer(#v)));
let header = header.as_ref().map(|v| quote!(.header(#v)));
let max_width = max_width.as_ref().map(|v| quote!(.max_width(#v)));

let CommandCfg {
name,
Expand All @@ -228,6 +230,7 @@ impl ToTokens for Top {
#header
#footer
#usage
#max_width
.command(#name)
#(#short)*
#(#long)*
Expand All @@ -245,6 +248,7 @@ impl ToTokens for Top {
descr,
footer,
header,
max_width
} = options;
let body = match cargo_helper {
Some(cargo) => quote!(::bpaf::cargo_helper(#cargo, #body)),
Expand All @@ -256,6 +260,8 @@ impl ToTokens for Top {
let descr = descr.as_ref().map(|v| quote!(.descr(#v)));
let footer = footer.as_ref().map(|v| quote!(.footer(#v)));
let header = header.as_ref().map(|v| quote!(.header(#v)));
let max_width = max_width.as_ref().map(|v| quote!(.max_width(#v)));

quote! {
#vis fn #generate() -> ::bpaf::OptionParser<#ty> {
#[allow(unused_imports)]
Expand All @@ -268,6 +274,7 @@ impl ToTokens for Top {
#header
#footer
#usage
#max_width
}
}
}
Expand Down
5 changes: 1 addition & 4 deletions legacy/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,7 @@ edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
bpaf = { path = "../", features = ["derive", "autocomplete", "dull-color", "docgen"] }
bpaf = { path = "../", features = ["derive", "autocomplete", "docgen"] }
bpaf_derive = { path = "../bpaf_derive" }
rustix = "=0.37.19"
linux-raw-sys = "=0.3.8"
is-terminal = "=0.4.7"

[workspace]
1 change: 1 addition & 0 deletions src/buffer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ mod manpage;
mod splitter;

pub(crate) use self::console::Color;

#[cfg(feature = "docgen")]
pub use manpage::Section;

Expand Down
8 changes: 4 additions & 4 deletions src/buffer/console.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ use super::{
use super::Style;

const MAX_TAB: usize = 24;
const MAX_WIDTH: usize = 100;
pub(crate) const MAX_WIDTH: usize = 100;

#[derive(Debug, Copy, Clone, Eq, PartialEq)]
/// Default to dull color if colors are enabled,
Expand Down Expand Up @@ -133,11 +133,11 @@ impl Doc {
/// difference for rendered help message, otherwise you can pass `true`.
#[must_use]
pub fn monochrome(&self, full: bool) -> String {
self.render_console(full, Color::Monochrome)
self.render_console(full, Color::Monochrome, MAX_WIDTH)
}

#[allow(clippy::too_many_lines)] // it's a big ass match statement
pub(crate) fn render_console(&self, full: bool, color: Color) -> String {
pub(crate) fn render_console(&self, full: bool, color: Color, max_width: usize) -> String {
let mut res = String::new();
let mut tabstop = 0;
let mut byte_pos = 0;
Expand Down Expand Up @@ -208,7 +208,7 @@ impl Doc {
if pending_blank_line && !res.ends_with("\n\n") {
res.push('\n');
}
if char_pos > MAX_WIDTH {
if char_pos + s.len() > max_width {
char_pos = 0;
res.truncate(res.trim_end().len());
res.push('\n');
Expand Down
22 changes: 12 additions & 10 deletions src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,7 @@ use std::ops::Range;
use crate::{
args::{Arg, State},
buffer::{Block, Color, Doc, Style, Token},
item::Item,
item::ShortLong,
item::{Item, ShortLong},
meta_help::Metavar,
meta_youmean::{Suggestion, Variant},
Meta,
Expand Down Expand Up @@ -202,20 +201,24 @@ impl ParseFailure {
}
}

/// Run an action appropriate to the failure and produce the exit code
///
/// Prints a message to `stdout` or `stderr` and returns the exit code
/// Returns the exit code for the failure
#[allow(clippy::must_use_candidate)]
pub fn exit_code(self) -> i32 {
match self {
Self::Stdout(..) | Self::Completion(..) => 0,
Self::Stderr(..) => 1,
}
}

/// Prints a message to `stdout` or `stderr` appropriate to the failure.
pub fn print_mesage(&self, max_width: usize) {
let color = Color::default();
match self {
ParseFailure::Stdout(msg, full) => {
println!("{}", msg.render_console(full, color));
0
println!("{}", msg.render_console(*full, color, max_width));
}
ParseFailure::Completion(s) => {
print!("{}", s);
0
}
ParseFailure::Stderr(msg) => {
#[allow(unused_mut)]
Expand All @@ -231,8 +234,7 @@ impl ParseFailure {
color.push_str(Style::Invalid, &mut error, "Error: ");
}

eprintln!("{}{}", error, msg.render_console(true, color));
1
eprintln!("{}{}", error, msg.render_console(true, color, max_width));
}
}
}
Expand Down
20 changes: 19 additions & 1 deletion src/info.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ pub struct Info {
pub help_arg: NamedArg,
pub version_arg: NamedArg,
pub help_if_no_args: bool,
pub max_width: usize,
}

impl Default for Info {
Expand All @@ -42,6 +43,7 @@ impl Default for Info {
.long("version")
.help("Prints version information"),
help_if_no_args: false,
max_width: 100,
}
}
}
Expand Down Expand Up @@ -87,7 +89,10 @@ impl<T> OptionParser<T> {
{
match self.run_inner(Args::current_args()) {
Ok(t) => t,
Err(err) => std::process::exit(err.exit_code()),
Err(err) => {
err.print_mesage(self.info.max_width);
std::process::exit(err.exit_code())
}
}
}

Expand Down Expand Up @@ -647,6 +652,19 @@ impl<T> OptionParser<T> {
self.info.help_if_no_args = true;
self
}

/// Set the width of the help message printed to the terminal upon failure
///
/// By default, the help message is printed with a width of 100 characters.
/// This method allows to change where the help message is wrapped.
///
/// Setting the max width too low may negatively affect the readability of the help message.
/// Also, the alignment padding of broken lines is always applied.
#[must_use]
pub fn max_width(mut self, width: usize) -> Self {
self.info.max_width = width;
self
}
}

impl Info {
Expand Down
2 changes: 1 addition & 1 deletion tests/errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -181,7 +181,7 @@ fn should_not_split_adjacent_ambig_options() {
assert_eq!(r, expected);

let r = parser.run_inner(&["-ahello"]).unwrap_err().unwrap_stderr();
let expected = "app supports `-a` as both an option and an option-argument, try to split `-ahello` into individual options\n(-a -h ..) or use `-a=hello` syntax to disambiguate";
let expected = "app supports `-a` as both an option and an option-argument, try to split `-ahello` into individual\noptions (-a -h ..) or use `-a=hello` syntax to disambiguate";
assert_eq!(r, expected);

// this one is okay, try to parse -a as argument - it fails because "hello" is not a number, then
Expand Down
2 changes: 1 addition & 1 deletion tests/meta_youmean.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ fn ambiguity() {
let parser = construct!([a0, a1]).to_options();

let r = parser.run_inner(&["-aaaaaa"]).unwrap_err().unwrap_stderr();
assert_eq!(r, "app supports `-a` as both an option and an option-argument, try to split `-aaaaaa` into individual options\n(-a -a ..) or use `-a=aaaaa` syntax to disambiguate");
assert_eq!(r, "app supports `-a` as both an option and an option-argument, try to split `-aaaaaa` into individual\noptions (-a -a ..) or use `-a=aaaaa` syntax to disambiguate");

let r = parser.run_inner(&["-b"]).unwrap_err().unwrap_stderr();
// single char typos are too random
Expand Down
2 changes: 1 addition & 1 deletion tests/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1441,7 +1441,7 @@ fn suggestion_for_equals_1() {
.unwrap_stderr();
assert_eq!(
r,
"`--par` requires an argument `P`, got a flag `--bar=baz`, try `--par=--bar=baz` to use it as an argument"
"`--par` requires an argument `P`, got a flag `--bar=baz`, try `--par=--bar=baz` to use it as an\nargument"
);
}

Expand Down

0 comments on commit ad4cecd

Please sign in to comment.