Add --color always|never|auto interface (#1049)

Extends #1048 interface providing a more general interface that I think
should be standard.

Allows forcing colors to be on _or_ off. e.g. `NO_COLOR=1 pip install
pip-tools --color always` would be colored.

Hides the `--no-color` option as it only exists for compatibility (and
seems better than throwing an error when people assume it will exist).

Has a nice side-effect of documenting our coloring behaviors e.g.

```
--color <COLOR>
    Control colors in output
    
    [default: auto]

    Possible values:
    - auto:   Enables colored output only when the output is going to a terminal or TTY with support
    - always: Enables colored output regardless of the detected environment
    - never:  Disables colored output
```
This commit is contained in:
Zanie Blue 2024-01-22 23:01:36 -06:00 committed by GitHub
parent a9a7b0069b
commit 5db81c7caa
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View file

@ -57,14 +57,46 @@ struct Cli {
#[arg(global = true, long, short, conflicts_with = "quiet")]
verbose: bool,
/// Disable colors.
#[arg(global = true, long)]
/// Disable colors; provided for compatibility with `pip`.
#[arg(global = true, long, hide = true, conflicts_with = "color")]
no_color: bool,
/// Control colors in output.
#[arg(
global = true,
long,
value_enum,
default_value = "auto",
conflicts_with = "no_color"
)]
color: ColorChoice,
#[command(flatten)]
cache_args: CacheArgs,
}
#[derive(Debug, Clone, clap::ValueEnum)]
pub enum ColorChoice {
/// Enables colored output only when the output is going to a terminal or TTY with support.
Auto,
/// Enables colored output regardless of the detected environment.
Always,
/// Disables colored output.
Never,
}
impl ColorChoice {
fn to_anstream(&self) -> anstream::ColorChoice {
match self {
Self::Auto => anstream::ColorChoice::Auto,
Self::Always => anstream::ColorChoice::Always,
Self::Never => anstream::ColorChoice::Never,
}
}
}
#[derive(Subcommand)]
#[allow(clippy::large_enum_variant)]
enum Commands {
@ -558,6 +590,8 @@ async fn inner() -> Result<ExitStatus> {
if cli.no_color {
anstream::ColorChoice::write_global(anstream::ColorChoice::Never);
} else {
anstream::ColorChoice::write_global(cli.color.to_anstream());
}
miette::set_hook(Box::new(|_| {