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::EMPTY;
335
336 /// Answer a completion script's callback (`PROG __complete_word__ …`)
337 /// from this command's help data; `None` when `args` (the command line
338 /// after the program's name) is not one. See [`complete`].
339 fn completion_request(args: &[std::ffi::OsString]) -> Option<String> {
340 complete::answer(Self::help_data(), args)
341 }
342
343 /// The completion script for `shell`, calling back the program named in
344 /// the help data (`#[arg(name = "…")]`).
345 ///
346 /// # Panics
347 ///
348 /// If the command has no name, or one that is not a plain word.
349 fn completion_script(shell: complete::Shell) -> String {
350 complete::script(Self::HELP.name, shell)
351 }
352
353 /// Parse `words`, the arguments after the program name, already borrowed
354 /// as [`BStr`]s: what [`response::expand`] and [`words`] give. Nothing is
355 /// copied.
356 ///
357 /// An unknown flag or subcommand that is close to one of the program's
358 /// has it as [`Error::similar`].
359 fn parse_words(words: &[&BStr]) -> Result<Self, Error> {
360 Self::parse_argv(&mut Argv::new(words)).map_err(|error| error.suggested(Self::help_data()))
361 }
362
363 /// Parse `argv`, the whole command line, program name first. The name is
364 /// skipped.
365 fn parse_from_argv<I, S>(argv: I) -> Result<Self, Error>
366 where
367 I: IntoIterator<Item = S>,
368 S: AsRef<std::ffi::OsStr>,
369 {
370 Self::parse_from(argv.into_iter().skip(1))
371 }
372
373 /// Parse `args`, the arguments after the program name.
374 ///
375 /// ```
376 /// # #[cfg(feature = "derive")] {
377 /// use winnow_args::{Args, ErrorKind};
378 ///
379 /// #[derive(Args)]
380 /// struct Cli {
381 /// #[arg(short, long)]
382 /// verbose: bool,
383 /// }
384 ///
385 /// assert!(Cli::parse_from(["-v"]).unwrap().verbose);
386 /// assert!(Cli::parse_from_argv(["prog", "-v"]).unwrap().verbose);
387 /// let error = Cli::parse_from(["--loud"]).err().unwrap();
388 /// assert_eq!(error.kind(), ErrorKind::UnknownFlag);
389 /// # }
390 /// ```
391 fn parse_from<I, S>(args: I) -> Result<Self, Error>
392 where
393 I: IntoIterator<Item = S>,
394 S: AsRef<std::ffi::OsStr>,
395 {
396 let args: Vec<S> = args.into_iter().collect();
397 Self::parse_words(&words(&args))
398 }
399
400 /// Parse the process's arguments; on help, version or a failure, print
401 /// and exit as [`report`] does. It answers no completion callback: call
402 /// [`Args::completion_request`] first if the program has [`complete`] scripts.
403 fn parse() -> Self {
404 match Self::try_parse() {
405 Ok(parsed) => parsed,
406 Err(error) => std::process::exit(report(&error, &Self::program())),
407 }
408 }
409
410 /// Parse the process's arguments, leaving help, version and failures to
411 /// the caller: [`Args::parse`] without the printing and the exit.
412 ///
413 /// ```no_run
414 /// # #[cfg(feature = "derive")] {
415 /// use winnow_args::Args;
416 ///
417 /// #[derive(Args)]
418 /// struct Cli {
419 /// #[arg(short, long)]
420 /// verbose: bool,
421 /// }
422 ///
423 /// let cli = match Cli::try_parse() {
424 /// Ok(cli) => cli,
425 /// Err(error) => std::process::exit(winnow_args::report(&error, &Cli::program())),
426 /// };
427 /// # let _ = cli.verbose;
428 /// # }
429 /// ```
430 fn try_parse() -> Result<Self, Error> {
431 Self::parse_from_argv(std::env::args_os())
432 }
433
434 /// The program's name, as messages give it: `#[arg(name = "…")]`, else
435 /// the file name the process was run as.
436 fn program() -> String {
437 if !Self::HELP.name.is_empty() {
438 return Self::HELP.name.to_owned();
439 }
440 let argv0 = std::env::args_os().next().unwrap_or_default();
441 std::path::Path::new(&argv0)
442 .file_name()
443 .map(|name| name.to_string_lossy().into_owned())
444 .unwrap_or_default()
445 }
446}
447
448/// Print what a failed parse means, and give the exit status: help and version
449/// on stdout with 0, a bare `arg_required_else_help` invocation's help on stderr
450/// with 2, anything else as an error on stderr with 2. Colored with
451/// [`color::Theme::DEFAULT`] where the stream written to shows color; see
452/// [`report_with`] for another theme.
453pub fn report(error: &Error, program: &str) -> i32 {
454 report_with(error, program, &color::Theme::DEFAULT)
455}
456
457/// [`report`], painted with `theme`: its palette for the depth
458/// [`color::Depth::detect`] finds on the stream written to.
459///
460/// ```
461/// use winnow_args::color::{Paint, Palette, Theme};
462///
463/// // Bold, uncolored headers on 16-color terminals; the default elsewhere.
464/// const THEME: Theme = Theme {
465/// ansi16: Palette { header: Paint::NONE.bold(), ..Palette::DEFAULT },
466/// ..Theme::DEFAULT
467/// };
468/// # let _ = |e: &winnow_args::Error| winnow_args::report_with(e, "prog", &THEME);
469/// ```
470pub fn report_with(error: &Error, program: &str, theme: &color::Theme) -> i32 {
471 use std::io::IsTerminal as _;
472 let stdout = || help::Style::themed(theme, std::io::stdout().is_terminal());
473 let stderr = || help::Style::themed(theme, std::io::stderr().is_terminal());
474 // Help goes to stdout, except a bare invocation's, which is an error.
475 let bare = error.is_bare_help();
476 let style = if bare { stderr() } else { stdout() };
477 if let Some(help) = error.render_help_styled(program, style) {
478 if bare {
479 eprintln!("{help}");
480 return 2;
481 }
482 println!("{help}");
483 return 0;
484 }
485 if let Some(version) = error.version_text(program) {
486 println!("{version}");
487 return 0;
488 }
489 eprintln!("{}", error.render(stderr()));
490 2
491}
492
493/// Flags and words kept in command-line order: an enum deriving `Occurrence`,
494/// one variant per flag or positional, collected by an `#[arg(sequence)]`
495/// `Vec` field of an [`Args`] struct.
496///
497/// For command lines where position is meaning, as `ld`'s: `--as-needed` and
498/// `--whole-archive` apply to the inputs after them, so the linker folds the
499/// sequence rather than reading fields.
500pub trait Occurrence: Sized {
501 /// The name the derive files this type under when the documentation is
502 /// built. Empty for an implementation written by hand.
503 #[doc(hidden)]
504 const SPEC: &'static str = "";
505
506 /// Letters that always take the rest of their word (`-lfoo`), for a
507 /// `long_only` parent: no single-dash long name starting with one is tried.
508 const PREFIXES: &'static [u8] = &[];
509
510 /// `arg` as one of the variants, its value read from `input`; `None` when
511 /// no variant is spelled so.
512 fn from_arg<'i>(arg: &Arg<'i>, input: &mut Argv<'i>) -> Result<Option<Self>, Error>;
513
514 /// A word as the positional variant; `None` if there is none.
515 fn from_word(word: &token::Word<'_>) -> Result<Option<Self>, Error>;
516
517 /// Whether `name` is a variant's long name that may be spelled with one
518 /// dash, for a `long_only` parent.
519 fn is_long(name: &[u8]) -> bool;
520
521 /// The variants as help lists them, after the parent's own flags.
522 const ITEMS: &'static [help::Item] = &[];
523
524 /// Whether there is a positional variant: each plain word is that variant.
525 const POSITIONAL: bool = false;
526
527 /// Whether there is an `#[arg(bundle)]` variant.
528 const BUNDLES: bool = false;
529
530 /// A word of several short flags (`-sS`), whole, as the `#[arg(bundle)]`
531 /// variant: an item put before those of its letters, whoever takes them,
532 /// for a program that reports grouping (GNU ld deprecates it). `None` if
533 /// there is none.
534 fn from_bundle(word: &token::Word<'_>) -> Result<Option<Self>, Error> {
535 let _ = word;
536 Ok(None)
537 }
538
539 /// A flag no variant names, as the `#[arg(unknown)]` variant; `None` if
540 /// there is none. Asked by a parent whose field is
541 /// `#[arg(sequence, unknown)]`.
542 fn from_unknown(word: &token::Word<'_>) -> Result<Option<Self>, Error> {
543 let _ = word;
544 Ok(None)
545 }
546
547 /// Whether `letter` is a variant's short flag, and whether it takes a
548 /// value: how a parent with an `unknown` field tells an unknown bundle.
549 fn short(letter: char) -> Option<bool> {
550 let _ = letter;
551 None
552 }
553}
554
555/// An enum of subcommands, selected by a word.
556///
557/// Derived with `#[derive(Subcommand)]`; a struct holds one in an
558/// `#[arg(subcommand)]` field. The derive also implements [`Args`] for the enum,
559/// so it can be the whole command line.
560pub trait Subcommand: Sized {
561 /// The name the derive files this type under when the documentation is
562 /// built. Empty for an implementation written by hand.
563 #[doc(hidden)]
564 const SPEC: &'static str = "";
565
566 /// Whether `name` names a subcommand. Asked of every eligible word, so kept
567 /// apart from [`Subcommand::parse_subcommand`] and cheap to inline.
568 fn has(name: &[u8]) -> bool;
569
570 /// Parse the rest of `input` as the subcommand `name`, which [`Subcommand::has`];
571 /// `globals` binds its ancestors' global flags.
572 fn parse_subcommand(
573 name: &[u8],
574 input: &mut Argv<'_>,
575 globals: &mut dyn Globals,
576 ) -> Result<Self, Error>;
577}
578
579/// The global flags of a subcommand's ancestors, which it accepts as its own.
580///
581/// A parent hands one down to its subcommand; the subcommand offers it every
582/// flag it does not declare, so its own declarations take precedence.
583pub trait Globals {
584 /// Bind `arg`, read from `input`, if it is a global flag; `Ok(false)` if not.
585 fn bind<'i>(&mut self, arg: &Arg<'i>, input: &mut Argv<'i>) -> Result<bool, Error>;
586
587 /// Whether `-letter` is one of these flags, and if so whether it takes a
588 /// value. A command with `unknown_flags = "value"` asks about every letter
589 /// of a bundle before binding any.
590 fn short(&self, letter: char) -> Option<bool> {
591 let _ = letter;
592 None
593 }
594}
595
596/// No global flags: what a command line's root is given.
597impl Globals for () {
598 #[inline]
599 fn bind<'i>(&mut self, _: &Arg<'i>, _: &mut Argv<'i>) -> Result<bool, Error> {
600 Ok(false)
601 }
602}
603
604/// [`Globals`] from a closure. It does not answer [`Globals::short`]: the derive
605/// calls `inherit`, which forwards the parent's letters, so a lenient
606/// subcommand still sees them.
607pub fn globals<F>(bind: F) -> impl Globals
608where
609 F: for<'i> FnMut(&Arg<'i>, &mut Argv<'i>) -> Result<bool, Error>,
610{
611 struct FromFn<F>(F);
612 impl<F> Globals for FromFn<F>
613 where
614 F: for<'i> FnMut(&Arg<'i>, &mut Argv<'i>) -> Result<bool, Error>,
615 {
616 #[inline]
617 fn bind<'i>(&mut self, arg: &Arg<'i>, input: &mut Argv<'i>) -> Result<bool, Error> {
618 (self.0)(arg, input)
619 }
620 }
621 FromFn(bind)
622}
623
624/// [`Globals`] that are `shorts` (letter, takes a value), those `flattened`
625/// answers for, and `bind`, then `parent`'s: what the derive hands a
626/// subcommand of a struct with global flags, its own or of a struct it
627/// flattens. Unlike [`globals`], `short` sees those letters.
628#[doc(hidden)]
629pub fn inherit<'a, F>(
630 shorts: &'static [(char, bool)],
631 flattened: fn(char) -> Option<bool>,
632 parent: &'a mut dyn Globals,
633 bind: F,
634) -> impl Globals + 'a
635where
636 F: for<'i> FnMut(&Arg<'i>, &mut Argv<'i>, &mut dyn Globals) -> Result<bool, Error> + 'a,
637{
638 struct Inherit<'a, F> {
639 shorts: &'static [(char, bool)],
640 flattened: fn(char) -> Option<bool>,
641 parent: &'a mut dyn Globals,
642 bind: F,
643 }
644 impl<F> Globals for Inherit<'_, F>
645 where
646 F: for<'i> FnMut(&Arg<'i>, &mut Argv<'i>, &mut dyn Globals) -> Result<bool, Error>,
647 {
648 #[inline]
649 fn bind<'i>(&mut self, arg: &Arg<'i>, input: &mut Argv<'i>) -> Result<bool, Error> {
650 (self.bind)(arg, input, &mut *self.parent)
651 }
652
653 fn short(&self, letter: char) -> Option<bool> {
654 match self.shorts.iter().find(|(c, _)| *c == letter) {
655 Some(&(_, takes_value)) => Some(takes_value),
656 None => (self.flattened)(letter).or_else(|| self.parent.short(letter)),
657 }
658 }
659 }
660 Inherit {
661 shorts,
662 flattened,
663 parent,
664 bind,
665 }
666}
667
668/// Help prose the derive emits: kept with the `help-text` feature.
669#[cfg(feature = "help-text")]
670#[doc(hidden)]
671#[macro_export]
672macro_rules! __text {
673 ($text:literal) => {
674 $text
675 };
676}
677
678/// Help prose the derive emits: `""` without the `help-text` feature.
679#[cfg(not(feature = "help-text"))]
680#[doc(hidden)]
681#[macro_export]
682macro_rules! __text {
683 ($text:literal) => {
684 ""
685 };
686}
687
688#[doc(hidden)]
689pub mod __private {
690 pub use crate::env;
691 pub use crate::error::Error;
692 pub use crate::help::{concat_headings, concat_items};
693 pub use crate::stream::Argv;
694 pub use crate::token::{Arg, ValueOptions, Word, arg, arg_plus, long_only, number, split};
695 pub use crate::value::{ChoiceError, FromArg, documented_choices, filed_as, stated_choices};
696 pub use crate::{Globals, Subcommand, globals, inherit};
697 pub use winnow::stream::BStr;
698 pub type BoxError = crate::error::BoxError;
699
700 use crate::token::is_flag_like;
701
702 /// The flags of a struct that another flattens (`#[arg(flatten)]`), derived
703 /// for every `Args` struct that has flags only.
704 ///
705 /// The parent keeps a [`Flatten::Slots`], offers it each flag its own
706 /// arms do not take, and builds the value at the end.
707 #[diagnostic::on_unimplemented(
708 message = "`{Self}` cannot be flattened",
709 note = "a flattened struct derives `Args` and has only flags: no positionals, \
710 subcommand, `sequence`, `unknown`, `keywords`, \
711 `unknown_flags = \"value\"` or generics"
712 )]
713 pub trait Flatten: Sized {
714 /// What has been parsed so far.
715 type Slots: Default;
716
717 /// Bind `arg` if it is one of these flags; `Ok(false)` if not.
718 fn bind<'i>(
719 slots: &mut Self::Slots,
720 arg: &Arg<'i>,
721 input: &mut Argv<'i>,
722 ) -> Result<bool, Error>;
723
724 /// Whether `-letter` is one of these flags, and whether it takes a value.
725 fn short(letter: char) -> Option<bool>;
726
727 /// Bind `arg` if it is one of these flags that is `global`: what a
728 /// subcommand of the struct that flattens them is offered.
729 fn bind_global<'i>(
730 slots: &mut Self::Slots,
731 arg: &Arg<'i>,
732 input: &mut Argv<'i>,
733 ) -> Result<bool, Error>;
734
735 /// Whether `-letter` is one of these flags that is `global`, and
736 /// whether it takes a value.
737 fn global_short(letter: char) -> Option<bool>;
738
739 /// Whether `name` is a long name that may take one dash (`long_only`).
740 fn is_long(name: &[u8]) -> bool;
741
742 /// Whether `-letter` always takes the rest of its word (`prefix`).
743 fn is_prefix(letter: u8) -> bool;
744
745 /// Apply environment variables, defaults and rules, and build the value.
746 fn finish(slots: Self::Slots, input: &Argv<'_>) -> Result<Self, Error>;
747 }
748
749 /// `help a b …`: the long help of the command the words name, below `root`.
750 pub fn help_word(root: &'static crate::help::Command, input: &mut Argv<'_>) -> Error {
751 let mut words = Vec::new();
752 while !input.is_empty() && !is_flag_like(input.front()) {
753 words.push(input.take_word());
754 }
755 let (command, path) = crate::help::resolve(root, words.iter().map(|w| &***w));
756 path.into_iter()
757 .rev()
758 .fold(Error::help(command, true), Error::within)
759 }
760
761 /// Whether every letter of the short bundle `token` (`-abc`) is `known`,
762 /// up to the first that takes a value: the rest is that value.
763 pub fn bundle_known(token: &[u8], known: impl Fn(char) -> Option<bool>) -> bool {
764 let Some(mut rest) = token.strip_prefix(b"-") else {
765 return false;
766 };
767 // Letters are ASCII in practice: decode only from the first byte that is not.
768 while let Some((&byte, tail)) = rest.split_first() {
769 if !byte.is_ascii() {
770 let Ok(letters) = core::str::from_utf8(rest) else {
771 return false;
772 };
773 return letters.chars().try_for_each(|letter| match known(letter) {
774 None => Err(false),
775 Some(true) => Err(true),
776 Some(false) => Ok(()),
777 }) != Err(false);
778 }
779 match known(byte as char) {
780 None => return false,
781 Some(true) => return true,
782 Some(false) => rest = tail,
783 }
784 }
785 true
786 }
787
788 /// A short bundle of two or more letters naming one no flag answers to,
789 /// taken whole as a word: `unknown_flags = "value"`. `None`, consuming
790 /// nothing, for anything else; a single unknown letter binds nothing before
791 /// it, so the derive's fallback arm handles it without this check.
792 #[inline]
793 pub fn unknown_bundle<'i>(
794 input: &mut Argv<'i>,
795 known: impl Fn(char) -> Option<bool>,
796 ) -> Option<Word<'i>> {
797 let front = input.front();
798 let short = input.mode() == crate::stream::Mode::Word
799 && front.len() > 2
800 && front[0] == b'-'
801 && front[1] != b'-';
802 if !short || bundle_known(front, known) {
803 return None;
804 }
805 let offset = input.offset();
806 Some(Word {
807 value: input.take_word(),
808 offset,
809 after_separator: false,
810 })
811 }
812
813 /// A `#[arg(keywords)]` field: each value `flag` took (`-z now`) parsed as
814 /// the `--now` flag of `T`, in order; an error is an invalid value of `flag`
815 /// naming the keyword.
816 pub fn keywords<T: crate::Args>(values: &[&BStr], flag: &str, at: usize) -> Result<T, Error> {
817 let spelled: Vec<Vec<u8>> = values
818 .iter()
819 .map(|v| [b"--".as_slice(), v].concat())
820 .collect();
821 let words: Vec<&BStr> = spelled.iter().map(|w| BStr::new(w.as_slice())).collect();
822 T::parse_words(&words).map_err(|e| {
823 let keyword = e.token().map_or_else(String::new, |t| {
824 t.strip_prefix("--").unwrap_or(t).to_owned()
825 });
826 Error::invalid_value(at, flag, keyword.as_bytes(), e)
827 })
828 }
829
830 /// The end of a unit subcommand: only inherited global flags may follow,
831 /// or a request for its `help`.
832 pub fn finish_with(
833 input: &mut Argv<'_>,
834 globals: &mut dyn Globals,
835 help: &'static crate::help::Command,
836 ) -> Result<(), Error> {
837 while !input.is_empty() {
838 let arg = arg(input)?;
839 match arg {
840 Arg::Separator { .. } => {}
841 Arg::Long(_) | Arg::Short(_) if globals.bind(&arg, input)? => {}
842 Arg::Long(flag) if flag.name == b"help" => return Err(Error::help(help, true)),
843 Arg::Short(flag) if flag.letter == 'h' => return Err(Error::help(help, false)),
844 _ => return Err(arg.unexpected()),
845 }
846 }
847 Ok(())
848 }
849}