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 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //! # Capture the Flag //! //! Capture the Flag is a command-line flag parsing library aimed at producing well //! documented command-line interfaces with minimal boiler-plate. //! Flags are defined on the command-line as key-value string pairs which are parsed //! according to their key name and associated type. //! Flags can have the form `--key=value` or `--key value`. If the flag is of type //! `bool`, the flag can simply use `--key`, which implies `--key=true`. //! If specified, a flag can have a short form which begins with a single `-`. //! //! ## How to use //! //! Define a struct where each field represents a flag to parse. //! The parsing code is generated by deriving the trait [`ctflag::Flags`]. //! //! ``` //! # use ctflag::Flags; //! ##[derive(Flags)] //! struct MyFlags { //! enable_floopy: bool, //! output: Option<String>, //! } //! # fn main() {} //! ``` //! //! Parsing the command-line arguments is done by calling the relevant methods of the //! [`ctflag::Flags`] trait. //! //! ``` //! # use ctflag::Flags; //! # #[derive(Flags)] //! # struct MyFlags { //! # enable_floopy: bool, //! # output: Option<String>, //! # } //! # fn main() -> ctflag::Result<()> { //! let (flags, other_args) = MyFlags::from_args(std::env::args())?; //! # Ok(()) //! # } //! ``` //! //! A description of the flags, suitable for use in a help message, can be obtained //! by calling the [`ctflag::Flags::description()`] method. //! //! The behaviour of each flag can be changed using the `#[flag(...)]` attribute. //! //! - `desc = "..."`: Provides a description of the flag, displayed in the //! help text by the [`ctflag::Flags::description()`] method. //! - `placeholder = "..."`: Provides the text that appears in place of the //! flag's value in the help text. Defaults to "VALUE". //! - `default = ...`: For types other than `Optional`, provides a default //! value if the flag is not set on the command-line. This only works with type //! literals (bool, i64, str, etc.). //! - `short = '...'`: A short, single character alias for the flag name. //! //! ``` //! # use ctflag::Flags; //! ##[derive(Flags)] //! struct MyFlags { //! #[flag(desc = "The floopy floops the whoop")] //! enable_floopy: bool, //! //! #[flag(short = 'o', desc = "Output file", placeholder = "PATH")] //! output: Option<String>, //! //! #[flag( //! desc = "How many slomps to include", //! placeholder = "INTEGER", //! default = 34 //! )] //! slomps: i64, //! } //! # fn main() {} //! ``` //! //! The type of each field must implement the [`ctflag::FromArg`] trait. A blanket //! implementation of this trait exists for any type implementing the `FromStr` trait. //! //! ``` //! # use ctflag::{Flags, FromArg, FromArgError, FromArgResult}; //! // A custom type. //! enum Fruit { //! Apple, //! Orange, //! } //! //! impl FromArg for Fruit { //! fn from_arg(s: &str) -> FromArgResult<Self> { //! match s { //! "apple" => Ok(Fruit::Apple), //! "orange" => Ok(Fruit::Orange), //! _ => Err(FromArgError::with_message("bad fruit")), //! } //! } //! } //! //! impl Default for Fruit { //! fn default() -> Self { //! Fruit::Apple //! } //! } //! //! ##[derive(Flags)] //! struct MyFlags { //! fruit: Fruit, //! } //! # fn main() {} //! ``` //! //! [`ctflag::Flags`]: trait.Flags.html //! [`ctflag::FromArg`]: trait.FromArg.html //! [`ctflag::Flags::description()`]: trait.Flags.html#tymethod.description use std::fmt; use std::str::FromStr; // Define the required shared macros first. Definition order is // important for macros. #[macro_use] mod macros; // Users of this library shouldn't need to know that the derive functionality // is in a different crate. #[doc(hidden)] pub use ctflag_derive::*; // Public so that generated code outside of the crate can make use of it. #[doc(hidden)] pub mod internal; #[derive(Clone, Debug)] pub enum FlagError { ParseError(ParseErrorStruct), MissingValue(String), UnrecognizedArg(String), } #[derive(Clone, Debug)] pub struct ParseErrorStruct { pub type_str: &'static str, pub input: String, pub src: FromArgError, } pub type Result<T> = std::result::Result<T, FlagError>; /// Provides a command-line argument parsing implementation when derived /// for a named-struct. /// /// ``` /// # use ctflag::Flags; /// ##[derive(Flags)] /// struct MyFlags { /// enable_floopy: bool, /// // ... /// } /// # fn main() {} /// ``` /// /// Each field in the struct must implement the [`ctflag::FromArgs`] trait. /// /// # Default values /// /// A flag's default value can be specified using the `#[flag(default = ...)]` attribute. /// This attribute only allows the default value to be a type literal. For more /// control over the default value, using an `Option` type is preferred. /// If this attribute is not set, the type must implement the `Default` trait. /// /// Implementing this trait by hand is not recommended and would defeat /// the purpose of this crate. /// /// [`ctflag::FromArgs`]: trait.FromArgs.html pub trait Flags: Sized { /// Consumes the command-line arguments and returns a tuple containing /// the value of this type, and a list of command-line /// arguments that were not consumed. These arguments typically include /// the first command-line argument (usually the program name) and any /// non-flag arguments (no `-` prefix). /// /// # Example /// /// ``` /// # use ctflag::Flags; /// ##[derive(Flags)] /// struct MyFlags { /// enable_floopy: bool, /// // ... /// } /// /// # fn main() -> ctflag::Result<()> { /// let (flags, args) = MyFlags::from_args(std::env::args())?; /// if flags.enable_floopy { /// // ... /// } /// # Ok(()) /// # } /// ``` fn from_args<T>(args: T) -> Result<(Self, Vec<String>)> where T: IntoIterator<Item = String>; /// Returns a String that describes the flags defined in the struct /// implementing this trait. /// /// For a struct like: /// /// ``` /// # use ctflag::Flags; /// ##[derive(Flags)] /// struct MyFlags { /// #[flag(desc = "The floopy floops the whoop")] /// enable_floopy: bool, /// /// #[flag(short = 'o', desc = "Output file", placeholder = "PATH")] /// output: Option<String>, /// /// #[flag( /// desc = "How many slomps to include", /// placeholder = "INTEGER", /// default = 34 /// )] /// slomps: i64, /// } /// # fn main() {} /// ``` /// /// The returned String looks something like: /// /// ```text /// OPTIONS: /// --enable_floopy The floopy floops the whoop /// -o, --output [PATH] Output file /// --slomps INTEGER How many slomps to include (defaults to 34) /// ``` fn description() -> String; } #[derive(Clone, Debug)] pub struct FromArgError { msg: Option<String>, } pub type FromArgResult<T> = std::result::Result<T, FromArgError>; /// Any type declared in a struct that derives [`ctflag::Flags`] must implement /// this trait. A blanket implementation exists for types implementing `FromStr`. /// Custom types can implement this trait directly. /// /// [`ctflag::Flags`]: trait.Flags.html /// /// ``` /// # use ctflag::{Flags, FromArg, FromArgError, FromArgResult}; /// enum Fruit { /// Apple, /// Orange, /// } /// /// impl FromArg for Fruit { /// fn from_arg(s: &str) -> FromArgResult<Self> { /// match s { /// "apple" => Ok(Fruit::Apple), /// "orange" => Ok(Fruit::Orange), /// _ => Err(FromArgError::with_message("bad fruit")), /// } /// } /// } /// ``` pub trait FromArg: Sized { /// Parses a string `s` to return the value of this type. /// /// If parsing succeeds, return the value inside an `Ok`, otherwise /// return an error using [`ctflag::FromArgError::with_message`] inside /// an `Err`. /// [`ctflag::FromArgError::with_message`]: struct.FromArgError.html#method.with_message fn from_arg(value: &str) -> FromArgResult<Self>; } impl<T> FromArg for T where T: FromStr, { fn from_arg(s: &str) -> FromArgResult<T> { <T as FromStr>::from_str(s).map_err(|_| FromArgError::new()) } } impl fmt::Display for FlagError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { FlagError::ParseError(err) => { write!( f, "failed to parse \"{}\" as {} type", &err.input, err.type_str )?; if let Some(msg) = &err.src.msg { write!(f, ": {}", msg)?; } } FlagError::MissingValue(arg) => { write!(f, "missing value for argument \"{}\"", arg)?; } FlagError::UnrecognizedArg(arg) => { write!(f, "unrecognized argument \"{}\"", arg)?; } } Ok(()) } } impl FromArgError { fn new() -> Self { FromArgError { msg: None } } pub fn with_message<T>(msg: T) -> Self where T: fmt::Display, { FromArgError { msg: Some(format!("{}", msg)), } } } #[cfg(test)] mod tests { use super::*; // Since we are inside the ctflag crate, alias crate to ctflag. use crate as ctflag; #[derive(Flags)] struct Simple { one: String, two: Option<String>, three: bool, four: Option<bool>, five: i32, six: Option<i32>, seven: CustomType, } #[derive(Debug, PartialEq, Eq)] struct CustomType(&'static str); impl ctflag::FromArg for CustomType { fn from_arg(value: &str) -> ctflag::FromArgResult<Self> { match value { "foo" => Ok(CustomType("foo")), _ => { Err(ctflag::FromArgError::with_message("expected \"foo\"")) } } } } impl Default for CustomType { fn default() -> Self { CustomType("default") } } #[test] fn test_defaults() { let args = vec![String::from("prog_name")]; let (flags, rest) = Simple::from_args(args).unwrap(); assert_eq!(flags.one, ""); assert_eq!(flags.two, None); assert_eq!(flags.three, false); assert_eq!(flags.four, None); assert_eq!(flags.five, 0); assert_eq!(flags.six, None); assert_eq!(flags.seven, CustomType("default")); assert_eq!(rest.len(), 1); assert_eq!(rest[0], "prog_name"); } #[test] fn test_using_eq() { let args = vec![String::from("prog_name"), String::from("--one=hello")]; let (flags, _rest) = Simple::from_args(args).unwrap(); assert_eq!(flags.one, "hello"); } #[test] fn test_using_space() { let args = vec![ String::from("prog_name"), String::from("--one"), String::from("hello"), ]; let (flags, _rest) = Simple::from_args(args).unwrap(); assert_eq!(flags.one, "hello"); } #[test] fn test_bool_using_eq() { let args = vec![String::from("prog_name"), String::from("--three=true")]; let (flags, _rest) = Simple::from_args(args).unwrap(); assert_eq!(flags.three, true); } #[test] fn test_bool_using_space() { let args = vec![ String::from("prog_name"), String::from("--three"), String::from("false"), ]; let (flags, rest) = Simple::from_args(args).unwrap(); assert_eq!(flags.three, true); assert_eq!(rest.len(), 2); assert_eq!(rest[1], "false"); } #[test] fn test_option_using_eq() { let args = vec![String::from("prog_name"), String::from("--two=hello")]; let (flags, _rest) = Simple::from_args(args).unwrap(); assert_eq!(flags.two, Some(String::from("hello"))); } #[test] fn test_option_using_space() { let args = vec![ String::from("prog_name"), String::from("--two"), String::from("hello"), ]; let (flags, _rest) = Simple::from_args(args).unwrap(); assert_eq!(flags.two, Some(String::from("hello"))); } #[test] fn test_custom_type_using_eq() { let args = vec![String::from("prog_name"), String::from("--seven=foo")]; let (flags, _rest) = Simple::from_args(args).unwrap(); assert_eq!(flags.seven, CustomType("foo")); } #[test] fn test_custom_type_using_space() { let args = vec![ String::from("prog_name"), String::from("--seven"), String::from("foo"), ]; let (flags, _rest) = Simple::from_args(args).unwrap(); assert_eq!(flags.seven, CustomType("foo")); } #[test] fn test_int() { let args = vec![ String::from("prog_name"), String::from("--five=23"), String::from("--six=42"), ]; let (flags, _rest) = Simple::from_args(args).unwrap(); assert_eq!(flags.five, 23); assert_eq!(flags.six, Some(42)); } #[test] fn test_missing_value() { let args = vec![String::from("prog_name"), String::from("--one")]; assert_matches!( Simple::from_args(args), Err(ctflag::FlagError::MissingValue(_)) ); } #[test] fn test_bad_int() { let args = vec![String::from("prog_name"), String::from("--five=hello")]; assert_matches!( Simple::from_args(args), Err(ctflag::FlagError::ParseError(_)) ); } #[test] fn test_bad_bool() { let args = vec![String::from("prog_name"), String::from("--three=yes")]; assert_matches!( Simple::from_args(args), Err(ctflag::FlagError::ParseError(_)) ); } #[derive(Flags)] struct DefaultFlags { #[flag(default = 12)] one: i32, #[flag(default = "foo")] two: String, #[flag(default = "foo")] three: CustomType, #[flag(default = "bar")] four: NoDefaultCustomType, } #[derive(Debug, PartialEq, Eq)] struct NoDefaultCustomType(&'static str); impl ctflag::FromArg for NoDefaultCustomType { fn from_arg(value: &str) -> ctflag::FromArgResult<Self> { match value { "bar" => Ok(NoDefaultCustomType("bar")), _ => { Err(ctflag::FromArgError::with_message("expected \"bar\"")) } } } } #[test] fn test_custom_defaults() { let args = vec![String::from("prog_name")]; let (flags, _rest) = DefaultFlags::from_args(args).unwrap(); assert_eq!(flags.one, 12); assert_eq!(flags.two, "foo"); assert_eq!(flags.three, CustomType("foo")); assert_eq!(flags.four, NoDefaultCustomType("bar")); } #[allow(dead_code)] #[derive(Flags)] struct BadDefault { #[flag(default = "bad")] one: CustomType, } #[test] #[should_panic] fn test_bad_default() { let args = vec![String::from("prog_name")]; let _result = BadDefault::from_args(args); } #[allow(dead_code)] #[derive(Flags)] struct Description { #[flag(desc = "Howdy", default = "foo", placeholder = "THING")] one: String, #[flag(short = 't', desc = "Boom", placeholder = "VROOM")] two: Option<i32>, } #[test] fn test_description() { let desc: String = Description::description(); assert!( desc.contains(" --one THING Howdy (defaults to \"foo\")") ); assert!(desc.contains("-t, --two [VROOM] Boom")); } #[derive(Flags)] struct ShortFlag { #[flag(short = 'o')] output: String, } #[test] fn test_short_name_using_eq() { let args = vec![String::from("prog_name"), String::from("-o=file")]; let (flags, _rest) = ShortFlag::from_args(args).unwrap(); assert_eq!(flags.output, "file"); } #[test] fn test_short_name_using_space() { let args = vec![ String::from("prog_name"), String::from("-o"), String::from("file"), ]; let (flags, _rest) = ShortFlag::from_args(args).unwrap(); assert_eq!(flags.output, "file"); } }