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 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561
//! Option parser with custom derive support //! //! # Examples //! //! ``` //! extern crate gumdrop; //! #[macro_use] extern crate gumdrop_derive; //! //! use std::env::args; //! use gumdrop::Options; //! //! // Defines options that can be parsed from the command line. //! // //! // `derive(Options)` will generate an implementation of the trait `Options`. //! // An implementation of `Default` (derived or otherwise) is required for the //! // generated implementation. //! // //! // (`Debug` is only derived here for demonstration purposes.) //! #[derive(Debug, Default, Options)] //! struct MyOptions { //! // Contains "free" arguments -- those that are not options. //! // If no `free` field is declared, free arguments will result in an error. //! #[options(free)] //! free: Vec<String>, //! //! // Boolean options are treated as flags, taking no additional values. //! // The optional `help` attribute is displayed in `usage` text. //! #[options(help = "print help message")] //! help: bool, //! //! // Non-boolean fields will take a value from the command line. //! // Wrapping the type in an `Option` is not necessary, but provides clarity. //! #[options(help = "give a string argument")] //! string: Option<String>, //! //! // A field can be any type that implements `FromStr`. //! // The optional `meta` attribute is displayed in `usage` text. //! #[options(help = "give a number as an argument", meta = "N")] //! number: Option<i32>, //! //! // A `Vec` field will accumulate all values received from the command line. //! #[options(help = "give a list of string items")] //! item: Vec<String>, //! //! // The `count` flag will treat the option as a counter. //! // Each time the option is encountered, the field is incremented. //! #[options(count, help = "increase a counting value")] //! count: u32, //! //! // Option names are automatically generated from field names, but these //! // can be overriden. The attributes `short = "?"`, `long = "..."`, //! // `no_short`, and `no_long` are used to control option names. //! #[options(no_short, help = "this option has no short form")] //! long_option_only: bool, //! } //! //! fn main() { //! let args: Vec<String> = args().collect(); //! //! // Remember to skip the first argument. That's the program name. //! let opts = match MyOptions::parse_args_default(&args[1..]) { //! Ok(opts) => opts, //! Err(e) => { //! println!("{}: {}", args[0], e); //! return; //! } //! }; //! //! if opts.help { //! // Printing usage text for the `--help` option is handled explicitly //! // by the program. //! // However, `derive(Options)` does generate information about all //! // defined options. //! println!("Usage: {} [OPTIONS] [ARGUMENTS]", args[0]); //! println!(); //! println!("{}", MyOptions::usage()); //! } else { //! println!("{:#?}", opts); //! } //! } //! ``` //! //! `derive(Options)` can also be used on `enum`s to produce a subcommand //! option parser. //! //! ``` //! extern crate gumdrop; //! #[macro_use] extern crate gumdrop_derive; //! //! use std::env::args; //! use gumdrop::Options; //! //! // Define options for the program. //! #[derive(Debug, Default, Options)] //! struct MyOptions { //! // Options here can be accepted with any command (or none at all), //! // but they must come before the command name. //! #[options(help = "print help message")] //! help: bool, //! #[options(help = "be verbose")] //! verbose: bool, //! //! // The `command` option will delegate option parsing to the command type, //! // starting at the first free argument. //! #[options(command)] //! command: Option<Command>, //! } //! //! // The set of commands and the options each one accepts. //! // //! // Each variant of a command enum should be a unary tuple variant with only //! // one field. This field must implement `Options` and is used to parse arguments //! // that are given after the command name. //! #[derive(Debug, Options)] //! enum Command { //! // Command names are generated from variant names. //! // By default, a CamelCase name will be converted into a lowercase, //! // hyphen-separated name; e.g. `FooBar` becomes `foo-bar`. //! // //! // Names can be explicitly specified using `#[options(name = "...")]` //! #[options(help = "show help for a command")] //! Help(HelpOpts), //! #[options(help = "make stuff")] //! Make(MakeOpts), //! #[options(help = "install stuff")] //! Install(InstallOpts), //! } //! //! // Options accepted for the `help` command //! #[derive(Debug, Default, Options)] //! struct HelpOpts { //! #[options(free)] //! free: Vec<String>, //! } //! //! // Options accepted for the `make` command //! #[derive(Debug, Default, Options)] //! struct MakeOpts { //! #[options(free)] //! free: Vec<String>, //! #[options(help = "number of jobs", meta = "N")] //! jobs: Option<u32>, //! } //! //! // Options accepted for the `install` command //! #[derive(Debug, Default, Options)] //! struct InstallOpts { //! #[options(help = "target directory")] //! dir: Option<String>, //! } //! //! fn main() { //! let args: Vec<String> = args().collect(); //! //! // Remember to skip the first argument. That's the program name. //! let opts = match MyOptions::parse_args_default(&args[1..]) { //! Ok(opts) => opts, //! Err(e) => { //! println!("{}: {}", args[0], e); //! return; //! } //! }; //! //! if opts.help { //! // Main options are printed in the usual way. //! // This does not include any mention of commands because that //! // information is held by the Command type itself. //! println!("Usage: {} [OPTIONS] [COMMAND] [ARGUMENTS]", args[0]); //! println!(); //! println!("{}", MyOptions::usage()); //! println!(); //! //! // Help text for commands comes can be found in the `usage` method //! // of our Command enum. //! println!("Available commands:"); //! println!(); //! println!("{}", Command::usage()); //! } else if let Some(Command::Help(ref opts)) = opts.command { //! let cmd = match opts.free.get(0) { //! Some(cmd) => cmd, //! None => { //! println!("{}: help: missing command", args[0]); //! return; //! } //! }; //! //! // The Command enum will also give us a list of a command's options //! // if we ask for it by name. These are the same strings you'd get //! // from the `usage` method on each option struct. //! if let Some(help) = Command::command_usage(cmd) { //! if help.is_empty() { //! println!("command `{}` has no options", cmd); //! } else { //! println!("command `{}` accepts the following options:", cmd); //! println!(); //! println!("{}", help); //! } //! } else { //! println!("{}: unrecognized command: {}", args[0], cmd); //! } //! } else { //! println!("{:#?}", opts); //! } //! } //! ``` #![deny(missing_docs)] #[cfg(test)] #[macro_use] extern crate assert_matches; use std::error::Error as StdError; use std::fmt; use std::slice::Iter; use std::str::Chars; /// Parses arguments from the command line. /// /// The first argument (the program name) should be omitted. pub fn parse_args<T: Options>(args: &[String], style: ParsingStyle) -> Result<T, Error> { T::parse(&mut Parser::new(args, style)) } /// Parses arguments from the command line using the default parsing style. /// /// The first argument (the program name) should be omitted. pub fn parse_args_default<T: Options>(args: &[String]) -> Result<T, Error> { T::parse(&mut Parser::new(args, ParsingStyle::default())) } /// Represents an error encountered during argument parsing #[derive(Debug)] pub struct Error { inner: InnerError, } impl Error { /// Returns an error for a failed attempt at parsing an option value. pub fn failed_parse(opt: Opt, err: String) -> Error { Error{inner: InnerError::FailedParse(opt.to_string(), err)} } /// Returns an error for an option receiving an unexpected argument value, /// e.g. `--option=value`. pub fn unexpected_argument(opt: Opt) -> Error { Error{inner: InnerError::UnexpectedArgument(opt.to_string())} } /// Returns an error for a missing required argument. pub fn missing_argument(opt: Opt) -> Error { Error{inner: InnerError::MissingArgument(opt.to_string())} } /// Returns an error for a missing command name. pub fn missing_command() -> Error { Error{inner: InnerError::MissingCommand} } /// Returns an error when a free argument was encountered, but the options /// type does not support free arguments. pub fn unexpected_free(arg: &str) -> Error { Error{inner: InnerError::UnexpectedFree(arg.to_owned())} } /// Returns an error for an unrecognized command. pub fn unrecognized_command(name: &str) -> Error { Error{inner: InnerError::UnrecognizedCommand(name.to_owned())} } /// Returns an error for an unrecognized option. pub fn unrecognized_option(opt: Opt) -> Error { match opt { Opt::Short(short) => Error::unrecognized_short(short), Opt::Long(long) | Opt::LongWithArg(long, _) => Error::unrecognized_long(long), Opt::Free(_) => panic!("`Error::unrecognized_option` called with `Opt::Free` value") } } /// Returns an error for an unrecognized long option, e.g. `--option`. pub fn unrecognized_long(opt: &str) -> Error { Error{inner: InnerError::UnrecognizedLongOption(opt.to_owned())} } /// Returns an error for an unrecognized short option, e.g. `-o`. pub fn unrecognized_short(opt: char) -> Error { Error{inner: InnerError::UnrecognizedShortOption(opt)} } } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { use self::InnerError::*; match self.inner { FailedParse(ref opt, ref arg) => write!(f, "invalid argument to option `{}`: {}", opt, arg), MissingArgument(ref opt) => write!(f, "missing argument to option `{}`", opt), MissingCommand => f.write_str("missing command name"), UnexpectedArgument(ref opt) => write!(f, "option `{}` does not accept an argument", opt), UnexpectedFree(ref arg) => write!(f, "unexpected free argument `{}`", arg), UnrecognizedCommand(ref cmd) => write!(f, "unrecognized command `{}`", cmd), UnrecognizedLongOption(ref opt) => write!(f, "unrecognized option `--{}`", opt), UnrecognizedShortOption(opt) => write!(f, "unrecognized option `-{}`", opt), } } } impl StdError for Error { fn description(&self) -> &str { "failed to parse arguments" } } #[derive(Debug)] enum InnerError { FailedParse(String, String), MissingArgument(String), MissingCommand, UnexpectedArgument(String), UnexpectedFree(String), UnrecognizedCommand(String), UnrecognizedLongOption(String), UnrecognizedShortOption(char), } /// Parses options from a series of `&str`-like values. pub struct Parser<'a, S: 'a> { args: Iter<'a, S>, cur: Option<Chars<'a>>, style: ParsingStyle, terminated: bool, } impl<'a, S: 'a + AsRef<str>> Parser<'a, S> { /// Returns a new parser for the given series of arguments. /// /// The given slice should **not** contain the program name as its first /// element. pub fn new(args: &'a [S], style: ParsingStyle) -> Parser<'a, S> { Parser{ args: args.iter(), cur: None, style: style, terminated: false, } } /// Returns the next option or `None` if no options remain. /// /// If the previous option had an explicit argument, e.g. `--option=argument`, /// which was not consumed by a call to `next_arg()`, an error will be /// returned indicating that the argument was ignored. pub fn next_opt(&mut self) -> Option<Opt<'a>> { if let Some(mut cur) = self.cur.take() { if let Some(opt) = cur.next() { self.cur = Some(cur); return Some(Opt::Short(opt)); } } if self.terminated { return self.args.next().map(|s| Opt::Free(s.as_ref())); } match self.args.next().map(|s| s.as_ref()) { Some(arg @ "-") => { if self.style == ParsingStyle::StopAtFirstFree { self.terminated = true; } Some(Opt::Free(arg)) } Some("--") => { self.terminated = true; self.args.next().map(|s| Opt::Free(s.as_ref())) } Some(long) if long.starts_with("--") => { match long.find('=') { Some(pos) => Some(Opt::LongWithArg( &long[2..pos], &long[pos + 1..])), None => Some(Opt::Long(&long[2..])) } } Some(short) if short.starts_with('-') => { let mut chars = short[1..].chars(); let res = chars.next().map(Opt::Short); self.cur = Some(chars); res } Some(free) => { if self.style == ParsingStyle::StopAtFirstFree { self.terminated = true; } Some(Opt::Free(free)) } None => None } } /// Returns the next argument to an option or `None` if none remain. pub fn next_arg(&mut self) -> Option<&'a str> { if let Some(cur) = self.cur.take() { let arg = cur.as_str(); if !arg.is_empty() { return Some(arg); } } self.args.next().map(|s| s.as_ref()) } } impl<'a, S: 'a> Clone for Parser<'a, S> { fn clone(&self) -> Parser<'a, S> { Parser{ args: self.args.clone(), cur: self.cur.clone(), style: self.style, terminated: self.terminated, } } } /// Represents an option parsed from a `Parser` #[derive(Copy, Clone, Debug, Eq, PartialEq)] pub enum Opt<'a> { /// Short option, e.g. `-o` Short(char), /// Long option, e.g. `--option` Long(&'a str), /// Long option with argument, e.g. `--option=value` LongWithArg(&'a str, &'a str), /// Free argument Free(&'a str), } impl<'a> Opt<'a> { fn to_string(&self) -> String { match *self { Opt::Short(ch) => format!("-{}", ch), Opt::Long(s) => format!("--{}", s), Opt::LongWithArg(opt, _) => format!("--{}", opt), Opt::Free(_) => "free".to_owned() } } } /// Implements a set of options parsed from command line arguments. /// /// An implementation of this trait can be generated with `#[derive(Options)]` /// from the crate `gumdrop_derive`. Such a derived implementation requires that /// the type implement the trait `Default`. pub trait Options: Sized { /// Parses arguments until the given parser is exhausted or until /// an error is encountered. fn parse<S: AsRef<str>>(parser: &mut Parser<S>) -> Result<Self, Error>; /// Returns whether the user supplied a "help" option to request /// usage information about the program or any contained subcommands. /// /// The default implementation returns `false`. fn help_requested(&self) -> bool { false } /// Parses arguments received from the command line. /// /// The first argument (the program name) should be omitted. fn parse_args<S: AsRef<str>>(args: &[S], style: ParsingStyle) -> Result<Self, Error> { Self::parse(&mut Parser::new(args, style)) } /// Parses arguments received from the command line, /// using the default parsing style. /// /// The first argument (the program name) should be omitted. fn parse_args_default<S: AsRef<str>>(args: &[S]) -> Result<Self, Error> { Self::parse(&mut Parser::new(args, ParsingStyle::default())) } /// Parses options for the named command. fn parse_command<S: AsRef<str>>(name: &str, parser: &mut Parser<S>) -> Result<Self, Error>; /// Returns a string showing usage and help for each supported option. /// /// Option descriptions are separated by newlines. The returned string /// should **not** end with a newline. fn usage() -> &'static str; /// Returns a usage string for the named command. /// /// If the named command does not exist, `None` is returned. /// /// Command descriptions are separated by newlines. The returned string /// should **not** end with a newline. fn command_usage(command: &str) -> Option<&'static str>; } /// Controls behavior of free arguments in `Parser` #[derive(Copy, Clone, Debug, Eq, PartialEq)] pub enum ParsingStyle { /// Process all option arguments that appear AllOptions, /// After the first "free" argument is encountered, /// all remaining arguments will be considered "free" arguments. StopAtFirstFree, } impl Default for ParsingStyle { /// Returns the default parsing style, `AllOptions`. fn default() -> ParsingStyle { ParsingStyle::AllOptions } } #[cfg(test)] mod test { use super::{Opt, Parser, ParsingStyle}; #[test] fn test_parser() { let args = &["-a", "b", "-cde", "arg", "-xfoo", "--long", "--opt=val", "--", "y", "-z"]; let mut p = Parser::new(args, ParsingStyle::AllOptions); assert_matches!(p.next_opt(), Some(Opt::Short('a'))); assert_matches!(p.next_opt(), Some(Opt::Free("b"))); assert_matches!(p.next_opt(), Some(Opt::Short('c'))); assert_matches!(p.next_opt(), Some(Opt::Short('d'))); assert_matches!(p.next_opt(), Some(Opt::Short('e'))); assert_matches!(p.next_arg(), Some("arg")); assert_matches!(p.next_opt(), Some(Opt::Short('x'))); assert_matches!(p.next_arg(), Some("foo")); assert_matches!(p.next_opt(), Some(Opt::Long("long"))); assert_matches!(p.next_opt(), Some(Opt::LongWithArg("opt", "val"))); assert_matches!(p.next_opt(), Some(Opt::Free("y"))); assert_matches!(p.next_opt(), Some(Opt::Free("-z"))); assert_matches!(p.next_opt(), None); } #[test] fn test_parsing_style() { let args = &["-a", "b", "-c", "--d"]; let mut p = Parser::new(args, ParsingStyle::AllOptions); assert_matches!(p.next_opt(), Some(Opt::Short('a'))); assert_matches!(p.next_opt(), Some(Opt::Free("b"))); assert_matches!(p.next_opt(), Some(Opt::Short('c'))); assert_matches!(p.next_opt(), Some(Opt::Long("d"))); assert_matches!(p.next_opt(), None); let mut p = Parser::new(args, ParsingStyle::StopAtFirstFree); assert_matches!(p.next_opt(), Some(Opt::Short('a'))); assert_matches!(p.next_opt(), Some(Opt::Free("b"))); assert_matches!(p.next_opt(), Some(Opt::Free("-c"))); assert_matches!(p.next_opt(), Some(Opt::Free("--d"))); assert_matches!(p.next_opt(), None); } }