Skip to content

Commit

Permalink
Merge pull request #102 from rust-cli/colorchoice_clap
Browse files Browse the repository at this point in the history
Re-use clap's colorchoice in colorchoice_clap
  • Loading branch information
epage committed Jun 20, 2023
2 parents ea3bb47 + 7f3624d commit 83458ce
Show file tree
Hide file tree
Showing 3 changed files with 50 additions and 126 deletions.
112 changes: 47 additions & 65 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion crates/colorchoice-clap/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -21,4 +21,4 @@ pre-release-replacements = [

[dependencies]
colorchoice = { version = "1.0.0", path = "../colorchoice", default-features = false }
clap = { version = "4.0.0", default-features = false, features = ["std", "derive"] }
clap = { version = "4.3.5", default-features = false, features = ["std", "derive", "color"] }
62 changes: 2 additions & 60 deletions crates/colorchoice-clap/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@
//! }
//! ```

pub use clap::ColorChoice;

/// Mixin a clap argument for colored output selection
#[derive(Copy, Clone, Default, Debug, PartialEq, Eq, clap::Args)]
#[command(about = None, long_about = None)]
Expand All @@ -36,66 +38,6 @@ impl Color {
}
}

/// Argument value for when to color output
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum ColorChoice {
Auto,
Always,
Never,
}

impl ColorChoice {
/// Report all `possible_values`
pub fn possible_values() -> impl Iterator<Item = clap::builder::PossibleValue> {
use clap::ValueEnum;
Self::value_variants()
.iter()
.filter_map(clap::ValueEnum::to_possible_value)
}

fn as_str(&self) -> &'static str {
match self {
Self::Auto => AUTO,
Self::Always => ALWAYS,
Self::Never => NEVER,
}
}
}

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

impl std::fmt::Display for ColorChoice {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.as_str().fmt(f)
}
}

impl std::str::FromStr for ColorChoice {
type Err = String;

fn from_str(s: &str) -> Result<Self, Self::Err> {
<Self as clap::ValueEnum>::from_str(s, false)
}
}

impl clap::ValueEnum for ColorChoice {
fn value_variants<'a>() -> &'a [Self] {
&[Self::Auto, Self::Always, Self::Never]
}

fn to_possible_value(&self) -> Option<clap::builder::PossibleValue> {
Some(clap::builder::PossibleValue::new(self.as_str()))
}
}

const AUTO: &str = "auto";
const ALWAYS: &str = "always";
const NEVER: &str = "never";

#[cfg(test)]
mod test {
use super::*;
Expand Down

0 comments on commit 83458ce

Please sign in to comment.