clap icon indicating copy to clipboard operation
clap copied to clipboard

clap::Error to colored string

Open sigoden opened this issue 1 year ago • 5 comments

Please complete the following tasks

Clap Version

master

Describe your use case

I make a bash cli tool(https://github.com/sigoden/argc), it use clap as cli parser.

A pr(https://github.com/sigoden/argc/issues/37) have been submitted for request colored help and colored error message.

So I need a way to covert clap::Error to colored string.

Describe the solution you'd like

The easiest way is to expose following two apis.

  1. clap::error::Error::formatted

  2. clap::builder::StyledStr::write_colored

A better way is to add a to_color_string function to clap::error::Error

impl Error {
    #[cfg(feature = "color")]
    pub fn to_colored_string(&self) -> String {

    }
}

Alternatives, if applicable

No response

Additional Context

No response

sigoden avatar Aug 27 '22 12:08 sigoden

Is there a reason you can't just use Error::print or Error::exit?

In clap 4.x, we are planning on changing how we handle terminal styling which will lead to use exposing something like what is proposed in here.

epage avatar Aug 29 '22 13:08 epage

Argc use bash eval $(argc --argc-eval "$0" "$@") to retrive passed variables from stdout, so the help text or error message must print to stderr.

Error::print or Error::exit will print to stdout in some situation(ErrorKind::DisplayHelp | ErrorKind::DisplayVersion). So I can't use them.

sigoden avatar Aug 29 '22 13:08 sigoden

Error::print or Error::exit will print to stdout in some situation(ErrorKind::DisplayHelp | ErrorKind::DisplayVersion). So I can't use them.

In the interim, you can check the error kind and conditionally do it based on that.

epage avatar Aug 29 '22 14:08 epage

But I still need to print help(ErrorKind::DisplayHelp) to stderr. Is there a way to get the colored help string?

sigoden avatar Aug 29 '22 14:08 sigoden

No, and there won't be until some time during clap 4.x.

I was providing a way to workaround the problem until we do provide an API for this. This is my top clap priority once 4.0 is released.

epage avatar Aug 29 '22 15:08 epage

Went ahead with this in #4248

epage avatar Sep 28 '22 16:09 epage