Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -444,7 +444,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
47 changes: 29 additions & 18 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,28 @@ impl<'help> App<'help> {
self
}

/// Sets the behaviour of colored output during runtime.
///
/// **NOTE:** This choice is propagated to all child subcommands.
///
/// **NOTE:** Default behaviour is [`ColorChoice::Auto`].
///
/// # Examples
///
/// ```no_run
/// # use clap::{App, ColorChoice};
/// App::new("myprog")
/// .color(ColorChoice::Never)
/// .get_matches();
/// ```
/// [`ColorChoice::Auto`]: crate::ColorChoice::Auto
#[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 @@ -1788,7 +1811,7 @@ impl<'help> App<'help> {
/// [`--help` (long)]: Arg::long_about()
pub fn print_help(&mut self) -> io::Result<()> {
self._build();
let color = self.color();
let color = self.get_color();

let p = Parser::new(self);
let mut c = Colorizer::new(false, color);
Expand All @@ -1815,7 +1838,7 @@ impl<'help> App<'help> {
/// [`--help` (long)]: Arg::long_about()
pub fn print_long_help(&mut self) -> io::Result<()> {
self._build();
let color = self.color();
let color = self.get_color();

let p = Parser::new(self);
let mut c = Colorizer::new(false, color);
Expand Down Expand Up @@ -2656,20 +2679,8 @@ impl<'help> App<'help> {
}

#[inline]
// Should we color the output?
pub(crate) fn 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
}
pub(crate) fn get_color(&self) -> ColorChoice {
self.color
}

#[inline]
Expand Down
80 changes: 1 addition & 79 deletions src/build/app/settings.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,10 +26,6 @@ bitflags! {
const NO_POS_VALUES = 1 << 17;
const NEXT_LINE_HELP = 1 << 18;
const DERIVE_DISP_ORDER = 1 << 19;
const COLORED_HELP = 1 << 20;
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 @@ -59,7 +55,7 @@ pub struct AppFlags(Flags);

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

Expand All @@ -80,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 @@ -491,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 @@ -1086,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
13 changes: 5 additions & 8 deletions src/output/fmt.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,4 @@
#[cfg(not(feature = "color"))]
use crate::util::termcolor::{Color, ColorChoice};
#[cfg(feature = "color")]
use termcolor::{Color, ColorChoice};
use crate::util::color::{Color, ColorChoice};

use std::{
fmt::{self, Display, Formatter},
Expand Down Expand Up @@ -63,12 +60,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
Loading