winnow_args/lib.rs
1//! Command line parsing built from [winnow] parsers.
2//!
3//! winnow-args parses a program's arguments into typed values, typically a
4//! struct with one field per flag or positional. It distinguishes:
5//!
6//! - **flags**, long (`--verbose`) or short (`-v`); short flags can be bundled,
7//! `-vq` for `-v -q`;
8//! - **values** of flags, given as the next word (`--path /tmp`, `-p /tmp`) or
9//! attached (`--path=/tmp`, `-p/tmp`);
10//! - **positionals**, words identified by their position: `a` and `b` in
11//! `cp a b`;
12//! - **subcommands**, words that select a command with arguments of its own:
13//! `add` in `git add -p`;
14//! - `--`, after which every word is a positional.
15//!
16//! A failed parse returns an [`Error`] with its kind, the word at fault and its
17//! offset.
18//!
19//! There are two ways to say which of these a program takes:
20//!
21//! - `#[derive(Args)]` on a struct. A field is a flag or a positional, its type
22//! says how many values it takes and what they convert to, and its doc comment
23//! is its help. This is what most programs want, and the faster of the two.
24//! - By hand, with [`combinator`]. A flag is a [winnow] parser, and
25//! `alt`, `repeat` and the rest of winnow combine flags into a command line.
26//!
27//! Either way the words are read where the shell left them: nothing is copied or
28//! re-split, and the bytes need not be UTF-8 until a value's type asks for text.
29//! Both also cover command lines older than `--long`: `+x` options as in a bash
30//! builtin, and flags whose order matters as in `ld`.
31//!
32// The example needs the `derive` feature.
33#![cfg_attr(feature = "derive", doc = "```")]
34#![cfg_attr(not(feature = "derive"), doc = "```ignore")]
35//! use std::path::PathBuf;
36//! use winnow_args::Args;
37//!
38//! /// Look somewhere.
39//! #[derive(Args, Debug)]
40//! struct Cli {
41//! /// Say more.
42//! #[arg(short, long)]
43//! verbose: bool,
44//! /// Where to look.
45//! #[arg(short, long)]
46//! path: Option<PathBuf>,
47//! #[arg(positional)]
48//! files: Vec<String>,
49//! }
50//!
51//! // In `main`: `let cli = Cli::parse();`
52//! let cli = Cli::parse_from(["-v", "--path=/tmp", "a", "b"])?;
53//! assert!(cli.verbose);
54//! assert_eq!(cli.path, Some(PathBuf::from("/tmp")));
55//! assert_eq!(cli.files, ["a", "b"]);
56//! # Ok::<(), winnow_args::Error>(())
57//! ```
58//!
59//! # Where to look
60//!
61#![cfg_attr(
62 feature = "derive",
63 doc = "- [`derive@Args`], [`derive@Subcommand`], [`derive@ValueEnum`] and [`derive@Occurrence`]:
64 the derives. Each page lists every attribute it takes."
65)]
66//! - [`combinator`]: the same command lines written by hand, and [`token`],
67//! the lexer under both.
68//! - [`FromArg`]: what a value can be, and the types in [`value`] for a
69//! `FromStr` type, a C-syntax number and `key=value`.
70//! - [`Error`] and [`report`]: what a failed parse holds, and how it is printed,
71//! with a tip when something close to what was typed is accepted.
72//! - [`help`] and [`color`]: the help text and its theme. A description's
73//! `` `quoted` ``, `*emphasized*` and `**strong**` spans are painted, each
74//! by a paint of its own in [`color::Palette`].
75//! - [`complete`]: completion scripts for bash, zsh, fish, elvish and
76//! PowerShell, for flags, subcommands and values.
77//! - [`response`]: `@file` words.
78//! - [`run`]: calling the command a line selected, with `#[arg(run)]` on the
79//! enum of subcommands.
80//! - [`with_env`]: a test's own environment variables.
81//!
82//! Man and markdown pages are made by `winnow-args-man` and
83//! `winnow-args-markdown`, from what the derives write when the environment
84//! variable `WINNOW_ARGS_SPEC` names a directory; the derive crate's
85//! documentation says how.
86//!
87//! # Entry points
88//!
89//! - [`Args::parse`] in `main`. Help, version and a failure are printed, and
90//! the process exits.
91//! - [`Args::try_parse`] returns the [`Error`] for the caller to handle.
92//! - [`Args::parse_from`] takes the words after the program name: what a test
93//! calls.
94//! - [`Args::parse_from_argv`] takes the whole line, program name first.
95//! - [`Args::parse_words`] takes words that are already [`BStr`]s.
96//! - [`Args::completion_request`] goes before any of them in a program that
97//! has [`complete`] scripts.
98//!
99//! # Performance
100//!
101//! The parser is generated at compile time, so a parse costs the same however
102//! many commands the program declares; clap and bpaf build theirs at each
103//! start. A parse is a few thousand instructions and a few hundred
104//! nanoseconds. The measurements, against clap, bpaf and usage, and the
105//! method are in the repository's
106//! [benchmarks](https://github.com/lu-zero/winnow-args/tree/HEAD/benchmarks).
107//!
108//! # Cargo features
109//!
110//! - `derive` (default): the derives.
111//! - `help-text` (default): the prose of derived help. Without it, help still
112//! lists commands, flags, values and defaults, and the binary is smaller.
113//! - `terminal-size`: wrap help to the terminal's width when `COLUMNS` is unset.
114//!
115//! # From clap and usage
116//!
117//! The spellings that differ. Everything else is on the derive's own page.
118//!
119//! | | clap | usage | winnow-args |
120//! |---|---|---|---|
121//! | the command | `#[derive(Parser)]` | `#[derive(Cli)]` | `#[derive(Args)]` |
122//! | its name, its version | `#[command(name, version)]` | `#[usage(bin, version)]` | `#[arg(name, version)]` |
123//! | an attribute | `#[arg]`, `#[command]` | `#[usage]` | `#[arg]` |
124//! | subcommands | `#[derive(Subcommand)]` | `#[derive(Subcommands)]` | `#[derive(Subcommand)]` |
125//! | words after the program name | none: the name comes first | `parse_from` | `parse_from` |
126//! | the whole line | `try_parse_from` | `parse_from_argv` | `parse_from_argv` |
127//! | a count | `action = ArgAction::Count` | `count` | `count` |
128//! | a positional | no `long` or `short` | no `short` or `long` | `#[arg(positional)]` |
129//! | a field with no attribute | a positional | a positional | `--field-name` |
130//! | a default, an environment variable | `default_value`, `env` | `default`, `env` | `default`, `env` |
131//! | several words, a delimiter | `num_args`, `value_delimiter` | `num_args`, `delimiter` | `values`, `delimiter` |
132//! | a value that may be left off | `default_missing_value` | `default_missing` | `default_missing` |
133//! | choices from an enum | `#[arg(value_enum)]` | `#[usage(value_enum)]` | the type derives `ValueEnum` |
134//! | a conflict | `conflicts_with = "file"` | `conflicts("--file")` | `conflicts("--file")` |
135//! | the flag that clears a switch | `ArgAction::SetFalse` | `negate = "--no-force"` | `negate = "no-force"` |
136//! | shared flags | `#[command(flatten)]` | `#[usage(flatten)]` | `#[arg(flatten)]` |
137//! | a subcommand field | `#[command(subcommand)]` | `#[usage(subcommand)]` | `#[arg(subcommand)]` |
138//! | an unknown flag | an error | a value, unless `unknown_flags = "error"` | an error, unless `unknown_flags = "value"` |
139
140pub mod color;
141pub mod combinator;
142pub mod complete;
143pub mod env;
144pub mod error;
145pub mod help;
146pub mod response;
147pub mod run;
148pub mod stream;
149pub mod token;
150pub mod value;
151
152pub use env::with_env;
153pub use error::{Error, ErrorKind};
154pub use stream::{Argv, words};
155pub use token::Arg;
156pub use value::{ChoiceError, FromArg};
157/// A word of the command line, and a flag's value: bytes, not necessarily
158/// UTF-8. What [`FromArg::from_arg`] is given.
159pub use winnow::stream::BStr;
160
161#[cfg(feature = "derive")]
162pub use winnow_args_derive::{Args, Occurrence, Subcommand, ValueEnum};
163
164// The README's example is compiled as a doctest.
165#[cfg(all(doctest, feature = "derive"))]
166#[doc = include_str!("../README.md")]
167pub struct Readme;
168
169// The derive crate cannot call `parse_from`, so these examples are tested here.
170#[cfg(all(doctest, feature = "derive"))]
171pub mod derive_examples {
172 //! ```
173 //! use winnow_args::Args;
174 //!
175 //! /// Copy files.
176 //! #[derive(Args, Debug)]
177 //! #[arg(name = "cp", version)]
178 //! struct Cp {
179 //! /// Explain what is done; repeat for more.
180 //! #[arg(short, long, count)]
181 //! verbose: u8,
182 //! /// Overwrite without asking.
183 //! #[arg(short, long, negate)]
184 //! force: bool,
185 //! /// Attributes to keep.
186 //! #[arg(long, delimiter = ',')]
187 //! preserve: Vec<String>,
188 //! /// Jobs to run.
189 //! #[arg(short, long, env = "CP_JOBS", default = "1")]
190 //! jobs: usize,
191 //! #[arg(positional)]
192 //! source: String,
193 //! #[arg(positional)]
194 //! dest: Option<String>,
195 //! }
196 //!
197 //! let cp = Cp::parse_from(["-vvf", "--preserve=mode,links", "a", "--no-force", "b"])?;
198 //! assert_eq!((cp.verbose, cp.force, cp.jobs), (2, false, 1));
199 //! assert_eq!(cp.preserve, ["mode", "links"]);
200 //! assert_eq!((cp.source.as_str(), cp.dest.as_deref()), ("a", Some("b")));
201 //! # Ok::<(), winnow_args::Error>(())
202 //! ```
203 //!
204 //! ```
205 //! use winnow_args::{Args, Subcommand};
206 //!
207 //! #[derive(Args, Debug, PartialEq)]
208 //! struct Add {
209 //! #[arg(positional)]
210 //! paths: Vec<String>,
211 //! }
212 //!
213 //! #[derive(Subcommand, Debug, PartialEq)]
214 //! enum Command {
215 //! /// Stage files.
216 //! Add(Add),
217 //! /// Show what changed.
218 //! #[arg(alias = "st")]
219 //! Status,
220 //! }
221 //!
222 //! #[derive(Args, Debug)]
223 //! struct Git {
224 //! /// Say less.
225 //! #[arg(short, long, global)]
226 //! quiet: bool,
227 //! #[arg(subcommand)]
228 //! command: Command,
229 //! }
230 //!
231 //! let git = Git::parse_from(["add", "-q", "a", "b"])?;
232 //! assert!(git.quiet);
233 //! assert_eq!(git.command, Command::Add(Add { paths: vec!["a".into(), "b".into()] }));
234 //! assert_eq!(Git::parse_from(["st"])?.command, Command::Status);
235 //!
236 //! match git.command {
237 //! Command::Add(Add { paths }) => println!("staging {paths:?}"),
238 //! Command::Status => println!("on branch main"),
239 //! }
240 //! # Ok::<(), winnow_args::Error>(())
241 //! ```
242 //!
243 //! ```
244 //! use winnow_args::{Args, Occurrence};
245 //!
246 //! #[derive(Occurrence, Debug, PartialEq)]
247 //! enum Item {
248 //! /// Link what follows only if needed.
249 //! #[arg(long)]
250 //! AsNeeded,
251 //! /// Search for a library.
252 //! #[arg(short = 'l', prefix)]
253 //! Library(String),
254 //! #[arg(positional, value_name = "FILE")]
255 //! Input(String),
256 //! }
257 //!
258 //! #[derive(Args, Debug)]
259 //! struct Ld {
260 //! #[arg(short, long)]
261 //! output: Option<String>,
262 //! #[arg(sequence)]
263 //! items: Vec<Item>,
264 //! }
265 //!
266 //! let ld = Ld::parse_from(["a.o", "--as-needed", "-lm", "-o", "out", "b.o"])?;
267 //! assert_eq!(ld.output.as_deref(), Some("out"));
268 //! assert_eq!(
269 //! ld.items,
270 //! [
271 //! Item::Input("a.o".into()),
272 //! Item::AsNeeded,
273 //! Item::Library("m".into()),
274 //! Item::Input("b.o".into()),
275 //! ]
276 //! );
277 //! # Ok::<(), winnow_args::Error>(())
278 //! ```
279 //!
280 //! ```
281 //! use winnow_args::{Args, ErrorKind, ValueEnum};
282 //!
283 //! #[derive(ValueEnum, Debug, PartialEq)]
284 //! enum Color {
285 //! Always,
286 //! #[arg(alias = "no")]
287 //! Never,
288 //! #[arg(name = "auto")]
289 //! WhenTerminal,
290 //! }
291 //!
292 //! #[derive(Args, Debug)]
293 //! struct Cli {
294 //! #[arg(long)]
295 //! color: Option<Color>,
296 //! }
297 //!
298 //! assert_eq!(Cli::parse_from(["--color=auto"])?.color, Some(Color::WhenTerminal));
299 //! assert_eq!(Cli::parse_from(["--color", "no"])?.color, Some(Color::Never));
300 //! let error = Cli::parse_from(["--color=red"]).unwrap_err();
301 //! assert_eq!(error.kind(), ErrorKind::InvalidChoice);
302 //! # Ok::<(), winnow_args::Error>(())
303 //! ```
304}
305
306/// A type parsed from a whole command line.
307pub trait Args: Sized {
308 /// The name the derive files this type under when the documentation is
309 /// built. Empty for an implementation written by hand.
310 #[doc(hidden)]
311 const SPEC: &'static str = "";
312
313 /// Parse the command line in `input`, consuming all of it.
314 ///
315 /// This is a winnow parser: `Cli::parse_argv` can be passed anywhere a
316 /// `Parser<Argv, Cli, Error>` is expected.
317 fn parse_argv(input: &mut Argv<'_>) -> Result<Self, Error> {
318 Self::parse_argv_with(input, &mut ())
319 }
320
321 /// [`Args::parse_argv`] as a subcommand: flags it does not declare itself
322 /// are offered to `globals`, its ancestors' global flags.
323 fn parse_argv_with(input: &mut Argv<'_>, globals: &mut dyn Globals) -> Result<Self, Error>;
324
325 /// [`Args::HELP`], from where the type is. A constant is built again in
326 /// each crate that names it, and help is large: the derive writes this
327 /// beside the type, so a program in another crate has the one copy.
328 #[doc(hidden)]
329 fn help_data() -> &'static help::Command {
330 Self::HELP
331 }
332
333 /// This command's help, rendered only when asked for.
334 const HELP: &'static help::Command = &help::Command {
335 name: "",
336 about: "",
337 long_about: "",
338 after_help: "",
339 after_long_help: "",
340 items: &[],
341 subcommands: &[],
342 subcommand_required: false,
343 help_flag: false,
344 help_short: false,
345 version: None,
346 };
347
348 /// Answer a completion script's callback (`PROG __complete_word__ …`)
349 /// from this command's help data; `None` when `args` (the command line
350 /// after the program's name) is not one. See [`complete`].
351 fn completion_request(args: &[std::ffi::OsString]) -> Option<String> {
352 complete::answer(Self::help_data(), args)
353 }
354
355 /// The completion script for `shell`, calling back the program named in
356 /// the help data (`#[arg(name = "…")]`).
357 ///
358 /// # Panics
359 ///
360 /// If the command has no name, or one that is not a plain word.
361 fn completion_script(shell: complete::Shell) -> String {
362 complete::script(Self::HELP.name, shell)
363 }
364
365 /// Parse `words`, the arguments after the program name, already borrowed
366 /// as [`BStr`]s: what [`response::expand`] and [`words`] give. Nothing is
367 /// copied.
368 ///
369 /// An unknown flag or subcommand that is close to one of the program's
370 /// has it as [`Error::similar`].
371 fn parse_words(words: &[&BStr]) -> Result<Self, Error> {
372 Self::parse_argv(&mut Argv::new(words)).map_err(|error| error.suggested(Self::help_data()))
373 }
374
375 /// Parse `argv`, the whole command line, program name first. The name is
376 /// skipped.
377 fn parse_from_argv<I, S>(argv: I) -> Result<Self, Error>
378 where
379 I: IntoIterator<Item = S>,
380 S: AsRef<std::ffi::OsStr>,
381 {
382 Self::parse_from(argv.into_iter().skip(1))
383 }
384
385 /// Parse `args`, the arguments after the program name.
386 ///
387 /// ```
388 /// # #[cfg(feature = "derive")] {
389 /// use winnow_args::{Args, ErrorKind};
390 ///
391 /// #[derive(Args)]
392 /// struct Cli {
393 /// #[arg(short, long)]
394 /// verbose: bool,
395 /// }
396 ///
397 /// assert!(Cli::parse_from(["-v"]).unwrap().verbose);
398 /// assert!(Cli::parse_from_argv(["prog", "-v"]).unwrap().verbose);
399 /// let error = Cli::parse_from(["--loud"]).err().unwrap();
400 /// assert_eq!(error.kind(), ErrorKind::UnknownFlag);
401 /// # }
402 /// ```
403 fn parse_from<I, S>(args: I) -> Result<Self, Error>
404 where
405 I: IntoIterator<Item = S>,
406 S: AsRef<std::ffi::OsStr>,
407 {
408 let args: Vec<S> = args.into_iter().collect();
409 Self::parse_words(&words(&args))
410 }
411
412 /// Parse the process's arguments; on help, version or a failure, print
413 /// and exit as [`report`] does. It answers no completion callback: call
414 /// [`Args::completion_request`] first if the program has [`complete`] scripts.
415 fn parse() -> Self {
416 match Self::try_parse() {
417 Ok(parsed) => parsed,
418 Err(error) => std::process::exit(report(&error, &Self::program())),
419 }
420 }
421
422 /// Parse the process's arguments, leaving help, version and failures to
423 /// the caller: [`Args::parse`] without the printing and the exit.
424 ///
425 /// ```no_run
426 /// # #[cfg(feature = "derive")] {
427 /// use winnow_args::Args;
428 ///
429 /// #[derive(Args)]
430 /// struct Cli {
431 /// #[arg(short, long)]
432 /// verbose: bool,
433 /// }
434 ///
435 /// let cli = match Cli::try_parse() {
436 /// Ok(cli) => cli,
437 /// Err(error) => std::process::exit(winnow_args::report(&error, &Cli::program())),
438 /// };
439 /// # let _ = cli.verbose;
440 /// # }
441 /// ```
442 fn try_parse() -> Result<Self, Error> {
443 Self::parse_from_argv(std::env::args_os())
444 }
445
446 /// The program's name, as messages give it: `#[arg(name = "…")]`, else
447 /// the file name the process was run as.
448 fn program() -> String {
449 if !Self::HELP.name.is_empty() {
450 return Self::HELP.name.to_owned();
451 }
452 let argv0 = std::env::args_os().next().unwrap_or_default();
453 std::path::Path::new(&argv0)
454 .file_name()
455 .map(|name| name.to_string_lossy().into_owned())
456 .unwrap_or_default()
457 }
458}
459
460/// Print what a failed parse means, and give the exit status: help and version
461/// on stdout with 0, a bare `arg_required_else_help` invocation's help on stderr
462/// with 2, anything else as an error on stderr with 2. Colored with
463/// [`color::Theme::DEFAULT`] where the stream written to shows color; see
464/// [`report_with`] for another theme.
465pub fn report(error: &Error, program: &str) -> i32 {
466 report_with(error, program, &color::Theme::DEFAULT)
467}
468
469/// [`report`], painted with `theme`: its palette for the depth
470/// [`color::Depth::detect`] finds on the stream written to.
471///
472/// ```
473/// use winnow_args::color::{Paint, Palette, Theme};
474///
475/// // Bold, uncolored headers on 16-color terminals; the default elsewhere.
476/// const THEME: Theme = Theme {
477/// ansi16: Palette { header: Paint::NONE.bold(), ..Palette::DEFAULT },
478/// ..Theme::DEFAULT
479/// };
480/// # let _ = |e: &winnow_args::Error| winnow_args::report_with(e, "prog", &THEME);
481/// ```
482pub fn report_with(error: &Error, program: &str, theme: &color::Theme) -> i32 {
483 use std::io::IsTerminal as _;
484 let stdout = || help::Style::themed(theme, std::io::stdout().is_terminal());
485 let stderr = || help::Style::themed(theme, std::io::stderr().is_terminal());
486 // Help goes to stdout, except a bare invocation's, which is an error.
487 let bare = error.is_bare_help();
488 let style = if bare { stderr() } else { stdout() };
489 if let Some(help) = error.render_help_styled(program, style) {
490 if bare {
491 eprintln!("{help}");
492 return 2;
493 }
494 println!("{help}");
495 return 0;
496 }
497 if let Some(version) = error.version_text(program) {
498 println!("{version}");
499 return 0;
500 }
501 eprintln!("{}", error.render(stderr()));
502 2
503}
504
505/// Flags and words kept in command-line order: an enum deriving `Occurrence`,
506/// one variant per flag or positional, collected by an `#[arg(sequence)]`
507/// `Vec` field of an [`Args`] struct.
508///
509/// For command lines where position is meaning, as `ld`'s: `--as-needed` and
510/// `--whole-archive` apply to the inputs after them, so the linker folds the
511/// sequence rather than reading fields.
512pub trait Occurrence: Sized {
513 /// The name the derive files this type under when the documentation is
514 /// built. Empty for an implementation written by hand.
515 #[doc(hidden)]
516 const SPEC: &'static str = "";
517
518 /// Letters that always take the rest of their word (`-lfoo`), for a
519 /// `long_only` parent: no single-dash long name starting with one is tried.
520 const PREFIXES: &'static [u8] = &[];
521
522 /// `arg` as one of the variants, its value read from `input`; `None` when
523 /// no variant is spelled so.
524 fn from_arg<'i>(arg: &Arg<'i>, input: &mut Argv<'i>) -> Result<Option<Self>, Error>;
525
526 /// A word as the positional variant; `None` if there is none.
527 fn from_word(word: &token::Word<'_>) -> Result<Option<Self>, Error>;
528
529 /// Whether `name` is a variant's long name that may be spelled with one
530 /// dash, for a `long_only` parent.
531 fn is_long(name: &[u8]) -> bool;
532
533 /// The variants as help lists them, after the parent's own flags.
534 const ITEMS: &'static [help::Item] = &[];
535
536 /// Whether there is a positional variant: each plain word is that variant.
537 const POSITIONAL: bool = false;
538
539 /// Whether there is an `#[arg(bundle)]` variant.
540 const BUNDLES: bool = false;
541
542 /// A word of several short flags (`-sS`), whole, as the `#[arg(bundle)]`
543 /// variant: an item put before those of its letters, whoever takes them,
544 /// for a program that reports grouping (GNU ld deprecates it). `None` if
545 /// there is none.
546 fn from_bundle(word: &token::Word<'_>) -> Result<Option<Self>, Error> {
547 let _ = word;
548 Ok(None)
549 }
550
551 /// A flag no variant names, as the `#[arg(unknown)]` variant; `None` if
552 /// there is none. Asked by a parent whose field is
553 /// `#[arg(sequence, unknown)]`.
554 fn from_unknown(word: &token::Word<'_>) -> Result<Option<Self>, Error> {
555 let _ = word;
556 Ok(None)
557 }
558
559 /// Whether `letter` is a variant's short flag, and whether it takes a
560 /// value: how a parent with an `unknown` field tells an unknown bundle.
561 fn short(letter: char) -> Option<bool> {
562 let _ = letter;
563 None
564 }
565}
566
567/// An enum of subcommands, selected by a word.
568///
569/// Derived with `#[derive(Subcommand)]`; a struct holds one in an
570/// `#[arg(subcommand)]` field. The derive also implements [`Args`] for the enum,
571/// so it can be the whole command line.
572pub trait Subcommand: Sized {
573 /// The name the derive files this type under when the documentation is
574 /// built. Empty for an implementation written by hand.
575 #[doc(hidden)]
576 const SPEC: &'static str = "";
577
578 /// Whether `name` names a subcommand. Asked of every eligible word, so kept
579 /// apart from [`Subcommand::parse_subcommand`] and cheap to inline.
580 fn has(name: &[u8]) -> bool;
581
582 /// Parse the rest of `input` as the subcommand `name`, which [`Subcommand::has`];
583 /// `globals` binds its ancestors' global flags.
584 fn parse_subcommand(
585 name: &[u8],
586 input: &mut Argv<'_>,
587 globals: &mut dyn Globals,
588 ) -> Result<Self, Error>;
589}
590
591/// The global flags of a subcommand's ancestors, which it accepts as its own.
592///
593/// A parent hands one down to its subcommand; the subcommand offers it every
594/// flag it does not declare, so its own declarations take precedence.
595pub trait Globals {
596 /// Bind `arg`, read from `input`, if it is a global flag; `Ok(false)` if not.
597 fn bind<'i>(&mut self, arg: &Arg<'i>, input: &mut Argv<'i>) -> Result<bool, Error>;
598
599 /// Whether `-letter` is one of these flags, and if so whether it takes a
600 /// value. A command with `unknown_flags = "value"` asks about every letter
601 /// of a bundle before binding any.
602 fn short(&self, letter: char) -> Option<bool> {
603 let _ = letter;
604 None
605 }
606}
607
608/// No global flags: what a command line's root is given.
609impl Globals for () {
610 #[inline]
611 fn bind<'i>(&mut self, _: &Arg<'i>, _: &mut Argv<'i>) -> Result<bool, Error> {
612 Ok(false)
613 }
614}
615
616/// [`Globals`] from a closure. It does not answer [`Globals::short`]: the derive
617/// calls `inherit`, which forwards the parent's letters, so a lenient
618/// subcommand still sees them.
619pub fn globals<F>(bind: F) -> impl Globals
620where
621 F: for<'i> FnMut(&Arg<'i>, &mut Argv<'i>) -> Result<bool, Error>,
622{
623 struct FromFn<F>(F);
624 impl<F> Globals for FromFn<F>
625 where
626 F: for<'i> FnMut(&Arg<'i>, &mut Argv<'i>) -> Result<bool, Error>,
627 {
628 #[inline]
629 fn bind<'i>(&mut self, arg: &Arg<'i>, input: &mut Argv<'i>) -> Result<bool, Error> {
630 (self.0)(arg, input)
631 }
632 }
633 FromFn(bind)
634}
635
636/// [`Globals`] that are `shorts` (letter, takes a value), those `flattened`
637/// answers for, and `bind`, then `parent`'s: what the derive hands a
638/// subcommand of a struct with global flags, its own or of a struct it
639/// flattens. Unlike [`globals`], `short` sees those letters.
640#[doc(hidden)]
641pub fn inherit<'a, F>(
642 shorts: &'static [(char, bool)],
643 flattened: fn(char) -> Option<bool>,
644 parent: &'a mut dyn Globals,
645 bind: F,
646) -> impl Globals + 'a
647where
648 F: for<'i> FnMut(&Arg<'i>, &mut Argv<'i>, &mut dyn Globals) -> Result<bool, Error> + 'a,
649{
650 struct Inherit<'a, F> {
651 shorts: &'static [(char, bool)],
652 flattened: fn(char) -> Option<bool>,
653 parent: &'a mut dyn Globals,
654 bind: F,
655 }
656 impl<F> Globals for Inherit<'_, F>
657 where
658 F: for<'i> FnMut(&Arg<'i>, &mut Argv<'i>, &mut dyn Globals) -> Result<bool, Error>,
659 {
660 #[inline]
661 fn bind<'i>(&mut self, arg: &Arg<'i>, input: &mut Argv<'i>) -> Result<bool, Error> {
662 (self.bind)(arg, input, &mut *self.parent)
663 }
664
665 fn short(&self, letter: char) -> Option<bool> {
666 match self.shorts.iter().find(|(c, _)| *c == letter) {
667 Some(&(_, takes_value)) => Some(takes_value),
668 None => (self.flattened)(letter).or_else(|| self.parent.short(letter)),
669 }
670 }
671 }
672 Inherit {
673 shorts,
674 flattened,
675 parent,
676 bind,
677 }
678}
679
680/// Help prose the derive emits: kept with the `help-text` feature.
681#[cfg(feature = "help-text")]
682#[doc(hidden)]
683#[macro_export]
684macro_rules! __text {
685 ($text:literal) => {
686 $text
687 };
688}
689
690/// Help prose the derive emits: `""` without the `help-text` feature.
691#[cfg(not(feature = "help-text"))]
692#[doc(hidden)]
693#[macro_export]
694macro_rules! __text {
695 ($text:literal) => {
696 ""
697 };
698}
699
700#[doc(hidden)]
701pub mod __private {
702 pub use crate::env;
703 pub use crate::error::Error;
704 pub use crate::help::concat_items;
705 pub use crate::stream::Argv;
706 pub use crate::token::{Arg, ValueOptions, Word, arg, arg_plus, long_only, number, split};
707 pub use crate::value::{ChoiceError, FromArg, documented_choices, filed_as, stated_choices};
708 pub use crate::{Globals, Subcommand, globals, inherit};
709 pub use winnow::stream::BStr;
710 pub type BoxError = crate::error::BoxError;
711
712 use crate::token::is_flag_like;
713
714 /// The flags of a struct that another flattens (`#[arg(flatten)]`), derived
715 /// for every `Args` struct that has flags only.
716 ///
717 /// The parent keeps a [`Flatten::Slots`], offers it each flag its own
718 /// arms do not take, and builds the value at the end.
719 #[diagnostic::on_unimplemented(
720 message = "`{Self}` cannot be flattened",
721 note = "a flattened struct derives `Args` and has only flags: no positionals, \
722 subcommand, `sequence`, `unknown`, `keywords`, \
723 `unknown_flags = \"value\"` or generics"
724 )]
725 pub trait Flatten: Sized {
726 /// What has been parsed so far.
727 type Slots: Default;
728
729 /// Bind `arg` if it is one of these flags; `Ok(false)` if not.
730 fn bind<'i>(
731 slots: &mut Self::Slots,
732 arg: &Arg<'i>,
733 input: &mut Argv<'i>,
734 ) -> Result<bool, Error>;
735
736 /// Whether `-letter` is one of these flags, and whether it takes a value.
737 fn short(letter: char) -> Option<bool>;
738
739 /// Bind `arg` if it is one of these flags that is `global`: what a
740 /// subcommand of the struct that flattens them is offered.
741 fn bind_global<'i>(
742 slots: &mut Self::Slots,
743 arg: &Arg<'i>,
744 input: &mut Argv<'i>,
745 ) -> Result<bool, Error>;
746
747 /// Whether `-letter` is one of these flags that is `global`, and
748 /// whether it takes a value.
749 fn global_short(letter: char) -> Option<bool>;
750
751 /// Whether `name` is a long name that may take one dash (`long_only`).
752 fn is_long(name: &[u8]) -> bool;
753
754 /// Whether `-letter` always takes the rest of its word (`prefix`).
755 fn is_prefix(letter: u8) -> bool;
756
757 /// Apply environment variables, defaults and rules, and build the value.
758 fn finish(slots: Self::Slots, input: &Argv<'_>) -> Result<Self, Error>;
759 }
760
761 /// `help a b …`: the long help of the command the words name, below `root`.
762 pub fn help_word(root: &'static crate::help::Command, input: &mut Argv<'_>) -> Error {
763 let mut words = Vec::new();
764 while !input.is_empty() && !is_flag_like(input.front()) {
765 words.push(input.take_word());
766 }
767 let (command, path) = crate::help::resolve(root, words.iter().map(|w| &***w));
768 path.into_iter()
769 .rev()
770 .fold(Error::help(command, true), Error::within)
771 }
772
773 /// Whether every letter of the short bundle `token` (`-abc`) is `known`,
774 /// up to the first that takes a value: the rest is that value.
775 pub fn bundle_known(token: &[u8], known: impl Fn(char) -> Option<bool>) -> bool {
776 let Some(mut rest) = token.strip_prefix(b"-") else {
777 return false;
778 };
779 // Letters are ASCII in practice: decode only from the first byte that is not.
780 while let Some((&byte, tail)) = rest.split_first() {
781 if !byte.is_ascii() {
782 let Ok(letters) = core::str::from_utf8(rest) else {
783 return false;
784 };
785 return letters.chars().try_for_each(|letter| match known(letter) {
786 None => Err(false),
787 Some(true) => Err(true),
788 Some(false) => Ok(()),
789 }) != Err(false);
790 }
791 match known(byte as char) {
792 None => return false,
793 Some(true) => return true,
794 Some(false) => rest = tail,
795 }
796 }
797 true
798 }
799
800 /// A short bundle of two or more letters naming one no flag answers to,
801 /// taken whole as a word: `unknown_flags = "value"`. `None`, consuming
802 /// nothing, for anything else; a single unknown letter binds nothing before
803 /// it, so the derive's fallback arm handles it without this check.
804 #[inline]
805 pub fn unknown_bundle<'i>(
806 input: &mut Argv<'i>,
807 known: impl Fn(char) -> Option<bool>,
808 ) -> Option<Word<'i>> {
809 let front = input.front();
810 let short = input.mode() == crate::stream::Mode::Word
811 && front.len() > 2
812 && front[0] == b'-'
813 && front[1] != b'-';
814 if !short || bundle_known(front, known) {
815 return None;
816 }
817 let offset = input.offset();
818 Some(Word {
819 value: input.take_word(),
820 offset,
821 after_separator: false,
822 })
823 }
824
825 /// A `#[arg(keywords)]` field: each value `flag` took (`-z now`) parsed as
826 /// the `--now` flag of `T`, in order; an error is an invalid value of `flag`
827 /// naming the keyword.
828 pub fn keywords<T: crate::Args>(values: &[&BStr], flag: &str, at: usize) -> Result<T, Error> {
829 let spelled: Vec<Vec<u8>> = values
830 .iter()
831 .map(|v| [b"--".as_slice(), v].concat())
832 .collect();
833 let words: Vec<&BStr> = spelled.iter().map(|w| BStr::new(w.as_slice())).collect();
834 T::parse_words(&words).map_err(|e| {
835 let keyword = e.token().map_or_else(String::new, |t| {
836 t.strip_prefix("--").unwrap_or(t).to_owned()
837 });
838 Error::invalid_value(at, flag, keyword.as_bytes(), e)
839 })
840 }
841
842 /// The end of a unit subcommand: only inherited global flags may follow,
843 /// or a request for its `help`.
844 pub fn finish_with(
845 input: &mut Argv<'_>,
846 globals: &mut dyn Globals,
847 help: &'static crate::help::Command,
848 ) -> Result<(), Error> {
849 while !input.is_empty() {
850 let arg = arg(input)?;
851 match arg {
852 Arg::Separator { .. } => {}
853 Arg::Long(_) | Arg::Short(_) if globals.bind(&arg, input)? => {}
854 Arg::Long(flag) if flag.name == b"help" => return Err(Error::help(help, true)),
855 Arg::Short(flag) if flag.letter == 'h' => return Err(Error::help(help, false)),
856 _ => return Err(arg.unexpected()),
857 }
858 }
859 Ok(())
860 }
861}