Function yansi::whenever

source ·
pub fn whenever(condition: Condition)
Expand description

Dynamically enables and disables styling globally based on condition.

condition is expected to be fast: it is checked dynamically, each time a Painted value is displayed.

§Example

use yansi::Condition;

yansi::whenever(Condition::STDOUT_IS_TTY);

// On each styling, check if we have TTYs.
yansi::whenever(Condition::STDOUTERR_ARE_TTY_LIVE);

// Check `NO_COLOR`, `CLICOLOR`, and if we have TTYs.
const HAVE_COLOR: Condition = Condition(|| {
    std::env::var_os("NO_COLOR").is_none()
        && (Condition::CLICOLOR_LIVE)()
        && Condition::stdouterr_are_tty_live()
});

// This will call `HAVE_COLOR` every time styling is needed. In this
// example, this means that env vars will be checked on each styling.
yansi::whenever(HAVE_COLOR);

// This instead caches the value (checking `env()` exactly once, now).
yansi::whenever(Condition::cached((HAVE_COLOR)()));

// Is identical to this:
match (HAVE_COLOR)() {
    true => yansi::enable(),
    false => yansi::disable(),
}