Skip to main content

akv_cli/
lib.rs

1// Copyright 2025 Heath Stewart.
2// Licensed under the MIT License. See LICENSE.txt in the project root for license information.
3
4// cspell:ignore docsrs
5#![cfg_attr(docsrs, feature(doc_cfg))]
6#![deny(missing_docs)]
7#![doc = include_str!("../README.md")]
8
9pub mod cache;
10#[cfg(feature = "color")]
11pub mod color;
12mod error;
13pub mod jose;
14pub mod json;
15pub mod parsing;
16
17use std::borrow::Cow;
18
19pub use error::*;
20
21/// Whether to write color attributes to the terminal.
22#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
23pub enum ColorMode {
24    /// Write color attributes if `stdout` is a TTY and color is not otherwise disabled.
25    #[default]
26    Auto,
27
28    /// Always write color attributes.
29    Always,
30
31    /// Never write color attributes.
32    Never,
33}
34
35impl ColorMode {
36    /// Whether ANSI color is enabled.
37    pub fn enabled(&self) -> bool {
38        #[cfg(feature = "color")]
39        {
40            use yansi::Condition;
41
42            match self {
43                ColorMode::Always => true,
44                ColorMode::Auto => Condition::tty_and_color(),
45                ColorMode::Never => false,
46            }
47        }
48
49        #[cfg(not(feature = "color"))]
50        false
51    }
52
53    /// Gets a [`Style`] based on this `ColorMode`.
54    pub fn style(&self) -> Style {
55        Style(*self)
56    }
57}
58
59/// Styles text depending on the [`ColorMode`].
60pub struct Style(#[cfg_attr(not(feature = "color"), allow(dead_code))] ColorMode);
61
62impl Style {
63    /// Conditionally colors the `message`.
64    pub fn error<'a>(&self, message: &'a str) -> Cow<'a, str> {
65        #[cfg(feature = "color")]
66        {
67            use yansi::{Color, Paint, Style};
68
69            static STYLE: Style = Color::Red.bold();
70
71            if self.0.enabled() {
72                return Cow::Owned(message.paint(STYLE).to_string());
73            }
74
75            Cow::Borrowed(message)
76        }
77
78        #[cfg(not(feature = "color"))]
79        Cow::Borrowed(message)
80    }
81}