| 1 |
/// A re-implementation of GnuPG's command-line parser. |
| 2 |
|
| 3 |
use std::{ |
| 4 |
collections::BTreeSet, |
| 5 |
fmt::Debug, |
| 6 |
io::{self, BufRead, BufReader}, |
| 7 |
path::Path, |
| 8 |
}; |
| 9 |
|
| 10 |
pub mod flags; |
| 11 |
use flags::*; |
| 12 |
#[macro_use] |
| 13 |
pub mod options; |
| 14 |
pub mod utils; |
| 15 |
|
| 16 |
/// A command or option with long option, flags, and description. |
| 17 |
#[derive(Debug)] |
| 18 |
pub struct Opt<T: Debug + Into<isize>> { |
| 19 |
pub short_opt: T, |
| 20 |
pub long_opt: &'static str, |
| 21 |
pub flags: u32, |
| 22 |
pub description: &'static str, |
| 23 |
} |
| 24 |
|
| 25 |
#[derive(Debug, PartialEq, Eq)] |
| 26 |
pub enum Argument<T: Debug> { |
| 27 |
Option(T, Value), |
| 28 |
Positional(String), |
| 29 |
} |
| 30 |
|
| 31 |
impl<T: Debug> Argument<T> { |
| 32 |
/// Returns the option and value, if any. |
| 33 |
pub fn option(&self) -> Option<(&T, &Value)> { |
| 34 |
match self { |
| 35 |
Argument::Option(t, v) => Some((t, v)), |
| 36 |
Argument::Positional(_) => None, |
| 37 |
} |
| 38 |
} |
| 39 |
} |
| 40 |
|
| 41 |
/// Some arguments take a value. |
| 42 |
#[derive(Debug, Clone, PartialEq, Eq, Hash)] |
| 43 |
pub enum Value { |
| 44 |
Int(i64), |
| 45 |
String(String), |
| 46 |
UInt(u64), |
| 47 |
None, |
| 48 |
} |
| 49 |
|
| 50 |
impl Value { |
| 51 |
/// Returns the kind of this value as human-readable string. |
| 52 |
fn kind(&self) -> &'static str { |
| 53 |
match self { |
| 54 |
Value::Int(_) => "int", |
| 55 |
Value::String(_) => "string", |
| 56 |
Value::UInt(_) => "unsigned int", |
| 57 |
Value::None => "none", |
| 58 |
} |
| 59 |
} |
| 60 |
|
| 61 |
/// Returns the integer value, if applicable. |
| 62 |
pub fn as_int(&self) -> Result<i64> { |
| 63 |
if let Value::Int(v) = self { |
| 64 |
Ok(*v) |
| 65 |
} else { |
| 66 |
Err(Error::ConversionFailed(self.kind(), "int")) |
| 67 |
} |
| 68 |
} |
| 69 |
|
| 70 |
/// Returns the string value, if applicable. |
| 71 |
pub fn as_str(&self) -> Result<&str> { |
| 72 |
if let Value::String(v) = self { |
| 73 |
Ok(v) |
| 74 |
} else { |
| 75 |
Err(Error::ConversionFailed(self.kind(), "string")) |
| 76 |
} |
| 77 |
} |
| 78 |
|
| 79 |
/// Returns the unsigned integer value, if applicable. |
| 80 |
pub fn as_uint(&self) -> Result<u64> { |
| 81 |
if let Value::UInt(v) = self { |
| 82 |
Ok(*v) |
| 83 |
} else { |
| 84 |
Err(Error::ConversionFailed(self.kind(), "unsigned int")) |
| 85 |
} |
| 86 |
} |
| 87 |
} |
| 88 |
|
| 89 |
/// Arguments can be read from the command line or a file. |
| 90 |
pub struct Parser<T: Copy + Debug + PartialEq + Eq + Into<isize> + 'static> { |
| 91 |
name: &'static str, |
| 92 |
gnupg_version: &'static str, |
| 93 |
synopsis: &'static str, |
| 94 |
additional_version: Box<dyn Fn(&crate::Config)>, |
| 95 |
options: &'static [Opt<T>], |
| 96 |
} |
| 97 |
|
| 98 |
impl<T: Copy + Debug + PartialEq + Eq + Into<isize> + 'static> Parser<T> { |
| 99 |
/// Creates a new parser for the given options. |
| 100 |
pub fn new(name: &'static str, |
| 101 |
gnupg_version: &'static str, |
| 102 |
synopsis: &'static str, |
| 103 |
options: &'static [Opt<T>]) -> Parser<T> { |
| 104 |
Parser { |
| 105 |
name, |
| 106 |
gnupg_version, |
| 107 |
synopsis, |
| 108 |
additional_version: Box::new(|_| ()), |
| 109 |
options, |
| 110 |
} |
| 111 |
} |
| 112 |
|
| 113 |
/// Returns the command's long argument name. |
| 114 |
pub fn argument_name(&self, cmd: T) -> Option<&'static str> { |
| 115 |
self.options.iter() |
| 116 |
.find(|o| o.short_opt == cmd && ! o.long_opt.is_empty()) |
| 117 |
.map(|o| o.long_opt) |
| 118 |
} |
| 119 |
|
| 120 |
/// Registers a callback to print additional version information. |
| 121 |
pub fn with_additional_version_information<F>(mut self, fun: F) -> Self |
| 122 |
where |
| 123 |
F: Fn(&crate::Config) + 'static, |
| 124 |
{ |
| 125 |
self.additional_version = Box::new(fun); |
| 126 |
self |
| 127 |
} |
| 128 |
|
| 129 |
/// Parses the command-line arguments. |
| 130 |
pub fn parse_command_line(&self) -> Iter<T> |
| 131 |
{ |
| 132 |
let mut args = std::env::args(); |
| 133 |
args.next(); // swallow argv[0] |
| 134 |
|
| 135 |
self.parse( |
| 136 |
true, |
| 137 |
Box::new(std::iter::once( |
| 138 |
Box::new(args.map(|arg| arg.to_string())) |
| 139 |
as Box<dyn Iterator<Item = _>>))) |
| 140 |
} |
| 141 |
|
| 142 |
/// Parses the given arguments. |
| 143 |
#[cfg(test)] |
| 144 |
pub fn parse_args(&self, |
| 145 |
args: impl IntoIterator<Item = &'static str> + 'static) |
| 146 |
-> Iter<T> |
| 147 |
{ |
| 148 |
self.parse( |
| 149 |
true, |
| 150 |
Box::new(std::iter::once( |
| 151 |
Box::new(args.into_iter().map(|arg| arg.to_string())) |
| 152 |
as Box<dyn Iterator<Item = _>>))) |
| 153 |
} |
| 154 |
|
| 155 |
/// Tries to parse the given file. |
| 156 |
/// |
| 157 |
/// If the file does not exist, an empty iterator is returned. |
| 158 |
pub fn try_parse_file<P>(&self, path: P) |
| 159 |
-> io::Result<Box<dyn Iterator<Item = Result<Argument<T>>>>> |
| 160 |
where |
| 161 |
P: AsRef<Path>, |
| 162 |
{ |
| 163 |
match std::fs::File::open(path) { |
| 164 |
Ok(f) => { |
| 165 |
let args = Box::new( |
| 166 |
BufReader::new(f) |
| 167 |
.lines() |
| 168 |
.filter_map(|rl| rl.ok()) |
| 169 |
// Trim whitespace. |
| 170 |
.map(|l| l.trim().to_string()) |
| 171 |
// Ignore comments. |
| 172 |
.filter(|l| ! l.starts_with('#')) |
| 173 |
// Ignore empty lines. |
| 174 |
.filter(|l| ! l.is_empty()) |
| 175 |
// Split into argument and value, taking care |
| 176 |
// of quoting. |
| 177 |
.map(|l| -> Box<dyn Iterator<Item = String>> { |
| 178 |
Box::new(l.splitn(2, |c: char| c.is_ascii_whitespace()) |
| 179 |
.map(|w| if w.starts_with('"') && w.ends_with('"') { |
| 180 |
w[1..w.len()-1].into() |
| 181 |
} else { |
| 182 |
w.into() |
| 183 |
}) |
| 184 |
.collect::<Vec<_>>() |
| 185 |
.into_iter()) |
| 186 |
})); |
| 187 |
Ok(Box::new(self.parse(false, args))) |
| 188 |
}, |
| 189 |
Err(e) => if e.kind() == io::ErrorKind::NotFound { |
| 190 |
Ok(Box::new(std::iter::empty())) |
| 191 |
} else { |
| 192 |
Err(e) |
| 193 |
} |
| 194 |
} |
| 195 |
} |
| 196 |
|
| 197 |
/// Parses the arguments. |
| 198 |
fn parse(&self, |
| 199 |
cmdline: bool, |
| 200 |
args: Box<dyn Iterator<Item = Box<dyn Iterator<Item = String>>>>) |
| 201 |
-> Iter<T> |
| 202 |
{ |
| 203 |
Iter { |
| 204 |
options: self.options, |
| 205 |
line: args, |
| 206 |
current: None, |
| 207 |
current_short: None, |
| 208 |
cmdline, |
| 209 |
seen_positional: false, |
| 210 |
special_filenames: false, |
| 211 |
quiet: false, |
| 212 |
ignore_arguments: Default::default(), |
| 213 |
} |
| 214 |
} |
| 215 |
|
| 216 |
/// Displays version information. |
| 217 |
pub fn version(&self, config: &crate::Config, sequoia_version: &str) { |
| 218 |
const NBSP: char = '\u{00A0}'; // A non-breaking space. |
| 219 |
safe_println!("{} (GnuPG-compatible{NBSP}Sequoia{NBSP}Chameleon) {}", |
| 220 |
self.name, self.gnupg_version); |
| 221 |
safe_println!("Sequoia {} Chameleon {}", |
| 222 |
self.name, env!("CARGO_PKG_VERSION")); |
| 223 |
safe_println!("sequoia-openpgp {}", sequoia_version); |
| 224 |
safe_println!("Copyright (C) 2024 Sequoia PGP"); |
| 225 |
safe_println!("License GNU GPL-3.0-or-later \ |
| 226 |
<https://gnu.org/licenses/gpl.html>"); |
| 227 |
safe_println!("This is free software: \ |
| 228 |
you are free to change and redistribute it."); |
| 229 |
safe_println!("There is NO WARRANTY, \ |
| 230 |
to the extent permitted by law."); |
| 231 |
(self.additional_version)(config); |
| 232 |
} |
| 233 |
|
| 234 |
/// Displays help. |
| 235 |
pub fn help(&self, config: &crate::Config, sequoia_version: &str) { |
| 236 |
self.version(config, sequoia_version); |
| 237 |
safe_println!(); |
| 238 |
safe_println!("Syntax: {} [options] [files]", self.name); |
| 239 |
safe_println!("{}", self.synopsis); |
| 240 |
safe_println!(); |
| 241 |
|
| 242 |
let mut current_group = None; |
| 243 |
let mut last_line_was_empty = true; |
| 244 |
for o in self.options { |
| 245 |
if o.flags & OPT_HEADER > 0 { |
| 246 |
// This is a header, but we only emit the header if we |
| 247 |
// display any options from this group. |
| 248 |
current_group = |
| 249 |
(!o.description.is_empty()).then(|| o.description); |
| 250 |
continue; |
| 251 |
} |
| 252 |
|
| 253 |
if o.description == "@" { |
| 254 |
// Hidden from the help. |
| 255 |
continue; |
| 256 |
} |
| 257 |
|
| 258 |
if let Some(group) = current_group.take() { |
| 259 |
// We are displaying an option from this group, |
| 260 |
// display the group header! |
| 261 |
safe_println!(); |
| 262 |
safe_println!("{}:", group); |
| 263 |
} |
| 264 |
|
| 265 |
last_line_was_empty = o.description.ends_with("\n"); |
| 266 |
if o.description == "@\n" { |
| 267 |
// Empty line. |
| 268 |
safe_println!(); |
| 269 |
} else if o.description.starts_with("@") { |
| 270 |
// Caption. |
| 271 |
safe_println!("{}", &o.description[1..]); |
| 272 |
} else { |
| 273 |
let (meta, description) = |
| 274 |
if o.description.starts_with("|") { |
| 275 |
let mut f = o.description.split('|'); |
| 276 |
f.next(); |
| 277 |
(Some(f.next().unwrap()), f.next().unwrap()) |
| 278 |
} else { |
| 279 |
(None, o.description) |
| 280 |
}; |
| 281 |
|
| 282 |
if o.long_opt.is_empty() { |
| 283 |
let short_opt = if let Some(m) = meta { |
| 284 |
format!("{} {}", o.short_opt.into() as u8 as char, m) |
| 285 |
} else { |
| 286 |
format!("{}", o.short_opt.into() as u8 as char) |
| 287 |
}; |
| 288 |
|
| 289 |
safe_println!(" -{:<33} {}", |
| 290 |
short_opt, |
| 291 |
description); |
| 292 |
} else { |
| 293 |
let long_opt = if let Some(m) = meta { |
| 294 |
format!("{} {}", o.long_opt, m) |
| 295 |
} else { |
| 296 |
o.long_opt.to_string() |
| 297 |
}; |
| 298 |
|
| 299 |
if o.short_opt.into() <= 0x7f { |
| 300 |
safe_println!(" -{}, --{:<28} {}", |
| 301 |
o.short_opt.into() as u8 as char, |
| 302 |
long_opt, |
| 303 |
description); |
| 304 |
} else { |
| 305 |
safe_println!(" --{:<28} {}", |
| 306 |
long_opt, |
| 307 |
description); |
| 308 |
} |
| 309 |
} |
| 310 |
} |
| 311 |
} |
| 312 |
|
| 313 |
if ! last_line_was_empty { |
| 314 |
safe_println!(); |
| 315 |
} |
| 316 |
|
| 317 |
safe_println!("Please report bugs to \ |
| 318 |
<https://gitlab.com/sequoia-pgp/sequoia-chameleon-gnupg>"); |
| 319 |
} |
| 320 |
|
| 321 |
/// Displays a message about warranty, or the lack there of. |
| 322 |
pub fn warranty(&self) { |
| 323 |
safe_println!("\ |
| 324 |
This program is free software: you can redistribute it and/or modify |
| 325 |
it under the terms of the GNU General Public License as published by |
| 326 |
the Free Software Foundation, either version 3 of the License, or |
| 327 |
(at your option) any later version. |
| 328 |
|
| 329 |
This program is distributed in the hope that it will be useful, |
| 330 |
but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 331 |
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 332 |
GNU General Public License for more details."); |
| 333 |
} |
| 334 |
|
| 335 |
/// Displays all options. |
| 336 |
pub fn dump_options(&self) { |
| 337 |
for o in self.options { |
| 338 |
if ! o.long_opt.is_empty() && o.flags & OPT_IGNORE == 0 { |
| 339 |
safe_println!("--{}", o.long_opt); |
| 340 |
} |
| 341 |
} |
| 342 |
} |
| 343 |
|
| 344 |
/// Displays all options in tabular form. |
| 345 |
pub fn dump_options_table(&self) { |
| 346 |
for o in self.options { |
| 347 |
if ! o.long_opt.is_empty() { |
| 348 |
safe_println!("{}:{}:{}:{}:", |
| 349 |
o.long_opt, o.short_opt.into(), o.flags, o.description); |
| 350 |
} |
| 351 |
} |
| 352 |
} |
| 353 |
} |
| 354 |
|
| 355 |
/// Iterator over the command line arguments. |
| 356 |
pub struct Iter<T: Copy + Debug + PartialEq + Eq + Into<isize> + 'static> { |
| 357 |
options: &'static [Opt<T>], |
| 358 |
line: Box<dyn Iterator<Item = Box<dyn Iterator<Item = String>>>>, |
| 359 |
current: Option<Box<dyn Iterator<Item = String>>>, |
| 360 |
current_short: Option<String>, |
| 361 |
cmdline: bool, |
| 362 |
seen_positional: bool, |
| 363 |
|
| 364 |
/// Did we see --enable-special-filenames? |
| 365 |
special_filenames: bool, |
| 366 |
|
| 367 |
/// Whether to emit warnings on stderr. |
| 368 |
quiet: bool, |
| 369 |
|
| 370 |
/// The list of ignored arguments. |
| 371 |
ignore_arguments: BTreeSet<String>, |
| 372 |
} |
| 373 |
|
| 374 |
impl<T: Copy + Debug + PartialEq + Eq + Into<isize> + 'static> Iter<T> { |
| 375 |
/// Don't emit warnings on stderr. |
| 376 |
pub fn quietly(mut self) -> Self { |
| 377 |
self.quiet = true; |
| 378 |
self |
| 379 |
} |
| 380 |
|
| 381 |
fn maybe_get_value(&mut self, opt: &Opt<T>) -> Result<Argument<T>> { |
| 382 |
let typ = flags_type(opt.flags); |
| 383 |
if typ == TYPE_NONE { |
| 384 |
return Ok(Argument::Option(opt.short_opt, Value::None)); |
| 385 |
} |
| 386 |
|
| 387 |
let value = match self.current_short.take() |
| 388 |
.or_else(|| self.current.as_mut().and_then(|i| i.next())) |
| 389 |
{ |
| 390 |
Some(v) => v, |
| 391 |
None if opt.flags & OPT_OPTIONAL > 0 => |
| 392 |
return Ok(Argument::Option(opt.short_opt, Value::None)), |
| 393 |
None => |
| 394 |
return Err(Error::Missing(opt.long_opt.into())), |
| 395 |
}; |
| 396 |
|
| 397 |
// Handle OPT_PREFIX. |
| 398 |
let (value, radix) = if opt.flags & OPT_PREFIX > 0 |
| 399 |
&& (value.starts_with("0x") || value.starts_with("0X")) |
| 400 |
{ |
| 401 |
(&value[2..], 16) |
| 402 |
} else { |
| 403 |
(&value[..], 10) |
| 404 |
}; |
| 405 |
|
| 406 |
match typ { |
| 407 |
TYPE_NONE => unreachable!("handled above"), |
| 408 |
TYPE_INT | TYPE_LONG => match i64::from_str_radix(value, radix) { |
| 409 |
Ok(v) => Ok(Argument::Option(opt.short_opt, Value::Int(v))), |
| 410 |
Err(_) => Err(Error::BadValue(opt.long_opt.into(), |
| 411 |
"integer", |
| 412 |
value.into())), |
| 413 |
}, |
| 414 |
TYPE_ULONG => match u64::from_str_radix(value, radix) { |
| 415 |
Ok(v) => Ok(Argument::Option(opt.short_opt, Value::UInt(v))), |
| 416 |
Err(_) => Err(Error::BadValue(opt.long_opt.into(), |
| 417 |
"unsigned integer", |
| 418 |
value.into())), |
| 419 |
}, |
| 420 |
TYPE_STRING => |
| 421 |
Ok(Argument::Option(opt.short_opt, Value::String(value.into()))), |
| 422 |
n => unreachable!("bad type {}", n), |
| 423 |
} |
| 424 |
} |
| 425 |
} |
| 426 |
|
| 427 |
impl<T: Copy + Debug + PartialEq + Eq + Into<isize> + 'static> Iterator for Iter<T> { |
| 428 |
type Item = Result<Argument<T>>; |
| 429 |
|
| 430 |
fn next(&mut self) -> Option<Self::Item> { |
| 431 |
// Handle leftover short options. |
| 432 |
if let Some(rest) = self.current_short.take() { |
| 433 |
let mut chars = rest.chars(); |
| 434 |
let a0 = match chars.next() { |
| 435 |
Some(c) => c, |
| 436 |
None => unreachable!("current_short is not empty"), |
| 437 |
}; |
| 438 |
|
| 439 |
// See if there are more short arguments after this one. |
| 440 |
let rest = chars.collect::<String>(); |
| 441 |
self.current_short = |
| 442 |
if rest.is_empty() { None } else { Some(rest) }; |
| 443 |
|
| 444 |
let matches = self.options.iter() |
| 445 |
.filter(|o| o.short_opt.into() == a0 as isize) |
| 446 |
.collect::<Vec<_>>(); |
| 447 |
|
| 448 |
let m = match matches.len() { |
| 449 |
0 => return Some(Err(Error::Unknown(a0.into()))), |
| 450 |
_ => matches[0], |
| 451 |
}; |
| 452 |
|
| 453 |
return Some(self.maybe_get_value(m)); |
| 454 |
} |
| 455 |
|
| 456 |
// Once we saw a positional argument, all remaining arguments |
| 457 |
// are positional. |
| 458 |
if self.seen_positional { |
| 459 |
assert!(self.cmdline); |
| 460 |
if let Some(c) = self.current.as_mut() { |
| 461 |
if let Some(arg) = c.next() { |
| 462 |
if arg != "-" && arg.starts_with('-') && ! self.quiet { |
| 463 |
safe_eprintln!("gpg: Note: {:?} is not considered an option", |
| 464 |
arg); |
| 465 |
} |
| 466 |
return Some(Ok(Argument::Positional(arg))); |
| 467 |
} else { |
| 468 |
// We're done. |
| 469 |
return None; |
| 470 |
} |
| 471 |
} else { |
| 472 |
// We're done. |
| 473 |
return None; |
| 474 |
} |
| 475 |
} |
| 476 |
|
| 477 |
if self.current.is_none() { |
| 478 |
self.current = self.line.next(); |
| 479 |
} |
| 480 |
|
| 481 |
if self.current.is_none() { |
| 482 |
// Exhausted top-level iterator, we're done. |
| 483 |
return None; |
| 484 |
} |
| 485 |
|
| 486 |
let mut current = self.current.take().unwrap(); |
| 487 |
let arg = match current.next() { |
| 488 |
Some(a) => { |
| 489 |
self.current = Some(current); |
| 490 |
a |
| 491 |
}, |
| 492 |
None => { |
| 493 |
// Exhausted iterator, see if there is a next line. |
| 494 |
return self.next(); |
| 495 |
}, |
| 496 |
}; |
| 497 |
|
| 498 |
let (long, mut a) = if self.cmdline { |
| 499 |
if arg == "--" { |
| 500 |
// This indicates the start of positional arguments, |
| 501 |
// while not being an argument by itself. Having |
| 502 |
// consumed it, set the positional flag and recurse. |
| 503 |
self.seen_positional = true; |
| 504 |
return self.next(); |
| 505 |
} |
| 506 |
|
| 507 |
if ! arg.starts_with("-") { |
| 508 |
// A positional argument. |
| 509 |
self.seen_positional = true; |
| 510 |
return Some(Ok(Argument::Positional(arg.into()))); |
| 511 |
} |
| 512 |
|
| 513 |
if arg.starts_with("--") { |
| 514 |
// Long option. |
| 515 |
(true, &arg[2..]) |
| 516 |
} else { |
| 517 |
// Short option. |
| 518 |
(false, &arg[1..]) |
| 519 |
} |
| 520 |
} else { |
| 521 |
// Config file. All options are long options. |
| 522 |
(true, &arg[..]) |
| 523 |
}; |
| 524 |
|
| 525 |
if long && a == "enable-special-filenames" |
| 526 |
&& ! self.seen_positional |
| 527 |
{ |
| 528 |
// From now on, we'll handle -@ slightly differently. |
| 529 |
self.special_filenames = true; |
| 530 |
} |
| 531 |
|
| 532 |
if ! long && self.special_filenames |
| 533 |
&& utils::special_filename_fd(&arg).is_some() |
| 534 |
{ |
| 535 |
// This is a named file descriptor as a positional |
| 536 |
// argument. |
| 537 |
self.seen_positional = true; |
| 538 |
return Some(Ok(Argument::Positional(arg.into()))); |
| 539 |
} |
| 540 |
|
| 541 |
let m = if long { |
| 542 |
// See if we have a value in this argument. |
| 543 |
let value; |
| 544 |
(a, value) = if self.cmdline { |
| 545 |
let mut split = a.splitn(2, "="); |
| 546 |
(split.next().unwrap(), split.next().map(|s| s.to_string())) |
| 547 |
} else { |
| 548 |
(a, self.current.as_mut().and_then(|c| c.next())) |
| 549 |
}; |
| 550 |
|
| 551 |
if ! self.cmdline { |
| 552 |
if a == "ignore-invalid-option" { |
| 553 |
if let Some(v) = value { |
| 554 |
for name in v.split(char::is_whitespace) |
| 555 |
.map(str::trim).filter(|s| ! s.is_empty()) |
| 556 |
{ |
| 557 |
self.ignore_arguments.insert(name.into()); |
| 558 |
} |
| 559 |
} |
| 560 |
return self.next(); |
| 561 |
} |
| 562 |
|
| 563 |
if self.ignore_arguments.contains(a) { |
| 564 |
return self.next(); |
| 565 |
} |
| 566 |
} |
| 567 |
|
| 568 |
let matches = self.options.iter().filter(|o| o.long_opt.starts_with(a)) |
| 569 |
.collect::<Vec<_>>(); |
| 570 |
|
| 571 |
let matched = match matches.len() { |
| 572 |
0 => return Some(Err(Error::Unknown(a.into()))), |
| 573 |
1 => matches[0], |
| 574 |
n => { |
| 575 |
// See if there is an *exact* match. |
| 576 |
let exact = self.options.iter().filter(|o| o.long_opt == a) |
| 577 |
.collect::<Vec<_>>(); |
| 578 |
|
| 579 |
// See if all matches refer to the same CmdOrOpt. |
| 580 |
if matches.iter() |
| 581 |
.all(|m| m.short_opt == matches[0].short_opt) |
| 582 |
{ |
| 583 |
matches[0] |
| 584 |
} else if ! exact.is_empty() { |
| 585 |
exact[0] |
| 586 |
} else { |
| 587 |
let mut also = String::new(); |
| 588 |
for (i, c) in matches.iter().enumerate() { |
| 589 |
match i { |
| 590 |
0 => (), |
| 591 |
x if x == n - 1 => also.push_str(", and "), |
| 592 |
_ => also.push_str(", "), |
| 593 |
} |
| 594 |
|
| 595 |
also.push_str("--"); |
| 596 |
also.push_str(c.long_opt); |
| 597 |
} |
| 598 |
return Some(Err(Error::Ambiguous(a.into(), also))) |
| 599 |
} |
| 600 |
}, |
| 601 |
}; |
| 602 |
|
| 603 |
if let Some(value) = value { |
| 604 |
if flags_type(matched.flags) != TYPE_NONE { |
| 605 |
// This long argument takes a value. If we have a |
| 606 |
// value from this very argument (--foo=value), stash |
| 607 |
// that into `current_short` for `maybe_get_value` to |
| 608 |
// find. |
| 609 |
self.current_short = Some(value.into()); |
| 610 |
} else { |
| 611 |
// This argument does not take a value, but the GnuPG |
| 612 |
// argument parser silently ignores that. |
| 613 |
if ! self.quiet { |
| 614 |
safe_eprintln!("gpg: Note: Ignoring value {:?} \ |
| 615 |
for option \"--{}\"", |
| 616 |
value, a); |
| 617 |
} |
| 618 |
} |
| 619 |
} |
| 620 |
|
| 621 |
matched |
| 622 |
} else { |
| 623 |
assert!(! self.seen_positional); |
| 624 |
|
| 625 |
let mut chars = a.chars(); |
| 626 |
let a0 = match chars.next() { |
| 627 |
Some(c) => c, |
| 628 |
None => { |
| 629 |
// This is the first positional argument. |
| 630 |
self.seen_positional = true; |
| 631 |
return Some(Ok(Argument::Positional(arg.into()))); |
| 632 |
}, |
| 633 |
}; |
| 634 |
|
| 635 |
// See if there are more short arguments after this one. |
| 636 |
let rest = chars.collect::<String>(); |
| 637 |
self.current_short = |
| 638 |
if rest.is_empty() { None } else { Some(rest) }; |
| 639 |
|
| 640 |
let matches = self.options.iter() |
| 641 |
.filter(|o| o.short_opt.into() == a0 as isize) |
| 642 |
.collect::<Vec<_>>(); |
| 643 |
|
| 644 |
match matches.len() { |
| 645 |
0 => return Some(Err(Error::Unknown(a0.into()))), |
| 646 |
_ => matches[0], |
| 647 |
} |
| 648 |
}; |
| 649 |
|
| 650 |
Some(self.maybe_get_value(m)) |
| 651 |
} |
| 652 |
} |
| 653 |
|
| 654 |
/// Errors during argument parsing. |
| 655 |
#[derive(thiserror::Error, Debug)] |
| 656 |
pub enum Error { |
| 657 |
#[error("Malformed argument {:?}", _0)] |
| 658 |
Malformed(String), |
| 659 |
#[error("Unknown argument {:?}", _0)] |
| 660 |
Unknown(String), |
| 661 |
#[error("Ambiguous argument: {:?} matches {}", _0, _1)] |
| 662 |
Ambiguous(String, String), |
| 663 |
#[error("Missing parameter for {:?}", _0)] |
| 664 |
Missing(String), |
| 665 |
#[error("Parameter for {:?} is not a {}: {}", _0, _1, _2)] |
| 666 |
BadValue(String, &'static str, String), |
| 667 |
#[error("Cannot convert {} to {}", _0, _1)] |
| 668 |
ConversionFailed(&'static str, &'static str), |
| 669 |
} |
| 670 |
|
| 671 |
/// Result specialization. |
| 672 |
pub type Result<T> = std::result::Result<T, Error>; |
| 673 |
|
| 674 |
#[cfg(test)] |
| 675 |
mod tests { |
| 676 |
use std::io::Write; |
| 677 |
use super::*; |
| 678 |
|
| 679 |
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] |
| 680 |
#[allow(non_camel_case_types)] |
| 681 |
pub enum CmdOrOpt { |
| 682 |
oQuiet = 'q' as isize, |
| 683 |
oOutput = 'o' as isize, |
| 684 |
o300 = 300, |
| 685 |
o301, |
| 686 |
oStatusFD, |
| 687 |
} |
| 688 |
|
| 689 |
impl From<CmdOrOpt> for isize { |
| 690 |
fn from(c: CmdOrOpt) -> isize { |
| 691 |
c as isize |
| 692 |
} |
| 693 |
} |
| 694 |
|
| 695 |
use CmdOrOpt::*; |
| 696 |
const OPTIONS: &[Opt<CmdOrOpt>] = &[ |
| 697 |
Opt { short_opt: o300, long_opt: "", flags: 0, description: "@\nOptions:\n", }, |
| 698 |
Opt { short_opt: oQuiet, long_opt: "quiet", flags: TYPE_NONE, description: "be somewhat more quiet", }, |
| 699 |
Opt { short_opt: oOutput, long_opt: "output", flags: TYPE_STRING, description: "|FILE|write output to FILE", }, |
| 700 |
Opt { short_opt: oStatusFD, long_opt: "status-fd", flags: TYPE_INT, description: "|FD|write status info to this FD", }, |
| 701 |
Opt { short_opt: o301, long_opt: "", flags: 0, description: "@\n", }, |
| 702 |
]; |
| 703 |
|
| 704 |
#[test] |
| 705 |
fn commandline() -> Result<()> { |
| 706 |
let parser = Parser::new("foo", "0.0.0", "does foo", &OPTIONS); |
| 707 |
|
| 708 |
let mut i = parser.parse_args(vec!["-q"]); |
| 709 |
assert_eq!(i.next().unwrap().unwrap(), |
| 710 |
Argument::Option(oQuiet, Value::None)); |
| 711 |
assert!(i.next().is_none()); |
| 712 |
|
| 713 |
let mut i = parser.parse_args(vec!["--quiet"]); |
| 714 |
assert_eq!(i.next().unwrap().unwrap(), |
| 715 |
Argument::Option(oQuiet, Value::None)); |
| 716 |
assert!(i.next().is_none()); |
| 717 |
|
| 718 |
let mut i = parser.parse_args(vec!["-q", "-q"]); |
| 719 |
assert_eq!(i.next().unwrap().unwrap(), |
| 720 |
Argument::Option(oQuiet, Value::None)); |
| 721 |
assert_eq!(i.next().unwrap().unwrap(), |
| 722 |
Argument::Option(oQuiet, Value::None)); |
| 723 |
assert!(i.next().is_none()); |
| 724 |
|
| 725 |
let mut i = parser.parse_args(vec!["-o"]); |
| 726 |
assert!(i.next().unwrap().is_err()); |
| 727 |
assert!(i.next().is_none()); |
| 728 |
|
| 729 |
let mut i = parser.parse_args(vec!["--output"]); |
| 730 |
assert!(i.next().unwrap().is_err()); |
| 731 |
assert!(i.next().is_none()); |
| 732 |
|
| 733 |
let mut i = parser.parse_args(vec!["-o", "foo"]); |
| 734 |
assert_eq!(i.next().unwrap().unwrap(), |
| 735 |
Argument::Option(oOutput, Value::String("foo".into()))); |
| 736 |
assert!(i.next().is_none()); |
| 737 |
|
| 738 |
let mut i = parser.parse_args(vec!["-ofoo"]); |
| 739 |
assert_eq!(i.next().unwrap().unwrap(), |
| 740 |
Argument::Option(oOutput, Value::String("foo".into()))); |
| 741 |
assert!(i.next().is_none()); |
| 742 |
|
| 743 |
let mut i = parser.parse_args(vec!["--output", "foo"]); |
| 744 |
assert_eq!(i.next().unwrap().unwrap(), |
| 745 |
Argument::Option(oOutput, Value::String("foo".into()))); |
| 746 |
assert!(i.next().is_none()); |
| 747 |
|
| 748 |
let mut i = parser.parse_args(vec!["-qo", "foo"]); |
| 749 |
assert_eq!(i.next().unwrap().unwrap(), |
| 750 |
Argument::Option(oQuiet, Value::None)); |
| 751 |
assert_eq!(i.next().unwrap().unwrap(), |
| 752 |
Argument::Option(oOutput, Value::String("foo".into()))); |
| 753 |
assert!(i.next().is_none()); |
| 754 |
|
| 755 |
let mut i = parser.parse_args(vec!["-qofoo"]); |
| 756 |
assert_eq!(i.next().unwrap().unwrap(), |
| 757 |
Argument::Option(oQuiet, Value::None)); |
| 758 |
assert_eq!(i.next().unwrap().unwrap(), |
| 759 |
Argument::Option(oOutput, Value::String("foo".into()))); |
| 760 |
assert!(i.next().is_none()); |
| 761 |
|
| 762 |
let mut i = parser.parse_args(vec!["--status-fd"]); |
| 763 |
assert!(i.next().unwrap().is_err()); |
| 764 |
assert!(i.next().is_none()); |
| 765 |
|
| 766 |
let mut i = parser.parse_args(vec!["--status-fd", "drei"]); |
| 767 |
assert!(i.next().unwrap().is_err()); |
| 768 |
assert!(i.next().is_none()); |
| 769 |
|
| 770 |
let mut i = parser.parse_args(vec!["--status-fd", "3"]); |
| 771 |
assert_eq!(i.next().unwrap().unwrap(), |
| 772 |
Argument::Option(oStatusFD, Value::Int(3))); |
| 773 |
assert!(i.next().is_none()); |
| 774 |
|
| 775 |
let mut i = parser.parse_args(vec!["--status-fd=3"]); |
| 776 |
assert_eq!(i.next().unwrap().unwrap(), |
| 777 |
Argument::Option(oStatusFD, Value::Int(3))); |
| 778 |
assert!(i.next().is_none()); |
| 779 |
|
| 780 |
let mut i = parser.parse_args(vec!["foo"]); |
| 781 |
assert_eq!(i.next().unwrap().unwrap(), |
| 782 |
Argument::Positional("foo".into())); |
| 783 |
assert!(i.next().is_none()); |
| 784 |
|
| 785 |
let mut i = parser.parse_args(vec!["--quiet", "foo"]); |
| 786 |
assert_eq!(i.next().unwrap().unwrap(), |
| 787 |
Argument::Option(oQuiet, Value::None)); |
| 788 |
assert_eq!(i.next().unwrap().unwrap(), |
| 789 |
Argument::Positional("foo".into())); |
| 790 |
assert!(i.next().is_none()); |
| 791 |
|
| 792 |
let mut i = parser.parse_args(vec!["--quiet", "foo", "-q"]); |
| 793 |
assert_eq!(i.next().unwrap().unwrap(), |
| 794 |
Argument::Option(oQuiet, Value::None)); |
| 795 |
assert_eq!(i.next().unwrap().unwrap(), |
| 796 |
Argument::Positional("foo".into())); |
| 797 |
assert_eq!(i.next().unwrap().unwrap(), |
| 798 |
Argument::Positional("-q".into())); |
| 799 |
assert!(i.next().is_none()); |
| 800 |
|
| 801 |
let mut i = |
| 802 |
parser.parse_args(vec!["--quiet", "foo", "-q", "--status-fd"]); |
| 803 |
assert_eq!(i.next().unwrap().unwrap(), |
| 804 |
Argument::Option(oQuiet, Value::None)); |
| 805 |
assert_eq!(i.next().unwrap().unwrap(), |
| 806 |
Argument::Positional("foo".into())); |
| 807 |
assert_eq!(i.next().unwrap().unwrap(), |
| 808 |
Argument::Positional("-q".into())); |
| 809 |
assert_eq!(i.next().unwrap().unwrap(), |
| 810 |
Argument::Positional("--status-fd".into())); |
| 811 |
assert!(i.next().is_none()); |
| 812 |
|
| 813 |
let mut i = |
| 814 |
parser.parse_args(vec!["--quiet", "-"]); |
| 815 |
assert_eq!(i.next().unwrap().unwrap(), |
| 816 |
Argument::Option(oQuiet, Value::None)); |
| 817 |
assert_eq!(i.next().unwrap().unwrap(), |
| 818 |
Argument::Positional("-".into())); |
| 819 |
assert!(i.next().is_none()); |
| 820 |
|
| 821 |
let mut i = |
| 822 |
parser.parse_args(vec!["--quiet", "--"]); |
| 823 |
assert_eq!(i.next().unwrap().unwrap(), |
| 824 |
Argument::Option(oQuiet, Value::None)); |
| 825 |
assert!(i.next().is_none()); |
| 826 |
|
| 827 |
let mut i = |
| 828 |
parser.parse_args(vec!["--quiet", "--", "--quiet"]); |
| 829 |
assert_eq!(i.next().unwrap().unwrap(), |
| 830 |
Argument::Option(oQuiet, Value::None)); |
| 831 |
assert_eq!(i.next().unwrap().unwrap(), |
| 832 |
Argument::Positional("--quiet".into())); |
| 833 |
assert!(i.next().is_none()); |
| 834 |
|
| 835 |
Ok(()) |
| 836 |
} |
| 837 |
|
| 838 |
#[test] |
| 839 |
fn file() -> anyhow::Result<()> { |
| 840 |
let parser = Parser::new("foo", "0.0.0", "does foo", &OPTIONS); |
| 841 |
|
| 842 |
fn parse<F, T>(p: &Parser<T>, fun: F) |
| 843 |
-> anyhow::Result<Box<dyn Iterator<Item = Result<Argument<T>>>>> |
| 844 |
where |
| 845 |
F: Fn(&mut tempfile::NamedTempFile) -> anyhow::Result<()>, |
| 846 |
T: Copy + Debug + PartialEq + Eq + Into<isize> + 'static, |
| 847 |
{ |
| 848 |
let mut f = tempfile::NamedTempFile::new()?; |
| 849 |
fun(&mut f)?; |
| 850 |
f.flush()?; |
| 851 |
|
| 852 |
Ok(p.try_parse_file(f.path())?) |
| 853 |
} |
| 854 |
|
| 855 |
let mut i = parse(&parser, |f| Ok(writeln!(f, "quiet")?))?; |
| 856 |
assert_eq!(i.next().unwrap().unwrap(), |
| 857 |
Argument::Option(oQuiet, Value::None)); |
| 858 |
assert!(i.next().is_none()); |
| 859 |
|
| 860 |
|
| 861 |
let mut i = parse(&parser, |f| Ok(writeln!(f, "output")?))?; |
| 862 |
assert!(i.next().unwrap().is_err()); |
| 863 |
assert!(i.next().is_none()); |
| 864 |
|
| 865 |
let mut i = parse(&parser, |f| Ok(writeln!(f, "output\nfoo")?))?; |
| 866 |
assert!(i.next().unwrap().is_err()); |
| 867 |
assert!(i.next().unwrap().is_err()); |
| 868 |
assert!(i.next().is_none()); |
| 869 |
|
| 870 |
let mut i = parse(&parser, |f| Ok(writeln!(f, "output foo")?))?; |
| 871 |
assert_eq!(i.next().unwrap().unwrap(), |
| 872 |
Argument::Option(oOutput, Value::String("foo".into()))); |
| 873 |
assert!(i.next().is_none()); |
| 874 |
|
| 875 |
let mut i = parse(&parser, |f| Ok(writeln!(f, "output=foo")?))?; |
| 876 |
assert!(i.next().unwrap().is_err()); |
| 877 |
assert!(i.next().is_none()); |
| 878 |
|
| 879 |
let mut i = parse(&parser, |f| Ok(writeln!(f, "status-fd")?))?; |
| 880 |
assert!(i.next().unwrap().is_err()); |
| 881 |
assert!(i.next().is_none()); |
| 882 |
|
| 883 |
let mut i = parse(&parser, |f| Ok(writeln!(f, "status-fd drei")?))?; |
| 884 |
assert!(i.next().unwrap().is_err()); |
| 885 |
assert!(i.next().is_none()); |
| 886 |
|
| 887 |
let mut i = parse(&parser, |f| Ok(writeln!(f, "status-fd=drei")?))?; |
| 888 |
assert!(i.next().unwrap().is_err()); |
| 889 |
assert!(i.next().is_none()); |
| 890 |
|
| 891 |
let mut i = parse(&parser, |f| Ok(writeln!(f, "status-fd 3")?))?; |
| 892 |
assert_eq!(i.next().unwrap().unwrap(), |
| 893 |
Argument::Option(oStatusFD, Value::Int(3))); |
| 894 |
assert!(i.next().is_none()); |
| 895 |
|
| 896 |
let mut i = parse(&parser, |f| Ok(writeln!(f, "status-fd=3")?))?; |
| 897 |
assert!(i.next().unwrap().is_err()); |
| 898 |
assert!(i.next().is_none()); |
| 899 |
|
| 900 |
Ok(()) |
| 901 |
} |
| 902 |
} |