1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290
//! Data structures for command line arguments parsing.
use std::{env, iter};
use cargo_metadata::{camino::Utf8PathBuf, Metadata, Package};
use clap::ArgAction;
use eyre::eyre;
use tracing::Level;
use crate::{
workspace::{self, FeatureOption, MetadataExt, PackageExt},
Result,
};
/// Commmand line arguments to control log verbosity level.
///
/// # Examples
///
/// To get `--quiet` (`-q`) and `--verbose` (or `-v`) flags through your entire
/// program, just `flattern` this struct:
///
/// ```rust
/// use cli_xtask::{args::Verbosity, clap};
///
/// #[derive(Debug, clap::Parser)]
/// struct App {
/// #[clap(flatten)]
/// verbosity: Verbosity,
/// }
/// ```
///
/// The [`LogLevel`](crate::tracing::Level) values returned by
/// [`Verbosity::get()`](crate::args::Verbosity::get) are:
///
/// * `None`: `-qqq`
/// * `Some(Level::ERROR)`: `-qq`
/// * `Some(Level::WARN)`: `-q`
/// * `Some(Level::INFO)`: no arguments
/// * `Some(Level::DEBUG)`: `-v`
/// * `Some(Level::TRACE)`: `-vv`
#[derive(Debug, Clone, Default, clap::Args)]
pub struct Verbosity {
/// More output per occurrence
#[clap(long, short = 'v', action = ArgAction::Count, global = true)]
verbose: u8,
/// Less output per occurrence
#[clap(
long,
short = 'q',
action = ArgAction::Count,
global = true,
conflicts_with = "verbose"
)]
quiet: u8,
}
impl Verbosity {
/// Returns the log verbosity level.
pub fn get(&self) -> Option<Level> {
let level = i8::try_from(self.verbose).unwrap_or(i8::MAX)
- i8::try_from(self.quiet).unwrap_or(i8::MAX);
match level {
i8::MIN..=-3 => None,
-2 => Some(Level::ERROR),
-1 => Some(Level::WARN),
0 => Some(Level::INFO),
1 => Some(Level::DEBUG),
2..=i8::MAX => Some(Level::TRACE),
}
}
}
/// Command line arguments to specify the environment variables to set for the
/// subcommand.
#[derive(Debug, Clone, Default, clap::Args)]
pub struct EnvArgs {
/// Environment variables to set for the subcommand.
#[clap(
long,
short = 'e',
value_name = "KEY>=<VALUE", // hack
value_parser = EnvArgs::parse_parts,
)]
pub env: Vec<(String, String)>,
}
impl EnvArgs {
/// Creates a new `EnvArgs` from an iterator of `(key, value)` pairs.
pub fn new(iter: impl IntoIterator<Item = (impl Into<String>, impl Into<String>)>) -> Self {
Self {
env: iter
.into_iter()
.map(|(k, v)| (k.into(), v.into()))
.collect(),
}
}
fn parse_parts(s: &str) -> Result<(String, String)> {
match s.split_once('=') {
Some((key, value)) => Ok((key.into(), value.into())),
None => Ok((s.into(), "".into())),
}
}
}
/// Command line arguments to specify the workspaces where the subcommand runs
/// on.
#[derive(Debug, Clone, Default, clap::Args)]
#[non_exhaustive]
pub struct WorkspaceArgs {
/// Same as `--all-workspaces --workspace --each-feature`.
#[clap(long)]
pub exhaustive: bool,
/// Run the subcommand on all workspaces.
#[clap(long, conflicts_with = "exhaustive")]
pub all_workspaces: bool,
/// Run the subcommand on each workspace other than the current workspace.
#[clap(long)]
pub exclude_current_workspace: bool,
}
impl WorkspaceArgs {
/// `WorkspaceArgs` value with `--exhaustive` flag enabled.
pub const EXHAUSTIVE: Self = Self {
exhaustive: true,
all_workspaces: false,
exclude_current_workspace: false,
};
/// Returns the workspaces to run the subcommand on.
pub fn workspaces(&self) -> impl Iterator<Item = &'static Metadata> {
let workspaces = if self.exhaustive || self.all_workspaces {
if self.exclude_current_workspace {
&workspace::all()[1..]
} else {
workspace::all()
}
} else if self.exclude_current_workspace {
&workspace::all()[..0]
} else {
&workspace::all()[..1]
};
workspaces.iter()
}
}
/// Command line arguments to specify the packages to run the subcommand for.
#[derive(Debug, Clone, Default, clap::Args)]
#[non_exhaustive]
pub struct PackageArgs {
/// Command line arguments to specify the workspaces where the subcommand
/// runs on.
#[clap(flatten)]
pub workspace_args: WorkspaceArgs,
/// Run the subcommand for all packages in the workspace
#[clap(long, conflicts_with = "exhaustive")]
pub workspace: bool,
/// Package name to run the subcommand for
#[clap(long = "package", short = 'p', conflicts_with = "exhaustive")]
pub package: Option<String>,
}
impl PackageArgs {
/// `PackageArgs` value with `--exhaustive` flag enabled.
pub const EXHAUSTIVE: Self = Self {
workspace_args: WorkspaceArgs::EXHAUSTIVE,
workspace: false,
package: None,
};
/// Returns the packages to run the subcommand on.
pub fn packages(
&self,
) -> impl Iterator<Item = Result<(&'static Metadata, &'static Package)>> + '_ {
self.workspace_args
.workspaces()
.map(move |workspace| {
let packages = if self.workspace_args.exhaustive || self.workspace {
workspace.workspace_packages()
} else if let Some(name) = &self.package {
let pkg = workspace
.workspace_package_by_name(name)
.ok_or_else(|| eyre!("Package not found"))?;
vec![pkg]
} else {
let current_dir = Utf8PathBuf::try_from(env::current_dir()?)?;
let pkg = workspace
.workspace_package_by_path(¤t_dir)
.or_else(|| workspace.root_package())
.ok_or_else(|| eyre!("Package not found"))?;
vec![pkg]
};
let it = packages
.into_iter()
.map(move |package| (workspace, package));
Ok(it)
})
.flat_map(|res| -> Box<dyn Iterator<Item = _>> {
match res {
Ok(it) => Box::new(it.map(Ok)),
Err(err) => Box::new(iter::once(Err(err))),
}
})
}
}
/// Command line arguments to specify the features to run the subcommand with.
#[derive(Debug, Clone, Default, clap::Args)]
#[non_exhaustive]
pub struct FeatureArgs {
/// Command line arguments to specify the packages to run the subcommand
/// for.
#[clap(flatten)]
pub package_args: PackageArgs,
/// Run the subcommand with each feature enabled
#[clap(long, conflicts_with = "exhaustive")]
pub each_feature: bool,
}
impl FeatureArgs {
/// `FeatureArgs` value with `--exhaustive` flag enabled.
pub const EXHAUSTIVE: Self = Self {
package_args: PackageArgs::EXHAUSTIVE,
each_feature: false,
};
/// Returns the features to run the subcommand with.
pub fn features(
&self,
) -> impl Iterator<
Item = Result<(
&'static Metadata,
&'static Package,
Option<FeatureOption<'static>>,
)>,
> + '_ {
self.package_args
.packages()
.map(move |res| {
res.map(move |(workspace, package)| -> Box<dyn Iterator<Item = _>> {
let exhaustive = self.package_args.workspace_args.exhaustive;
if (exhaustive || self.each_feature) && !package.features.is_empty() {
Box::new(
package
.each_feature()
.map(move |feature| (workspace, package, Some(feature))),
)
} else {
Box::new(iter::once((workspace, package, None)))
}
})
})
.flat_map(|res| -> Box<dyn Iterator<Item = _>> {
match res {
Ok(it) => Box::new(it.map(Ok)),
Err(err) => Box::new(iter::once(Err(err))),
}
})
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn verbosity() {
use clap::Parser;
#[derive(Debug, clap::Parser)]
struct App {
#[clap(flatten)]
verbosity: Verbosity,
}
let cases: &[(&[&str], Option<Level>)] = &[
(&["-qqqq"], None),
(&["-qqq"], None),
(&["-qq"], Some(Level::ERROR)),
(&["-q"], Some(Level::WARN)),
(&[], Some(Level::INFO)),
(&["-v"], Some(Level::DEBUG)),
(&["-vv"], Some(Level::TRACE)),
];
for (arg, level) in cases {
let args = App::parse_from(["app"].into_iter().chain(arg.iter().copied()));
assert_eq!(args.verbosity.get(), *level, "arg: {}", arg.join(" "));
}
}
}