Skip to main content

bpaf/
info.rs

1//! Help message generation and rendering
2
3use crate::{
4    args::{Args, State},
5    error::Message,
6    meta_help::render_help,
7    parsers::NamedArg,
8    short, Doc, Error, Meta, ParseFailure, Parser,
9};
10
11/// Information about the parser
12///
13/// No longer public, users are only interacting with it via [`OptionParser`]
14#[derive(Debug, Clone)]
15#[doc(hidden)]
16pub struct Info {
17    /// version field, see [`version`][Info::version]
18    pub version: Option<Doc>,
19    /// Custom description field, see [`descr`][Info::descr]
20    pub descr: Option<Doc>,
21    /// Custom header field, see [`header`][Info::header]
22    pub header: Option<Doc>,
23    /// Custom footer field, see [`footer`][Info::footer]
24    pub footer: Option<Doc>,
25    /// Custom usage field, see [`usage`][Info::usage]
26    pub usage: Option<Doc>,
27    pub help_arg: NamedArg,
28    pub version_arg: NamedArg,
29    pub help_if_no_args: bool,
30    pub max_width: usize,
31}
32
33impl Default for Info {
34    fn default() -> Self {
35        Self {
36            version: None,
37            descr: None,
38            header: None,
39            footer: None,
40            usage: None,
41            help_arg: short('h').long("help").help("Prints help information"),
42            version_arg: short('V')
43                .long("version")
44                .help("Prints version information"),
45            help_if_no_args: false,
46            max_width: 100,
47        }
48    }
49}
50
51/// Ready to run [`Parser`] with additional information attached
52///
53/// Created with [`to_options`](Parser::to_options)
54///
55/// In addition to the inner parser `OptionParser` contains documentation about a program or a
56/// subcommand as a whole, version, custom usage, if specified, and handles custom parsers for
57/// `--version` and `--help` flags.
58pub struct OptionParser<T> {
59    pub(crate) inner: Box<dyn Parser<T>>,
60    pub(crate) info: Info,
61}
62
63impl<T> OptionParser<T> {
64    /// Execute the [`OptionParser`], extract a parsed value or print some diagnostic and exit
65    ///
66    /// # Usage
67    /// ```no_run
68    /// # use bpaf::*;
69    /// /// Parses number of repetitions of `-v` on a command line
70    /// fn verbosity() -> OptionParser<usize> {
71    ///     let parser = short('v')
72    ///         .req_flag(())
73    ///         .many()
74    ///         .map(|xs|xs.len());
75    ///
76    ///     parser
77    ///         .to_options()
78    ///         .descr("Takes verbosity flag and does nothing else")
79    /// }
80    ///
81    /// fn main() {
82    ///     let verbosity: usize = verbosity().run();
83    /// }
84    /// ```
85    #[must_use]
86    pub fn run(self) -> T
87    where
88        Self: Sized,
89    {
90        match self.run_inner(Args::current_args()) {
91            Ok(t) => t,
92            Err(err) => {
93                err.print_message(self.info.max_width);
94                std::process::exit(err.exit_code())
95            }
96        }
97    }
98
99    /// Execute the [`OptionParser`], extract a parsed value or return a [`ParseFailure`]
100    ///
101    /// In most cases using [`run`](OptionParser::run) is sufficient, you can use `try_run` if you
102    /// want to control the exit code or you need to perform a custom cleanup.
103    ///
104    /// # Usage
105    /// ```no_run
106    /// # use bpaf::*;
107    /// /// Parses number of repetitions of `-v` on a command line
108    /// fn verbosity() -> OptionParser<usize> {
109    ///     let parser = short('v')
110    ///         .req_flag(())
111    ///         .many()
112    ///         .map(|xs|xs.len());
113    ///
114    ///     parser
115    ///         .to_options()
116    ///         .descr("Takes verbosity flag and does nothing else")
117    /// }
118    ///
119    /// fn main() {
120    ///     let verbosity: Option<usize> = match verbosity().try_run() {
121    ///         Ok(v) => Some(v),
122    ///         Err(ParseFailure::Stdout(buf, full)) => {
123    ///             print!("{}", buf.monochrome(full));
124    ///             None
125    ///         }
126    ///         Err(ParseFailure::Completion(msg)) => {
127    ///             print!("{}", msg);
128    ///             None
129    ///         }
130    ///         Err(ParseFailure::Stderr(buf)) => {
131    ///             eprintln!("{}", buf.monochrome(true));
132    ///             None
133    ///         }
134    ///     };
135    ///
136    ///     // Run cleanup tasks
137    /// }
138    /// ```
139    ///
140    /// # Errors
141    ///
142    /// [`ParseFailure`] represents parsing errors, autocomplete results and generated `--help`
143    /// output.
144    #[deprecated = "You should switch to equivalent parser.run_inner(Args::current_args())"]
145    pub fn try_run(self) -> Result<T, ParseFailure>
146    where
147        Self: Sized,
148    {
149        self.run_inner(Args::current_args())
150    }
151
152    /// Execute the [`OptionParser`] and produce a values for unit tests or manual processing
153    ///
154    /// ```rust
155    /// # use bpaf::*;
156    /// # /*
157    /// #[test]
158    /// fn positional_argument() {
159    /// # */
160    ///     let parser =
161    ///         positional::<String>("FILE")
162    ///             .help("File to process")
163    ///             .to_options();
164    ///
165    ///     let help = parser
166    ///         .run_inner(&["--help"])
167    ///         .unwrap_err()
168    ///         .unwrap_stdout();
169    ///     let expected_help = "\
170    /// Usage: FILE
171    ///
172    /// Available positional items:
173    ///     FILE        File to process
174    ///
175    /// Available options:
176    ///     -h, --help  Prints help information
177    /// ";
178    ///     assert_eq!(expected_help, help);
179    /// # /*
180    /// }
181    /// # */
182    /// ```
183    ///
184    /// See also [`Args`] and it's `From` impls to produce input and
185    /// [`ParseFailure::unwrap_stderr`] / [`ParseFailure::unwrap_stdout`] for processing results.
186    ///
187    /// # Errors
188    ///
189    /// If parser can't produce desired result `run_inner` returns [`ParseFailure`]
190    /// which represents runtime behavior: one branch to print something to stdout and exit with
191    /// success and the other branch to print something to stderr and exit with failure.
192    ///
193    /// `bpaf` generates contents of this `ParseFailure` using expected textual output from
194    /// [`parse`](Parser::parse), stdout/stderr isn't actually captured.
195    ///
196    /// Exact string reperentations may change between versions including minor releases.
197    pub fn run_inner<'a>(&self, args: impl Into<Args<'a>>) -> Result<T, ParseFailure>
198    where
199        Self: Sized,
200    {
201        // prepare available short flags and arguments for disambiguation
202        let mut short_flags = Vec::new();
203        let mut short_args = Vec::new();
204        self.inner
205            .meta()
206            .collect_shorts(&mut short_flags, &mut short_args);
207        short_flags.extend(&self.info.help_arg.short);
208        short_flags.extend(&self.info.version_arg.short);
209        let args = args.into();
210        let mut err = None;
211        let mut state = State::construct(args, &short_flags, &short_args, &mut err);
212
213        // this only handles disambiguation failure in construct
214        if let Some(msg) = err {
215            #[cfg(feature = "autocomplete")]
216            let check_disambiguation = state.comp_ref().is_none();
217
218            #[cfg(not(feature = "autocomplete"))]
219            let check_disambiguation = false;
220
221            if check_disambiguation {
222                return Err(msg.render(&state, &self.inner.meta()));
223            }
224        }
225
226        self.run_subparser(&mut state)
227    }
228
229    /// Run subparser, implementation detail
230    pub(crate) fn run_subparser(&self, args: &mut State) -> Result<T, ParseFailure> {
231        // process should work like this:
232        // - inner parser is evaluated, it returns Error
233        // - if error is finalized (ParseFailure) - it is simply propagated outwards,
234        //   otherwise we are making a few attempts at improving it after dealing with
235        //   autocomplete/help
236        //
237        // - generate autocomplete, if enabled
238        // - produce --help, --version
239        // - Try to improve error message and finalize it otherwise
240        //
241        // outer parser gets value in ParseFailure format
242
243        let no_args = args.is_empty();
244        let res = self.inner.eval(args);
245
246        // Don't override inner parser printing usage info
247        let parser_failed = match res {
248            Ok(_) | Err(Error(Message::ParseFailure(ParseFailure::Stdout(..)))) => false,
249            Err(_) => true,
250        };
251
252        if parser_failed && self.info.help_if_no_args && no_args {
253            let buffer = render_help(
254                &args.path,
255                &self.info,
256                &self.inner.meta(),
257                &self.info.meta(),
258            );
259            return Err(ParseFailure::Stdout(buffer, false));
260        };
261
262        if let Err(Error(Message::ParseFailure(failure))) = res {
263            return Err(failure);
264        }
265        #[cfg(feature = "autocomplete")]
266        if let Some(comp) = args.check_complete() {
267            return Err(ParseFailure::Completion(comp));
268        }
269
270        let err = match res {
271            Ok(ok) => {
272                if let Some((ix, _)) = args.items_iter().next() {
273                    Message::Unconsumed(ix)
274                } else {
275                    return Ok(ok);
276                }
277            }
278            Err(Error(err)) => err,
279        };
280
281        // handle --help and --version messages
282        if let Ok(extra) = self.info.eval(args) {
283            let mut detailed = false;
284            let buffer = match extra {
285                ExtraParams::Help(d) => {
286                    detailed = d;
287                    render_help(
288                        &args.path,
289                        &self.info,
290                        &self.inner.meta(),
291                        &self.info.meta(),
292                    )
293                }
294                ExtraParams::Version(v) => {
295                    use crate::buffer::{Block, Token};
296                    let mut buffer = Doc::default();
297                    buffer.token(Token::BlockStart(Block::Block));
298                    buffer.text("Version: ");
299                    buffer.doc(&v);
300                    buffer.token(Token::BlockEnd(Block::Block));
301                    buffer
302                }
303            };
304            return Err(ParseFailure::Stdout(buffer, detailed));
305        }
306        Err(err.render(args, &self.inner.meta()))
307    }
308
309    /// Get first line of description if Available
310    ///
311    /// Used internally to avoid duplicating description for [`command`].
312    #[must_use]
313    pub(crate) fn short_descr(&self) -> Option<Doc> {
314        self.info.descr.as_ref().and_then(Doc::first_line)
315    }
316
317    /// Set the version field.
318    ///
319    /// By default `bpaf` won't include any version info and won't accept `--version` switch.
320    ///
321    /// # Combinatoric usage
322    ///
323    /// ```rust
324    /// use bpaf::*;
325    /// fn options() -> OptionParser<bool>  {
326    ///    short('s')
327    ///        .switch()
328    ///        .to_options()
329    ///        .version(env!("CARGO_PKG_VERSION"))
330    /// }
331    /// ```
332    ///
333    /// # Derive usage
334    ///
335    /// `version` annotation is available after `options` and `command` annotations, takes
336    /// an optional argument - version value to use, otherwise `bpaf_derive` would use value from cargo.
337    ///
338    /// ```rust
339    /// # use bpaf::*;
340    /// #[derive(Debug, Clone, Bpaf)]
341    /// #[bpaf(options, version)]
342    /// struct Options {
343    ///     #[bpaf(short)]
344    ///     switch: bool
345    /// }
346    /// ```
347    ///
348    /// # Example
349    /// ```console
350    /// $ app --version
351    /// Version: 0.5.0
352    /// ```
353    #[must_use]
354    pub fn version<B: Into<Doc>>(mut self, version: B) -> Self {
355        self.info.version = Some(version.into());
356        self
357    }
358    /// Set the description field
359    ///
360    /// Description field should be 1-2 lines long briefly explaining program purpose. If
361    /// description field is present `bpaf` would print it right before the usage line.
362    ///
363    /// # Combinatoric usage
364    /// ```rust
365    /// # use bpaf::*;
366    /// fn options() -> OptionParser<bool>  {
367    ///    short('s')
368    ///        .switch()
369    ///        .to_options()
370    ///        .descr("This is a description")
371    ///        .header("This is a header")
372    ///        .footer("This is a footer")
373    /// }
374    /// ```
375    ///
376    /// # Derive usage
377    ///
378    /// `bpaf_derive` uses doc comments on the `struct` / `enum` to derive description, it skips single empty
379    /// lines and uses double empty lines break it into blocks. `bpaf_derive` would use first block as the
380    /// description, second block - header, third block - footer.
381    ///
382    /// ```rust
383    /// # use bpaf::*;
384    /// #[derive(Debug, Clone, Bpaf)]
385    /// #[bpaf(options, version)]
386    /// /// This is a description
387    /// ///
388    /// ///
389    /// /// This is a header
390    /// ///
391    /// ///
392    /// /// This is a footer
393    /// ///
394    /// ///
395    /// /// This is just a comment
396    /// struct Options {
397    ///     #[bpaf(short)]
398    ///     switch: bool
399    /// }
400    /// ```
401    ///
402    /// # Example
403    ///
404    /// ```console
405    /// This is a description
406    ///
407    /// Usage: [-s]
408    ///
409    /// This is a header
410    ///
411    /// Available options:
412    ///     -s
413    ///     -h, --help     Prints help information
414    ///     -V, --version  Prints version information
415    ///
416    /// This is a footer
417    /// ```
418    #[must_use]
419    pub fn descr<B: Into<Doc>>(mut self, descr: B) -> Self {
420        self.info.descr = Some(descr.into());
421        self
422    }
423
424    /// Set the header field
425    ///
426    /// `bpaf` displays the header between the usage line and a list of the available options in `--help` output
427    ///
428    /// # Combinatoric usage
429    /// ```rust
430    /// # use bpaf::*;
431    /// fn options() -> OptionParser<bool>  {
432    ///    short('s')
433    ///        .switch()
434    ///        .to_options()
435    ///        .descr("This is a description")
436    ///        .header("This is a header")
437    ///        .footer("This is a footer")
438    /// }
439    /// ```
440    ///
441    /// # Derive usage
442    ///
443    /// `bpaf_derive` uses doc comments on the `struct` / `enum` to derive description, it skips single empty
444    /// lines and uses double empty lines break it into blocks. `bpaf_derive` would use first block as the
445    /// description, second block - header, third block - footer.
446    ///
447    /// ```rust
448    /// # use bpaf::*;
449    /// #[derive(Debug, Clone, Bpaf)]
450    /// #[bpaf(options, version)]
451    /// /// This is a description
452    /// ///
453    /// ///
454    /// /// This is a header
455    /// ///
456    /// ///
457    /// /// This is a footer
458    /// ///
459    /// ///
460    /// /// This is just a comment
461    /// struct Options {
462    ///     #[bpaf(short)]
463    ///     switch: bool
464    /// }
465    /// ```
466    ///
467    /// # Example
468    ///
469    /// ```console
470    /// This is a description
471    ///
472    /// Usage: [-s]
473    ///
474    /// This is a header
475    ///
476    /// Available options:
477    ///     -s
478    ///     -h, --help     Prints help information
479    ///     -V, --version  Prints version information
480    ///
481    /// This is a footer
482    /// ```
483    #[must_use]
484    pub fn header<B: Into<Doc>>(mut self, header: B) -> Self {
485        self.info.header = Some(header.into());
486        self
487    }
488
489    /// Set the footer field
490    ///
491    /// `bpaf` displays the footer after list of the available options in `--help` output
492    ///
493    /// # Combinatoric usage
494    /// ```rust
495    /// # use bpaf::*;
496    /// fn options() -> OptionParser<bool>  {
497    ///    short('s')
498    ///        .switch()
499    ///        .to_options()
500    ///        .descr("This is a description")
501    ///        .header("This is a header")
502    ///        .footer("This is a footer")
503    /// }
504    /// ```
505    ///
506    /// # Derive usage
507    ///
508    /// `bpaf_derive` uses doc comments on the `struct` / `enum` to derive description, it skips single empty
509    /// lines and uses double empty lines break it into blocks. `bpaf_derive` would use first block as the
510    /// description, second block - header, third block - footer.
511    ///
512    /// ```rust
513    /// # use bpaf::*;
514    /// #[derive(Debug, Clone, Bpaf)]
515    /// #[bpaf(options, version)]
516    /// /// This is a description
517    /// ///
518    /// ///
519    /// /// This is a header
520    /// ///
521    /// ///
522    /// /// This is a footer
523    /// ///
524    /// ///
525    /// /// This is just a comment
526    /// struct Options {
527    ///     #[bpaf(short)]
528    ///     switch: bool
529    /// }
530    /// ```
531    ///
532    /// # Example
533    ///
534    /// ```console
535    /// This is a description
536    ///
537    /// Usage: [-s]
538    ///
539    /// This is a header
540    ///
541    /// Available options:
542    ///     -s
543    ///     -h, --help     Prints help information
544    ///     -V, --version  Prints version information
545    ///
546    /// This is a footer
547    /// ```
548    #[must_use]
549    pub fn footer<M: Into<Doc>>(mut self, footer: M) -> Self {
550        self.info.footer = Some(footer.into());
551        self
552    }
553
554    /// Set custom usage field
555    ///
556    /// Custom usage field to use instead of one derived by `bpaf`.
557    #[cfg_attr(not(doctest), doc = include_str!("docs2/usage.md"))]
558    #[must_use]
559    pub fn usage<B>(mut self, usage: B) -> Self
560    where
561        B: Into<Doc>,
562    {
563        self.info.usage = Some(usage.into());
564        self
565    }
566
567    /// Generate new usage line using automatically derived usage
568    ///
569    /// You can customize the surroundings of the usage line while still
570    /// having part that frequently changes generated by bpaf
571    ///
572    #[cfg_attr(not(doctest), doc = include_str!("docs2/with_usage.md"))]
573    ///
574    /// At the moment this method is not directly supported by derive API,
575    /// but since it gives you an object of [`OptionParser<T>`](OptionParser)
576    /// type you can alter it using Combinatoric API:
577    /// ```text
578    /// #[derive(Debug, Clone, Bpaf)] {
579    /// pub struct Options {
580    ///     ...
581    /// }
582    ///
583    /// fn my_decor(usage: Doc) -> Doc {
584    ///     ...
585    /// }
586    ///
587    /// fn main() {
588    ///     let options = options().with_usage(my_decor).run();
589    ///     ...
590    /// }
591    /// ```
592    #[must_use]
593    pub fn with_usage<F>(mut self, f: F) -> Self
594    where
595        F: Fn(Doc) -> Doc,
596    {
597        let mut buf = Doc::default();
598        buf.write_meta(&self.inner.meta(), true);
599        self.info.usage = Some(f(buf));
600        self
601    }
602
603    /// Check the invariants `bpaf` relies on for normal operations
604    ///
605    /// Takes a parameter whether to check for cosmetic invariants or not
606    /// (max help width exceeding 120 symbols, etc), currently not in use
607    ///
608    /// Best used as part of your test suite:
609    /// ```no_run
610    /// # use bpaf::*;
611    /// #[test]
612    /// fn check_options() {
613    /// # let options = || short('p').switch().to_options();
614    ///     options().check_invariants(false)
615    /// }
616    /// ```
617    ///
618    /// # Panics
619    ///
620    /// `check_invariants` indicates problems with panic
621    pub fn check_invariants(&self, _cosmetic: bool) {
622        self.inner.meta().positional_invariant_check(true);
623    }
624
625    /// Customize parser for `--help`
626    ///
627    /// By default `bpaf` displays help when program is called with either `--help` or `-h`, you
628    /// can customize those names and description in the help message
629    ///
630    /// Note, `--help` is something user expects to work
631    #[cfg_attr(not(doctest), doc = include_str!("docs2/custom_help_version.md"))]
632    #[must_use]
633    pub fn help_parser(mut self, parser: NamedArg) -> Self {
634        self.info.help_arg = parser;
635        self
636    }
637
638    /// Customize parser for `--version`
639    ///
640    /// By default `bpaf` displays version information when program is called with either `--version`
641    /// or `-V` (and version is available), you can customize those names and description in the help message
642    ///
643    /// Note, `--version` is something user expects to work
644    #[cfg_attr(not(doctest), doc = include_str!("docs2/custom_help_version.md"))]
645    #[must_use]
646    pub fn version_parser(mut self, parser: NamedArg) -> Self {
647        self.info.version_arg = parser;
648        self
649    }
650
651    /// Print help if app was called with no parameters
652    ///
653    /// By default `bpaf` tries to parse command line options and displays the best possible
654    /// error it can come up with. If application requires a subcommand or some argument
655    /// and user specified none - it might be a better experience for user to print
656    /// the help message.
657    ///
658    /// ```rust
659    /// # use bpaf::*;
660    /// # fn options() -> OptionParser<bool> { short('a').switch().to_options() }
661    /// // create option parser in a usual way, derive or combinatoric API
662    /// let opts = options().fallback_to_usage().run();
663    /// ```
664    ///
665    /// For derive macro you can specify `fallback_to_usage` in top level annotations
666    /// for options and for individual commands if fallback to useage is the desired behavior:
667    ///
668    ///
669    /// ```ignore
670    /// #[derive(Debug, Clone, Bpaf)]
671    /// enum Commands {
672    ///     #[bpaf(command, fallback_to_usage)]
673    ///     Action {
674    ///         ...
675    ///     }
676    /// }
677    /// ```
678    ///
679    /// Or
680    ///
681    /// ```ignore
682    /// #[derive(Debug, Clone, Bpaf)]
683    /// #[bpaf(options, fallback_to_usage)]
684    /// struct Options {
685    ///     ...
686    /// }
687    ///
688    /// fn main() {
689    ///     let options = options().run(); // falls back to usage
690    /// }
691    /// ```
692    #[must_use]
693    pub fn fallback_to_usage(mut self) -> Self {
694        self.info.help_if_no_args = true;
695        self
696    }
697
698    /// Set the width of the help message printed to the terminal upon failure
699    ///
700    /// By default, the help message is printed with a width of 100 characters.
701    /// This method allows to change where the help message is wrapped.
702    ///
703    /// Setting the max width too low may negatively affect the readability of the help message.
704    /// Also, the alignment padding of broken lines is always applied.
705    #[must_use]
706    pub fn max_width(mut self, width: usize) -> Self {
707        self.info.max_width = width;
708        self
709    }
710}
711
712impl Info {
713    #[inline(never)]
714    fn mk_help_parser(&self) -> impl Parser<()> {
715        self.help_arg.clone().req_flag(())
716    }
717    #[inline(never)]
718    fn mk_version_parser(&self) -> impl Parser<()> {
719        self.version_arg.clone().req_flag(())
720    }
721}
722
723impl Parser<ExtraParams> for Info {
724    fn eval(&self, args: &mut State) -> Result<ExtraParams, Error> {
725        let help = self.mk_help_parser();
726        if help.eval(args).is_ok() {
727            return Ok(ExtraParams::Help(help.eval(args).is_ok()));
728        }
729
730        if let Some(version) = &self.version {
731            if self.mk_version_parser().eval(args).is_ok() {
732                return Ok(ExtraParams::Version(version.clone()));
733            }
734        }
735
736        // error message is not actually used anywhere
737        Err(Error(Message::ParseFail("not a version or help")))
738    }
739
740    fn meta(&self) -> Meta {
741        let help = self.mk_help_parser().meta();
742        match &self.version {
743            Some(_) => Meta::And(vec![help, self.mk_version_parser().meta()]),
744            None => help,
745        }
746    }
747}
748
749#[derive(Clone, Debug)]
750pub(crate) enum ExtraParams {
751    Help(bool),
752    Version(Doc),
753}