use std::fmt;
use std::str::FromStr;
mod data {
#![cfg_attr(
feature = "schema",
expect(
clippy::disallowed_macros,
reason = "schemars' JsonSchema derive expands concat!"
)
)]
#[cfg_attr(
any(feature = "view", feature = "help"),
doc = "",
doc = "[`ctl_term::ColorMode`]: crate::term::ColorMode",
doc = "[`Console`]: crate::term::Console"
)]
#[cfg_attr(
not(any(feature = "view", feature = "help")),
doc = "",
doc = "[`ctl_term::ColorMode`]: crate#cargo-features",
doc = "[`Console`]: crate#cargo-features"
)]
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
#[cfg_attr(feature = "cli", derive(clap::ValueEnum))]
#[cfg_attr(feature = "json", derive(serde::Deserialize, serde::Serialize))]
#[cfg_attr(feature = "json", serde(rename_all = "lowercase"))]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub enum ColorMode {
#[default]
Auto,
Always,
Never,
}
}
pub use data::ColorMode;
#[cfg(any(feature = "view", feature = "help"))]
impl From<ColorMode> for ctl_term::ColorMode {
fn from(mode: ColorMode) -> Self {
match mode {
ColorMode::Auto => Self::Auto,
ColorMode::Always => Self::Always,
ColorMode::Never => Self::Never,
}
}
}
impl FromStr for ColorMode {
type Err = ParseColorError;
fn from_str(value: &str) -> Result<Self, Self::Err> {
match value {
"auto" => Ok(Self::Auto),
"always" => Ok(Self::Always),
"never" => Ok(Self::Never),
_ => Err(ParseColorError),
}
}
}
impl fmt::Display for ColorMode {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(match self {
Self::Auto => "auto",
Self::Always => "always",
Self::Never => "never",
})
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct ParseColorError;
impl fmt::Display for ParseColorError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("expected auto, always, or never")
}
}
impl std::error::Error for ParseColorError {}
#[cfg(test)]
mod tests {
use indoc::indoc;
use super::ColorMode;
#[test]
fn parse_rejects_junk() {
let doc = indoc! {"
auto
always
never
"};
for line in doc.lines() {
assert!(line.parse::<ColorMode>().is_ok(), "{line}");
}
assert!("rainbow".parse::<ColorMode>().is_err());
}
}