Skip to content

Commit

Permalink
fix!: Make color settings an enum
Browse files Browse the repository at this point in the history
  • Loading branch information
pksunkara committed Oct 12, 2021
1 parent 5a696f0 commit fce9d21
Show file tree
Hide file tree
Showing 12 changed files with 56 additions and 128 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -472,7 +472,7 @@ Disabling optional features can decrease the binary size of `clap` and decrease
* **std**: _Not Currently Used._ Placeholder for supporting `no_std` environments in a backwards compatible manner.
* **derive**: Enables the custom derive (i.e. `#[derive(Parser)]`). Without this you must use one of the other methods of creating a `clap` CLI listed above. (builds dependency `clap_derive`)
* **cargo**: Turns on macros that read values from `CARGO_*` environment variables.
* **color**: Turns on colored error messages. (builds dependency `termcolor`)
* **color**: Turns on colored error messages. (builds dependency `atty`, `termcolor`)
* **env**: Turns on the usage of environment variables during parsing.
* **suggestions**: Turns on the `Did you mean '--myoption'?` feature for when users make typos. (builds dependency `strsim`)
* **unicode**: Turns on support for unicode characters in arguments and help messages. (builds dependency `textwrap`, `unicase`)
Expand Down
2 changes: 1 addition & 1 deletion clap_derive/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
#![doc(html_root_url = "https://docs.rs/clap_derive/3.0.0-beta.4")]

//! This crate is custom derive for clap. It should not be used
//! directly. See [clap documentation](clap)
//! directly. See [clap documentation](http://docs.rs/clap)
//! for the usage of `#[derive(Parser)]`.
#![forbid(unsafe_code)]
Expand Down
27 changes: 12 additions & 15 deletions src/build/app/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ use crate::{
mkeymap::MKeyMap,
output::{fmt::Colorizer, Help, HelpWriter, Usage},
parse::{ArgMatcher, ArgMatches, Input, Parser},
util::{safe_exit, termcolor::ColorChoice, Id, Key, USAGE_CODE},
util::{color::ColorChoice, safe_exit, Id, Key, USAGE_CODE},
Result as ClapResult, INTERNAL_ERROR_MSG,
};

Expand Down Expand Up @@ -90,6 +90,7 @@ pub struct App<'help> {
pub(crate) template: Option<&'help str>,
pub(crate) settings: AppFlags,
pub(crate) g_settings: AppFlags,
pub(crate) color: ColorChoice,
pub(crate) args: MKeyMap<'help>,
pub(crate) subcommands: Vec<App<'help>>,
pub(crate) replacers: HashMap<&'help str, &'help [&'help str]>,
Expand Down Expand Up @@ -985,7 +986,7 @@ impl<'help> App<'help> {
/// ```no_run
/// # use clap::{App, AppSettings};
/// App::new("myprog")
/// .unset_global_setting(AppSettings::ColorAuto)
/// .unset_global_setting(AppSettings::UnifiedHelpMessage)
/// # ;
/// ```
/// [global]: App::global_setting()
Expand All @@ -996,6 +997,14 @@ impl<'help> App<'help> {
self
}

/// @TODO
#[cfg(feature = "color")]
#[inline]
pub fn color(mut self, color: ColorChoice) -> Self {
self.color = color;
self
}

/// Sets the terminal width at which to wrap help messages. Defaults to
/// `100`. Using `0` will ignore terminal widths and use source formatting.
///
Expand Down Expand Up @@ -2646,20 +2655,8 @@ impl<'help> App<'help> {
}

#[inline]
// Should we color the output?
pub(crate) fn get_color(&self) -> ColorChoice {
debug!("App::color: Color setting...");

if self.is_set(AppSettings::ColorNever) {
debug!("Never");
ColorChoice::Never
} else if self.is_set(AppSettings::ColorAlways) {
debug!("Always");
ColorChoice::Always
} else {
debug!("Auto");
ColorChoice::Auto
}
self.color
}

#[inline]
Expand Down
79 changes: 1 addition & 78 deletions src/build/app/settings.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,9 +26,6 @@ bitflags! {
const NO_POS_VALUES = 1 << 17;
const NEXT_LINE_HELP = 1 << 18;
const DERIVE_DISP_ORDER = 1 << 19;
const COLOR_ALWAYS = 1 << 21;
const COLOR_AUTO = 1 << 22;
const COLOR_NEVER = 1 << 23;
const DONT_DELIM_TRAIL = 1 << 24;
const ALLOW_NEG_NUMS = 1 << 25;
const DISABLE_HELP_SC = 1 << 27;
Expand Down Expand Up @@ -58,7 +55,7 @@ pub struct AppFlags(Flags);

impl Default for AppFlags {
fn default() -> Self {
AppFlags(Flags::COLOR_AUTO)
Self::empty()
}
}

Expand All @@ -79,12 +76,6 @@ impl_settings! { AppSettings, AppFlags,
=> Flags::ALLOW_NEG_NUMS,
AllowMissingPositional("allowmissingpositional")
=> Flags::ALLOW_MISSING_POS,
ColorAlways("coloralways")
=> Flags::COLOR_ALWAYS,
ColorAuto("colorauto")
=> Flags::COLOR_AUTO,
ColorNever("colornever")
=> Flags::COLOR_NEVER,
DontDelimitTrailingValues("dontdelimittrailingvalues")
=> Flags::DONT_DELIM_TRAIL,
DontCollapseArgsInUsage("dontcollapseargsinusage")
Expand Down Expand Up @@ -490,62 +481,6 @@ pub enum AppSettings {
/// ```
SubcommandPrecedenceOverArg,

/// Enables colored output only when the output is going to a terminal or TTY.
///
/// **NOTE:** This is the default behavior of `clap`.
///
/// **NOTE:** Must be compiled with the `color` cargo feature.
///
/// # Platform Specific
///
/// This setting only applies to Unix, Linux, and OSX (i.e. non-Windows platforms).
///
/// # Examples
///
/// ```no_run
/// # use clap::{App, Arg, AppSettings};
/// App::new("myprog")
/// .setting(AppSettings::ColorAuto)
/// .get_matches();
/// ```
ColorAuto,

/// Enables colored output regardless of whether or not the output is going to a terminal/TTY.
///
/// **NOTE:** Must be compiled with the `color` cargo feature.
///
/// # Platform Specific
///
/// This setting only applies to Unix, Linux, and OSX (i.e. non-Windows platforms).
///
/// # Examples
///
/// ```no_run
/// # use clap::{App, Arg, AppSettings};
/// App::new("myprog")
/// .setting(AppSettings::ColorAlways)
/// .get_matches();
/// ```
ColorAlways,

/// Disables colored output no matter if the output is going to a terminal/TTY, or not.
///
/// **NOTE:** Must be compiled with the `color` cargo feature
///
/// # Platform Specific
///
/// This setting only applies to Unix, Linux, and OSX (i.e. non-Windows platforms)
///
/// # Examples
///
/// ```no_run
/// # use clap::{App, Arg, AppSettings};
/// App::new("myprog")
/// .setting(AppSettings::ColorNever)
/// .get_matches();
/// ```
ColorNever,

/// Disables the automatic collapsing of positional args into `[ARGS]` inside the usage string
///
/// # Examples
Expand Down Expand Up @@ -1085,18 +1020,6 @@ mod test {
"allownegativenumbers".parse::<AppSettings>().unwrap(),
AppSettings::AllowNegativeNumbers
);
assert_eq!(
"colorauto".parse::<AppSettings>().unwrap(),
AppSettings::ColorAuto
);
assert_eq!(
"coloralways".parse::<AppSettings>().unwrap(),
AppSettings::ColorAlways
);
assert_eq!(
"colornever".parse::<AppSettings>().unwrap(),
AppSettings::ColorNever
);
assert_eq!(
"disablehelpsubcommand".parse::<AppSettings>().unwrap(),
AppSettings::DisableHelpSubcommand
Expand Down
1 change: 1 addition & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ pub use crate::{
},
parse::errors::{Error, ErrorKind, Result},
parse::{ArgMatches, Indices, OsValues, Values},
util::color::ColorChoice,
};

pub use crate::derive::{ArgEnum, Args, FromArgMatches, IntoApp, Parser, Subcommand};
Expand Down
14 changes: 8 additions & 6 deletions src/output/fmt.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
#[cfg(not(feature = "color"))]
use crate::util::termcolor::{Color, ColorChoice};
use crate::util::color::Color;
use crate::util::color::ColorChoice;

#[cfg(feature = "color")]
use termcolor::{Color, ColorChoice};
use termcolor::Color;

use std::{
fmt::{self, Display, Formatter},
Expand Down Expand Up @@ -63,12 +65,12 @@ impl Colorizer {
impl Colorizer {
#[cfg(feature = "color")]
pub(crate) fn print(&self) -> io::Result<()> {
use termcolor::{BufferWriter, ColorSpec, WriteColor};
use termcolor::{BufferWriter, ColorChoice as DepColorChoice, ColorSpec, WriteColor};

let color_when = match self.color_when {
always @ ColorChoice::Always => always,
choice if is_a_tty(self.use_stderr) => choice,
_ => ColorChoice::Never,
ColorChoice::Always => DepColorChoice::Always,
ColorChoice::Auto if is_a_tty(self.use_stderr) => DepColorChoice::Auto,
_ => DepColorChoice::Never,
};

let writer = if self.use_stderr {
Expand Down
2 changes: 1 addition & 1 deletion src/parse/errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ use crate::{
build::Arg,
output::fmt::Colorizer,
parse::features::suggestions,
util::{safe_exit, termcolor::ColorChoice, SUCCESS_CODE, USAGE_CODE},
util::{color::ColorChoice, safe_exit, SUCCESS_CODE, USAGE_CODE},
App, AppSettings,
};

Expand Down
23 changes: 23 additions & 0 deletions src/util/color.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
/// @TODO
#[derive(Debug, Copy, Clone, PartialEq)]
pub enum ColorChoice {
/// @TODO
Auto,
/// @TODO
Always,
/// @TODO
Never,
}

impl Default for ColorChoice {
fn default() -> Self {
Self::Auto
}
}

#[derive(Debug)]
pub(crate) enum Color {
Green,
Yellow,
Red,
}
7 changes: 2 additions & 5 deletions src/util/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,7 @@ pub use self::fnv::Key;
pub(crate) use self::str_to_bool::str_to_bool;
pub(crate) use self::{graph::ChildGraph, id::Id};

#[cfg(feature = "color")]
pub(crate) use termcolor;

#[cfg(not(feature = "color"))]
pub(crate) mod termcolor;
pub(crate) mod color;

pub(crate) const SUCCESS_CODE: i32 = 0;
// While sysexists.h defines EX_USAGE as 64, this doesn't seem to be used much in practice but
Expand All @@ -39,5 +35,6 @@ pub(crate) fn safe_exit(code: i32) -> ! {
pub(crate) fn eq_ignore_case(left: &str, right: &str) -> bool {
left.eq_ignore_ascii_case(right)
}

#[cfg(feature = "unicode")]
pub(crate) use unicase::eq as eq_ignore_case;
13 changes: 0 additions & 13 deletions src/util/termcolor.rs

This file was deleted.

12 changes: 5 additions & 7 deletions tests/help.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2253,13 +2253,11 @@ fn option_usage_order() {

#[test]
fn about_in_subcommands_list() {
let app = App::new("about-in-subcommands-list")
.setting(AppSettings::ColorNever)
.subcommand(
App::new("sub")
.long_about("long about sub")
.about("short about sub"),
);
let app = App::new("about-in-subcommands-list").subcommand(
App::new("sub")
.long_about("long about sub")
.about("short about sub"),
);

assert!(utils::compare_output(
app,
Expand Down
2 changes: 1 addition & 1 deletion tests/macros.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ fn basic() {
(version: "0.1")
(about: "tests clap library")
(author: "Kevin K. <kbknapp@gmail.com>")
(@global_setting ColorNever)
(@global_setting UnifiedHelpMessage)
(@arg opt: -o --option +takes_value ... "tests options")
(@arg positional: index(1) "tests positionals")
(@arg flag: -f --flag ... +global "tests flags")
Expand Down

0 comments on commit fce9d21

Please sign in to comment.