Skip to main content

ctl_core/
flags.rs

1//! The flags every CLI built on ctl-core shares, as Clap structs to flatten
2//! into a parser.
3//!
4//! - [`OutputArgs`] adds `-f/--format`, `-c/--color`, `--no-color`, and
5//!   `-q/--quiet`. [`FormatArgs`], [`FormatLong`], and [`ColorLong`] are the
6//!   variants for a CLI that already owns `-c` or `-f`.
7//! - [`DryRunArgs`] adds `-n/--dry-run`, with `--preview` as an alias.
8//! - [`EnvPrefix`] binds every long option to an environment variable.
9//! - [`chassis_warnings`] and [`warn_opposites`] find repeated or contradictory
10//!   flags, which [`emit_warnings`] prints.
11//!
12//! ```
13//! use clap::Parser;
14//! use ctl_core::color::ColorMode;
15//! use ctl_core::flags::OutputArgs;
16//! use ctl_core::format::OutputFormat;
17//!
18//! #[derive(Parser)]
19//! struct Cli {
20//!     #[command(flatten)]
21//!     output: OutputArgs,
22//! }
23//!
24//! let cli = Cli::parse_from(["toy", "--format", "json", "--no-color"]);
25//! assert_eq!(cli.output.format, OutputFormat::Json);
26//! assert_eq!(cli.output.color(), ColorMode::Never);
27//! ```
28
29mod color;
30mod dry_run;
31mod env;
32mod output;
33mod warn;
34
35pub use color::ColorLong;
36pub use dry_run::DryRunArgs;
37pub use env::{EnvPrefix, env_under_flags};
38pub use output::{FormatArgs, FormatLong, OutputArgs};
39pub use warn::{FlagClash, FlagWarning, chassis_warnings, emit_warnings, warn_opposites};
40
41use crate::color::ColorMode;
42
43/// The colour mode in force: [`ColorMode::Never`] when `no_color` is set,
44/// otherwise `color`.
45#[must_use]
46pub fn resolve_color(color: ColorMode, no_color: bool) -> ColorMode {
47    if no_color { ColorMode::Never } else { color }
48}
49
50/// The value of a `--x`/`--no-x` pair declared with Clap's `overrides_with`
51/// both ways: `on`, the `--x` flag, returned unchanged.
52///
53/// Clap clears the flag that came first, so `on` already holds the answer.
54/// The call names that rule at the call site, so a reader does not look for
55/// a missing check of `--no-x`.
56#[must_use]
57pub fn switch(on: bool) -> bool {
58    on
59}