From 36609d00bca13a3c61bb4118c3117ecd92aa8b7d Mon Sep 17 00:00:00 2001 From: Andrew Gunnerson Date: Sun, 1 Nov 2026 23:39:01 -0500 Subject: [PATCH] Switch to winnow-args for CLI arg parsing The API is very similar to clap's API, but has better handling of argument groups and much better compile time validation. The compiled executable is also significantly smaller. Signed-off-by: Andrew Gunnerson --- Cargo.lock | 169 ++++++++++------------------------------ msd-tool/Cargo.toml | 2 +- msd-tool/src/client.rs | 53 ++++--------- msd-tool/src/daemon.rs | 6 +- msd-tool/src/main.rs | 27 ++----- msd-tool/src/sepatch.rs | 22 +++--- 6 files changed, 77 insertions(+), 202 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 9598caf..60ff498 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -17,56 +17,6 @@ version = "0.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e9d4ee0d472d1cd2e28c97dfa124b3d8d992e10eb0a035f33f5d12e3a177ba3b" -[[package]] -name = "anstream" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d" -dependencies = [ - "anstyle", - "anstyle-parse", - "anstyle-query", - "anstyle-wincon", - "colorchoice", - "is_terminal_polyfill", - "utf8parse", -] - -[[package]] -name = "anstyle" -version = "1.0.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000" - -[[package]] -name = "anstyle-parse" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e" -dependencies = [ - "utf8parse", -] - -[[package]] -name = "anstyle-query" -version = "1.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" -dependencies = [ - "windows-sys 0.61.2", -] - -[[package]] -name = "anstyle-wincon" -version = "3.0.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" -dependencies = [ - "anstyle", - "once_cell_polyfill", - "windows-sys 0.61.2", -] - [[package]] name = "anyhow" version = "1.0.104" @@ -179,52 +129,6 @@ dependencies = [ "libloading", ] -[[package]] -name = "clap" -version = "4.6.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aa8876b300ab35ba921adea3dfd70157a46249b33f95c9084ae5709785478946" -dependencies = [ - "clap_builder", - "clap_derive", -] - -[[package]] -name = "clap_builder" -version = "4.6.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ec0797fb7aeb1406c84efac526901f7ec3ead2124f946b494e72879d4b54704d" -dependencies = [ - "anstream", - "anstyle", - "clap_lex", - "strsim", -] - -[[package]] -name = "clap_derive" -version = "4.6.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f9c751b79415d4e559e3d1fcf128e09e720eb673a06d26cf6f392d37d75b66e0" -dependencies = [ - "heck", - "proc-macro2", - "quote", - "syn 3.0.6", -] - -[[package]] -name = "clap_lex" -version = "1.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1c133bc6a41be0d194c306b5506d15e6feeea7b1d6604bd3f8310dfb2ca96486" - -[[package]] -name = "colorchoice" -version = "1.0.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" - [[package]] name = "either" version = "1.18.0" @@ -275,12 +179,6 @@ version = "0.3.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e4eba85ea1d0a966a983acd07deee566e67395d2d96b6fb39e62b5a833f1eb0b" -[[package]] -name = "heck" -version = "0.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" - [[package]] name = "io-extras" version = "0.19.0" @@ -309,12 +207,6 @@ version = "2.12.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "791930b43c0d5973160d90a8f3894509f2b273430f5c5c73b668636d0287c5c0" -[[package]] -name = "is_terminal_polyfill" -version = "1.70.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" - [[package]] name = "itertools" version = "0.13.0" @@ -399,7 +291,6 @@ dependencies = [ "anyhow", "byteorder", "cap-std", - "clap", "libc", "rustix 1.1.5", "sepatch", @@ -407,6 +298,7 @@ dependencies = [ "tracing", "tracing-logcat", "tracing-subscriber", + "winnow-args", ] [[package]] @@ -443,12 +335,6 @@ version = "1.21.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" -[[package]] -name = "once_cell_polyfill" -version = "1.70.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" - [[package]] name = "pin-project-lite" version = "0.2.17" @@ -598,12 +484,6 @@ version = "1.16.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ba467056f1b547ed52077911161fc86985becbc60e8e1857c8a144dab0def891" -[[package]] -name = "strsim" -version = "0.11.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" - [[package]] name = "syn" version = "2.0.119" @@ -645,6 +525,16 @@ dependencies = [ "libc", ] +[[package]] +name = "terminal_size" +version = "0.4.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "230a1b821ccbd75b185820a1f1ff7b14d21da1e442e22c0863ea5f08771a8874" +dependencies = [ + "rustix 1.1.5", + "windows-sys 0.61.2", +] + [[package]] name = "thiserror" version = "2.0.20" @@ -748,12 +638,6 @@ version = "1.0.26" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d245f478577f809a851594d02313b640fb437e0bb33866753cff937863096954" -[[package]] -name = "utf8parse" -version = "0.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" - [[package]] name = "valuable" version = "0.1.1" @@ -922,6 +806,37 @@ version = "0.53.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d6bbff5f0aada427a1e5a6da5f1f98158182f26556f345ac9e04d36d0ebed650" +[[package]] +name = "winnow" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23b97319f7b8343df12cc98938e5c3eb436064524c8d2b4e30a1d3a36eecdf81" +dependencies = [ + "memchr", +] + +[[package]] +name = "winnow-args" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f7d83d54311d2e07890c5d453596eba319c366065630d8800cb6ecaa47a271e3" +dependencies = [ + "terminal_size", + "winnow", + "winnow-args-derive", +] + +[[package]] +name = "winnow-args-derive" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "90f6c0e613c8d3c4719038e35c8103294838e1521833642933ddf0b44be708dc" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "winx" version = "0.36.4" diff --git a/msd-tool/Cargo.toml b/msd-tool/Cargo.toml index aa5efea..37a706f 100644 --- a/msd-tool/Cargo.toml +++ b/msd-tool/Cargo.toml @@ -9,10 +9,10 @@ publish.workspace = true anyhow = "1.0.86" byteorder = "1.5.0" cap-std = "4.0.0" -clap = { version = "4.5.8", features = ["derive"] } rustix = { version = "1.1.3", features = ["fs", "net", "process", "thread"] } tracing = "0.1.40" tracing-subscriber = "0.3.18" +winnow-args = { version = "0.6.1", features = ["terminal-size"] } [dependencies.sepatch] git = "https://github.com/chenxiaolong/sepatch" diff --git a/msd-tool/src/client.rs b/msd-tool/src/client.rs index 7c8ec32..f948c1b 100644 --- a/msd-tool/src/client.rs +++ b/msd-tool/src/client.rs @@ -1,11 +1,11 @@ -// SPDX-FileCopyrightText: 2024 Andrew Gunnerson +// SPDX-FileCopyrightText: 2024-2026 Andrew Gunnerson // SPDX-License-Identifier: GPL-3.0-only use std::{fs::File, os::unix::net::UnixStream, path::PathBuf}; use anyhow::{Context, Result, bail}; use byteorder::{ReadBytesExt, WriteBytesExt}; -use clap::{CommandFactory, Parser, Subcommand, ValueEnum}; +use winnow_args::{Args, Subcommand, ValueEnum}; use crate::{ daemon, @@ -63,35 +63,11 @@ pub fn subcommand_client(cli: &ClientCli) -> Result<()> { } ClientCommand::SetMassStorage(c) => { if c.file.len() != c.type_.len() { - let (arg_id, actual_len, expected_len) = if c.file.len() < c.type_.len() { - ("file", c.file.len(), c.type_.len()) - } else { - ("type_", c.type_.len(), c.file.len()) - }; - - let mut command = SetMassStorageCli::command(); - command.build(); - - let arg = command - .get_arguments() - .find(|a| a.get_id() == arg_id) - .expect("argument not found"); - - let mut error = clap::Error::new(clap::error::ErrorKind::WrongNumberOfValues) - .with_cmd(&command); - error.insert( - clap::error::ContextKind::InvalidArg, - clap::error::ContextValue::String(arg.to_string()), + bail!( + "Number of disk images ({}) and device types ({}) must match", + c.file.len(), + c.type_.len(), ); - error.insert( - clap::error::ContextKind::ActualNumValues, - clap::error::ContextValue::Number(actual_len as isize), - ); - error.insert( - clap::error::ContextKind::ExpectedNumValues, - clap::error::ContextValue::Number(expected_len as isize), - ); - error.exit(); } let mut devices = vec![]; @@ -139,9 +115,8 @@ pub fn subcommand_client(cli: &ClientCli) -> Result<()> { (false, true) => MassStorageType::DiskRo, (false, false) => MassStorageType::DiskRw, }; - let type_value = type_.to_possible_value().unwrap(); - println!("{} -> {:?}", type_value.get_name(), device.file); + println!("{} -> {:?}", type_.name(), device.file); } } r => bail!("Invalid response: {r:?}"), @@ -153,7 +128,7 @@ pub fn subcommand_client(cli: &ClientCli) -> Result<()> { } /// Get currently active USB controller functions. -#[derive(Debug, Parser)] +#[derive(Debug, Args)] struct GetFunctionsCli; #[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)] @@ -170,19 +145,19 @@ enum MassStorageType { /// /// This command always replaces all mass storage devices. To remove all of /// them, don't specify any files. -#[derive(Debug, Parser)] +#[derive(Debug, Args)] struct SetMassStorageCli { /// Disk image or ISO file. - #[clap(short, long, value_parser)] + #[arg(short, long)] file: Vec, /// Mass storage device type. - #[clap(short, long)] + #[arg(short, long = "type")] type_: Vec, } /// Get currently active mass storage devices. -#[derive(Debug, Parser)] +#[derive(Debug, Args)] struct GetMassStorageCli; #[allow(clippy::enum_variant_names)] @@ -194,8 +169,8 @@ enum ClientCommand { } /// Send messages to daemon. -#[derive(Debug, Parser)] +#[derive(Debug, Args)] pub struct ClientCli { - #[command(subcommand)] + #[arg(subcommand)] command: ClientCommand, } diff --git a/msd-tool/src/daemon.rs b/msd-tool/src/daemon.rs index ffea5a5..8cfad47 100644 --- a/msd-tool/src/daemon.rs +++ b/msd-tool/src/daemon.rs @@ -1,4 +1,4 @@ -// SPDX-FileCopyrightText: 2024-2025 Andrew Gunnerson +// SPDX-FileCopyrightText: 2024-2026 Andrew Gunnerson // SPDX-License-Identifier: GPL-3.0-only //! This module implements the daemon that runs as the system user and listens @@ -33,12 +33,12 @@ use std::os::linux::net::SocketAddrExt; use anyhow::{Context, Result, anyhow, bail}; use byteorder::{ReadBytesExt, WriteBytesExt}; -use clap::Parser; use rustix::{ fs::{FileType, Gid, Mode, Uid}, thread::{CapabilitySet, CapabilitySets}, }; use tracing::{debug, error, info, info_span, warn}; +use winnow_args::Args; use crate::{ message::{ @@ -461,5 +461,5 @@ pub fn subcommand_daemon(_cli: &DaemonCli) -> Result<()> { } /// Run daemon. -#[derive(Debug, Parser)] +#[derive(Debug, Args)] pub struct DaemonCli; diff --git a/msd-tool/src/main.rs b/msd-tool/src/main.rs index 9027731..e4f9348 100644 --- a/msd-tool/src/main.rs +++ b/msd-tool/src/main.rs @@ -1,4 +1,4 @@ -// SPDX-FileCopyrightText: 2024 Andrew Gunnerson +// SPDX-FileCopyrightText: 2024-2026 Andrew Gunnerson // SPDX-License-Identifier: GPL-3.0-only mod client; @@ -9,13 +9,12 @@ mod usb; mod util; use std::{ - fmt, io::{self, IsTerminal}, process::ExitCode, }; -use clap::{Parser, Subcommand, ValueEnum}; use tracing::{Level, error}; +use winnow_args::{Args, Subcommand, ValueEnum}; #[allow(clippy::enum_variant_names)] #[derive(Debug, Subcommand)] @@ -32,31 +31,17 @@ pub enum LogTarget { Logcat, } -impl Default for LogTarget { - fn default() -> Self { - Self::Stderr - } -} - -impl fmt::Display for LogTarget { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.write_str(self.to_possible_value().ok_or(fmt::Error)?.get_name()) - } -} - -const HEADING: &str = "Global options"; - -#[derive(Debug, Parser)] +#[derive(Debug, Args)] struct Cli { - #[command(subcommand)] + #[arg(subcommand)] command: Command, /// Where to output log messages. - #[arg(long, global = true, value_name = "TARGET", default_value_t, help_heading = HEADING)] + #[arg(long, global, value_name = "TARGET", default = "stderr")] pub log_target: LogTarget, /// Lowest log message severity to output. - #[arg(long, global = true, value_name = "LEVEL", default_value_t = Level::INFO, help_heading = HEADING)] + #[arg(long, global, value_name = "LEVEL", from_str, default = "info")] pub log_level: Level, } diff --git a/msd-tool/src/sepatch.rs b/msd-tool/src/sepatch.rs index 44d19ed..abdca04 100644 --- a/msd-tool/src/sepatch.rs +++ b/msd-tool/src/sepatch.rs @@ -1,4 +1,4 @@ -// SPDX-FileCopyrightText: 2024-2025 Andrew Gunnerson +// SPDX-FileCopyrightText: 2024-2026 Andrew Gunnerson // SPDX-License-Identifier: GPL-3.0-only use std::{ @@ -9,8 +9,8 @@ use std::{ }; use anyhow::{Context, Result, anyhow, bail}; -use clap::{Args, Parser}; use sepatch::{PolicyDb, RuleAction}; +use winnow_args::Args; fn read_policy(path: &Path) -> Result { let data = fs::read(path).with_context(|| format!("Failed to open for reading: {path:?}"))?; @@ -493,14 +493,14 @@ pub fn subcommand_sepatch(cli: &SepatchCli) -> Result<()> { } #[derive(Debug, Args)] -#[group(required = true, multiple = false)] +#[arg(group("source", required))] struct SourceGroup { /// Source policy file. - #[arg(short, long, value_parser, value_name = "FILE")] + #[arg(short, long, value_name = "FILE", group = "source")] source: Option, /// Use currently loaded policy as source. - #[arg(short = 'S', long)] + #[arg(short = 'S', long, group = "source")] source_kernel: bool, } @@ -517,14 +517,14 @@ impl SourceGroup { } #[derive(Debug, Args)] -#[group(required = true, multiple = false)] +#[arg(group("target", required))] struct TargetGroup { /// Target policy file. - #[arg(short, long, value_parser, value_name = "FILE")] + #[arg(short, long, value_name = "FILE", group = "target")] target: Option, /// Load patched policy into kernel. - #[arg(short = 'T', long)] + #[arg(short = 'T', long, group = "target")] target_kernel: bool, } @@ -541,12 +541,12 @@ impl TargetGroup { } /// Patch SELinux policy file. -#[derive(Debug, Parser)] +#[derive(Debug, Args)] pub struct SepatchCli { - #[command(flatten)] + #[arg(flatten)] source: SourceGroup, - #[command(flatten)] + #[arg(flatten)] target: TargetGroup, /// Remove dontaudit/dontauditxperm rules.