| 1 |
// SPDX-FileCopyrightText: Peter Pentchev <[email protected]> |
| 2 |
// SPDX-License-Identifier: BSD-2-Clause |
| 3 |
//! A command-line tool used for querying a program for its features. |
| 4 |
|
| 5 |
use std::env; |
| 6 |
use std::process::{ExitCode, Termination}; |
| 7 |
use std::str::FromStr; |
| 8 |
|
| 9 |
use anyhow::{Context as _, Error, Result, anyhow, bail}; |
| 10 |
use clap::{CommandFactory as _, Parser as _}; |
| 11 |
use clap_derive::Parser; |
| 12 |
|
| 13 |
use feature_check::defs::{Config, DEFAULT_OPTION_NAME, DEFAULT_PREFIX, Mode, Obtained}; |
| 14 |
use feature_check::expr::{self as fexpr, CalcResult}; |
| 15 |
use feature_check::obtain; |
| 16 |
|
| 17 |
/// The list of the program's features. |
| 18 |
const FEATURES: [(&str, &str); 4] = [ |
| 19 |
("feature-check", env!("CARGO_PKG_VERSION")), |
| 20 |
("single", "1.0"), |
| 21 |
("list", "1.0"), |
| 22 |
("simple", "1.0"), |
| 23 |
]; |
| 24 |
|
| 25 |
/// The format in which the queried program's features should be displayed. |
| 26 |
#[derive(Debug, Clone, Copy)] |
| 27 |
enum OutputFormat { |
| 28 |
/// Display the feature list as a JSON object. |
| 29 |
Json, |
| 30 |
/// Display the feature list as a series of tab-separated fields on separate lines. |
| 31 |
Tsv, |
| 32 |
} |
| 33 |
|
| 34 |
impl OutputFormat { |
| 35 |
/// The string used to request JSON output. |
| 36 |
const JSON_NAME: &'static str = "json"; |
| 37 |
/// The string used to request tab-separated values output. |
| 38 |
const TSV_NAME: &'static str = "tsv"; |
| 39 |
} |
| 40 |
|
| 41 |
impl FromStr for OutputFormat { |
| 42 |
type Err = Error; |
| 43 |
|
| 44 |
fn from_str(value: &str) -> Result<Self, Self::Err> { |
| 45 |
match value { |
| 46 |
Self::JSON_NAME => Ok(Self::Json), |
| 47 |
Self::TSV_NAME => Ok(Self::Tsv), |
| 48 |
other => Err(anyhow!("Unrecognized output format '{other}'")), |
| 49 |
} |
| 50 |
} |
| 51 |
} |
| 52 |
|
| 53 |
impl AsRef<str> for OutputFormat { |
| 54 |
fn as_ref(&self) -> &str { |
| 55 |
match *self { |
| 56 |
Self::Json => Self::JSON_NAME, |
| 57 |
Self::Tsv => Self::TSV_NAME, |
| 58 |
} |
| 59 |
} |
| 60 |
} |
| 61 |
|
| 62 |
/// Runtime configuration for the feature-check command-line tool. |
| 63 |
#[derive(Debug)] |
| 64 |
struct MainConfig { |
| 65 |
/// The library crate's configuration settings. |
| 66 |
config: Config, |
| 67 |
/// The selected output format. |
| 68 |
output_format: OutputFormat, |
| 69 |
/// Display the version strings of the features, or only their names? |
| 70 |
show_version: bool, |
| 71 |
} |
| 72 |
|
| 73 |
/// Has the [`parse_args`] function managed to handle e.g. `--features` or `--version` output, |
| 74 |
/// or should the real "query a program's features" work be done? |
| 75 |
#[derive(Debug)] |
| 76 |
enum MainMode { |
| 77 |
/// Query a program's features. |
| 78 |
Do(MainConfig), |
| 79 |
/// Requested action already taken successfully. |
| 80 |
Handled, |
| 81 |
} |
| 82 |
|
| 83 |
/// What should the program return? |
| 84 |
#[derive(Debug)] |
| 85 |
enum MainResult { |
| 86 |
Ok, |
| 87 |
FeatureNotSupported, |
| 88 |
Error, |
| 89 |
} |
| 90 |
|
| 91 |
impl Termination for MainResult { |
| 92 |
fn report(self) -> ExitCode { |
| 93 |
ExitCode::from(match self { |
| 94 |
Self::Ok => 0, |
| 95 |
Self::FeatureNotSupported => 1, |
| 96 |
Self::Error => 2, |
| 97 |
}) |
| 98 |
} |
| 99 |
} |
| 100 |
|
| 101 |
#[derive(Debug, Parser)] |
| 102 |
#[clap(disable_help_flag(true))] |
| 103 |
#[expect(clippy::struct_excessive_bools, reason = "we do take a lot of options")] |
| 104 |
struct Cli { |
| 105 |
/// Display `feature-check` usage information and exit. |
| 106 |
#[clap(short, long)] |
| 107 |
help: bool, |
| 108 |
|
| 109 |
/// List the features supported by `feature-check` itself and exit. |
| 110 |
#[clap(long)] |
| 111 |
features: bool, |
| 112 |
|
| 113 |
/// List the features supported by the specified program. |
| 114 |
#[clap(short)] |
| 115 |
list: bool, |
| 116 |
|
| 117 |
/// Specify the query-features option to pass to the program. |
| 118 |
#[clap(short = 'O', default_value = DEFAULT_OPTION_NAME, allow_hyphen_values = true)] |
| 119 |
optname: String, |
| 120 |
|
| 121 |
/// Specify the output format for the list of features. |
| 122 |
#[clap(short = 'o', default_value = OutputFormat::TSV_NAME, allow_hyphen_values = true)] |
| 123 |
output_format: OutputFormat, |
| 124 |
|
| 125 |
/// The features prefix in the program output. |
| 126 |
#[clap(short = 'P', default_value = DEFAULT_PREFIX, allow_hyphen_values = true)] |
| 127 |
prefix: String, |
| 128 |
|
| 129 |
/// Output the feature version when querying a single feature". |
| 130 |
#[clap(short = 'v')] |
| 131 |
show_version: bool, |
| 132 |
|
| 133 |
/// Display `feature-check` version information and exit. |
| 134 |
#[clap(short = 'V', long)] |
| 135 |
version: bool, |
| 136 |
|
| 137 |
/// The feature name or `feature op version` expression to check for. |
| 138 |
expressions: Vec<String>, |
| 139 |
} |
| 140 |
|
| 141 |
/// Handle `--version`, `--help`, and/or `--features`. |
| 142 |
#[expect(clippy::print_stdout, reason = "this is the whole point")] |
| 143 |
fn version_help_features<F: FnOnce() -> String>( |
| 144 |
opt_version: bool, |
| 145 |
opt_help: bool, |
| 146 |
opt_features: bool, |
| 147 |
get_help: F, |
| 148 |
) -> Result<bool> { |
| 149 |
if opt_version { |
| 150 |
let version = FEATURES |
| 151 |
.iter() |
| 152 |
.find_map(|&(name, version)| (name == "feature-check").then_some(version)) |
| 153 |
.with_context(|| { |
| 154 |
format!( |
| 155 |
"Internal error: 'feature-check' not found in the features list: {FEATURES:?}", |
| 156 |
) |
| 157 |
})?; |
| 158 |
println!("feature-check {version}"); |
| 159 |
} |
| 160 |
|
| 161 |
if opt_help { |
| 162 |
println!("{usage}", usage = get_help()); |
| 163 |
} |
| 164 |
|
| 165 |
if opt_features { |
| 166 |
let features: Vec<String> = FEATURES |
| 167 |
.iter() |
| 168 |
.map(|&(name, version)| format!("{name}={version}")) |
| 169 |
.collect(); |
| 170 |
println!("Features: {features}", features = features.join(" ")); |
| 171 |
} |
| 172 |
|
| 173 |
Ok(opt_version || opt_help || opt_features) |
| 174 |
} |
| 175 |
|
| 176 |
/// Parse the command-line arguments, handle `--help`, `--version`, and `--features`. |
| 177 |
fn parse_args() -> Result<MainMode> { |
| 178 |
let opts = Cli::parse(); |
| 179 |
let get_help = || format!("{usage}", usage = Cli::command().render_long_help()); |
| 180 |
|
| 181 |
if version_help_features(opts.version, opts.help, opts.features, get_help)? { |
| 182 |
return Ok(MainMode::Handled); |
| 183 |
} |
| 184 |
|
| 185 |
let (program, opts_expr) = opts.expressions.split_first().with_context(get_help)?; |
| 186 |
let build = |mode| { |
| 187 |
Ok(MainMode::Do(MainConfig { |
| 188 |
config: Config::default() |
| 189 |
.with_option_name(opts.optname) |
| 190 |
.with_prefix(opts.prefix) |
| 191 |
.with_program(program.clone()) |
| 192 |
.with_mode(mode), |
| 193 |
output_format: opts.output_format, |
| 194 |
show_version: opts.show_version, |
| 195 |
})) |
| 196 |
}; |
| 197 |
|
| 198 |
if opts_expr.is_empty() { |
| 199 |
if !opts.list { |
| 200 |
bail!(get_help()); |
| 201 |
} |
| 202 |
build(Mode::List) |
| 203 |
} else { |
| 204 |
if opts.list { |
| 205 |
bail!(get_help()); |
| 206 |
} |
| 207 |
let expr = opts_expr.join(" "); |
| 208 |
let mode = fexpr::parse(&expr).context("Invalid expression specified")?; |
| 209 |
build(mode) |
| 210 |
} |
| 211 |
} |
| 212 |
|
| 213 |
/// Obtain the features of a program, display them as requested. |
| 214 |
#[expect(clippy::print_stdout, reason = "this is the whole point")] |
| 215 |
fn run(config: MainConfig) -> Result<MainResult> { |
| 216 |
Ok( |
| 217 |
match obtain::obtain_features(&config.config) |
| 218 |
.context("Could not obtain the program's list of features")? |
| 219 |
{ |
| 220 |
Obtained::Failed(_) | Obtained::NotSupported => MainResult::Error, |
| 221 |
Obtained::Features(features) => match config.config.mode { |
| 222 |
Mode::Single(feature) => { |
| 223 |
let value = feature |
| 224 |
.get_value(&features) |
| 225 |
.context("Could not evaluate the expression")?; |
| 226 |
#[expect( |
| 227 |
clippy::wildcard_enum_match_arm, |
| 228 |
reason = "we do only expect two outcomes" |
| 229 |
)] |
| 230 |
match value { |
| 231 |
CalcResult::Version(ver) => { |
| 232 |
if config.show_version { |
| 233 |
println!("{ver}", ver = ver.as_ref()); |
| 234 |
} |
| 235 |
MainResult::Ok |
| 236 |
} |
| 237 |
CalcResult::Null => MainResult::FeatureNotSupported, |
| 238 |
other => bail!("single.get_value() returned {other:?}"), |
| 239 |
} |
| 240 |
} |
| 241 |
Mode::List => match config.output_format { |
| 242 |
OutputFormat::Tsv => { |
| 243 |
let mut res: Vec<String> = features |
| 244 |
.iter() |
| 245 |
.map(|(name, value)| format!("{name}\t{value}")) |
| 246 |
.collect(); |
| 247 |
res.sort(); |
| 248 |
println!("{res}", res = res.join("\n")); |
| 249 |
MainResult::Ok |
| 250 |
} |
| 251 |
OutputFormat::Json => { |
| 252 |
println!( |
| 253 |
"{features}", |
| 254 |
features = serde_json::to_string_pretty(&features) |
| 255 |
.context("Internal error: could not serialize the features data")? |
| 256 |
); |
| 257 |
MainResult::Ok |
| 258 |
} |
| 259 |
}, |
| 260 |
Mode::Simple(expr) => { |
| 261 |
let value = expr |
| 262 |
.get_value(&features) |
| 263 |
.context("Could not evaluate the expression")?; |
| 264 |
#[expect( |
| 265 |
clippy::wildcard_enum_match_arm, |
| 266 |
reason = "we do only expect two outcomes" |
| 267 |
)] |
| 268 |
match value { |
| 269 |
CalcResult::Bool(true) => MainResult::Ok, |
| 270 |
CalcResult::Bool(false) => MainResult::FeatureNotSupported, |
| 271 |
other => bail!("parse_simple().get_value() returned {other:?}"), |
| 272 |
} |
| 273 |
} |
| 274 |
other => bail!("Internal error: unexpected mode {other:?} after obtain_features()"), |
| 275 |
}, |
| 276 |
other => bail!("Internal error: obtain_features() returned something weird: {other:?}"), |
| 277 |
}, |
| 278 |
) |
| 279 |
} |
| 280 |
|
| 281 |
fn main() -> Result<MainResult> { |
| 282 |
Ok(match parse_args()? { |
| 283 |
MainMode::Handled => MainResult::Ok, |
| 284 |
MainMode::Do(config) => run(config)?, |
| 285 |
}) |
| 286 |
} |