diff --git a/Cargo.lock b/Cargo.lock index cd6de7e8..64a7c230 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -260,6 +260,15 @@ dependencies = [ "clap_derive", ] +[[package]] +name = "clap-markdown" +version = "0.1.3-ghciwatch" +dependencies = [ + "clap", + "expect-test", + "textwrap 0.16.1", +] + [[package]] name = "clap_builder" version = "4.4.18" diff --git a/Cargo.toml b/Cargo.toml index 0c83c172..e6aa030f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,5 +1,6 @@ [workspace] members = [ + "clap-markdown", "test-harness", "test-harness-macro", ] diff --git a/clap-markdown/Cargo.toml b/clap-markdown/Cargo.toml new file mode 100644 index 00000000..eb3762b0 --- /dev/null +++ b/clap-markdown/Cargo.toml @@ -0,0 +1,21 @@ +[package] +name = "clap-markdown" +version = "0.1.3-ghciwatch" +authors = ["Connor Gray "] +edition = "2021" +license = "MIT OR Apache-2.0" +readme = "README.md" +repository = "https://github.com/ConnorGray/clap-markdown" +description = "Autogenerate Markdown documentation for clap command-line tools" +keywords = ["clap", "markdown", "command-line", "help"] +categories = ["command-line-interface", "command-line-utilities", "development-tools", "accessibility"] + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] +clap = "~4" +textwrap = { version = "0.16.1", default-features = false } + +[dev-dependencies] +clap = { version = "~4", features = ["derive"] } +expect-test = "1.5.0" diff --git a/clap-markdown/LICENSE-APACHE b/clap-markdown/LICENSE-APACHE new file mode 100644 index 00000000..2b3c52f9 --- /dev/null +++ b/clap-markdown/LICENSE-APACHE @@ -0,0 +1,176 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS \ No newline at end of file diff --git a/clap-markdown/LICENSE-MIT b/clap-markdown/LICENSE-MIT new file mode 100644 index 00000000..fa13aaa4 --- /dev/null +++ b/clap-markdown/LICENSE-MIT @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2022 Connor Gray + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. \ No newline at end of file diff --git a/clap-markdown/README.md b/clap-markdown/README.md new file mode 100644 index 00000000..0ed1c9c2 --- /dev/null +++ b/clap-markdown/README.md @@ -0,0 +1,25 @@ +# clap-markdown + +This is a vendored fork of Connor Gray's [`clap-markdown`][clap-markdown] +crate, which seems to be unmaintained (as of 2024-05). + +[clap-markdown]: https://github.com/ConnorGray/clap-markdown/ + +Major changes include: + +- Arguments are listed in a [`
` description list][dl] instead of a bulleted list. + + mdBook's Markdown renderer, pulldown-cmark, [doesn't support description + lists][pulldown-cmark-67], so we have to generate [raw inline + HTML][commonmark-html]. This makes the Markdown output much less pretty, but + looks great rendered in the ghciwatch user manual. + +- Arguments are wrapped in [``][anchor] links so that other parts + of the manual can link to specific arguments. + +- Support for documenting subcommands has been removed, as it's not used here. + +[anchor]: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a#linking_to_an_element_on_the_same_page +[dl]: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/dl +[pulldown-cmark-67]: https://github.com/pulldown-cmark/pulldown-cmark/issues/67 +[commonmark-html]: https://spec.commonmark.org/0.31.2/#raw-html diff --git a/clap-markdown/examples/complex_app.md b/clap-markdown/examples/complex_app.md new file mode 100644 index 00000000..fc0401f2 --- /dev/null +++ b/clap-markdown/examples/complex_app.md @@ -0,0 +1,121 @@ +# Command-line arguments for `clap-markdown` + +This is the short help. It goes first. + +**Usage:** `clap-markdown [OPTIONS]` + + + +This is the long help. It comes after. + +## Examples + +Do something simple with the defaults: + + complex_app + +## Options +
+ +
--command <SHELL_COMMAND>
+ +A shell command which starts a `ghci` REPL, e.g. `ghci` or `cabal v2-repl` or similar. + +This is used to launch the underlying `ghci` session that `ghciwatch` controls. + +May contain quoted arguments which will be parsed in a `sh`-like manner. + +
+
--enable-eval
+ +Evaluate Haskell code in comments. + +This parses line commands starting with `-- $>` or multiline commands delimited by `{- $>` and `<$ -}` and evaluates them after reloads. + +
+ +
+ +## File watching options +
+ +
--poll <DURATION>
+ +Use polling with the given interval rather than notification-based file watching. + +Polling tends to be more reliable and less performant. In particular, notification-based watching often misses updates on macOS. + +
+
--watch <PATH>
+ +A path to watch for changes. + +Directories are watched recursively. Can be given multiple times. + +
+
--reload-glob <RELOAD_GLOBS>
+ +Reload the `ghci` session when paths matching this glob change. + +By default, only changes to Haskell source files trigger reloads. If you'd like to exclude some files from that, you can add an ignore glob here, like `!src/my-special-dir/**/*.hs`. + +Globs provided here have precisely the same semantics as a single line in a `gitignore` file (`man gitignore`), where the meaning of `!` is inverted: namely, `!` at the beginning of a glob will ignore a file. + +The last matching glob will determine if a reload is triggered. + +Can be given multiple times. + +
+ +
+ +## Logging options +
+ +
--log-filter <LOG_FILTER>
+ +Log message filter. + +Can be any of "error", "warn", "info", "debug", or "trace". Supports more granular filtering, as well. + +The grammar is: `target[span{field=value}]=level`, where `target` is a module path, `span` is a span name, and `level` is one of the levels listed above. + +See [documentation in `tracing-subscriber`][1]. + +A nice value is `ghciwatch=debug`. + +[1]: https://docs.rs/tracing-subscriber/latest/tracing_subscriber/filter/struct.EnvFilter.html + + Default value: `ghciwatch=info` + +
+
--trace-spans <TRACE_SPANS>
+ +When to log span events, which loosely correspond to tasks being run in the async runtime. + +Allows multiple values, comma-separated. + + Default value: `new,close` + + Possible values: + - `new`: + Log when spans are created + - `enter`: + Log when spans are entered + - `exit`: + Log when spans are exited + - `close`: + Log when spans are dropped + - `none`: + Do not log span events + - `active`: + Log when spans are entered/exited + - `full`: + Log all span events + + +
+ +
+ + diff --git a/clap-markdown/examples/complex_app.rs b/clap-markdown/examples/complex_app.rs new file mode 100644 index 00000000..a5479373 --- /dev/null +++ b/clap-markdown/examples/complex_app.rs @@ -0,0 +1,162 @@ +use clap::builder::EnumValueParser; +use clap::builder::PossibleValue; +use clap::builder::ValueParserFactory; +use clap::Parser; + +/// This is the short help. It goes first. +/// +/// This is the long help. It comes after. +/// +/// ## Examples +/// +/// Do something simple with the defaults: +/// +/// complex_app +#[derive(Debug, Clone, Parser)] +#[command(version, author, verbatim_doc_comment)] +pub struct Opts { + /// A shell command which starts a `ghci` REPL, e.g. `ghci` or `cabal v2-repl` or similar. + /// + /// This is used to launch the underlying `ghci` session that `ghciwatch` controls. + /// + /// May contain quoted arguments which will be parsed in a `sh`-like manner. + #[arg(long, value_name = "SHELL_COMMAND")] + pub command: Option, + + /// Evaluate Haskell code in comments. + /// + /// This parses line commands starting with `-- $>` or multiline commands delimited by `{- $>` + /// and `<$ -}` and evaluates them after reloads. + #[arg(long, alias = "allow-eval")] + pub enable_eval: bool, + + /// Enable TUI mode (experimental). + #[arg(long, hide = true)] + pub tui: bool, + + /// Options to modify file watching. + #[command(flatten)] + pub watch: WatchOpts, + + /// Options to modify logging and error-handling behavior. + #[command(flatten)] + pub logging: LoggingOpts, +} + +/// Options for watching files. +#[derive(Debug, Clone, clap::Args)] +#[clap(next_help_heading = "File watching options")] +pub struct WatchOpts { + /// Use polling with the given interval rather than notification-based file watching. + /// + /// Polling tends to be more reliable and less performant. In particular, notification-based + /// watching often misses updates on macOS. + #[arg(long, value_name = "DURATION")] + pub poll: Option, + + /// A path to watch for changes. + /// + /// Directories are watched recursively. Can be given multiple times. + #[arg(long = "watch", value_name = "PATH")] + pub paths: Vec, + + /// Reload the `ghci` session when paths matching this glob change. + /// + /// By default, only changes to Haskell source files trigger reloads. If you'd like to exclude + /// some files from that, you can add an ignore glob here, like `!src/my-special-dir/**/*.hs`. + /// + /// Globs provided here have precisely the same semantics as a single line in a `gitignore` + /// file (`man gitignore`), where the meaning of `!` is inverted: namely, `!` at the beginning + /// of a glob will ignore a file. + /// + /// The last matching glob will determine if a reload is triggered. + /// + /// Can be given multiple times. + #[arg(long = "reload-glob")] + pub reload_globs: Vec, +} + +/// Options to modify logging and error-handling behavior. +#[derive(Debug, Clone, clap::Args)] +#[clap(next_help_heading = "Logging options")] +pub struct LoggingOpts { + /// Log message filter. + /// + /// Can be any of "error", "warn", "info", "debug", or "trace". Supports more granular + /// filtering, as well. + /// + /// The grammar is: `target[span{field=value}]=level`, where `target` is a module path, `span` + /// is a span name, and `level` is one of the levels listed above. + /// + /// See [documentation in `tracing-subscriber`][1]. + /// + /// A nice value is `ghciwatch=debug`. + /// + /// [1]: https://docs.rs/tracing-subscriber/latest/tracing_subscriber/filter/struct.EnvFilter.html + #[arg(long, default_value = "ghciwatch=info")] + pub log_filter: String, + + /// When to log span events, which loosely correspond to tasks being run in the async runtime. + /// + /// Allows multiple values, comma-separated. + #[arg( + long, + default_value = "new,close", + value_delimiter = ',', + value_parser = FmtSpanParserFactory::value_parser() + )] + pub trace_spans: Vec, +} + +#[derive(Clone, Debug)] +pub enum FmtSpan { + NEW, + ENTER, + EXIT, + CLOSE, + NONE, + ACTIVE, + FULL, +} + +impl clap::ValueEnum for FmtSpan { + fn value_variants<'a>() -> &'a [Self] { + &[ + Self::NEW, + Self::ENTER, + Self::EXIT, + Self::CLOSE, + Self::NONE, + Self::ACTIVE, + Self::FULL, + ] + } + + fn to_possible_value(&self) -> Option { + Some(match self { + Self::NEW => PossibleValue::new("new").help("Log when spans are created"), + Self::ENTER => PossibleValue::new("enter").help("Log when spans are entered"), + Self::EXIT => PossibleValue::new("exit").help("Log when spans are exited"), + Self::CLOSE => PossibleValue::new("close").help("Log when spans are dropped"), + Self::NONE => PossibleValue::new("none").help("Do not log span events"), + Self::ACTIVE => PossibleValue::new("active").help("Log when spans are entered/exited"), + Self::FULL => PossibleValue::new("full").help("Log all span events"), + }) + } +} + +/// [`clap`] parser factory for [`FmtSpan`] values. +pub struct FmtSpanParserFactory; + +impl ValueParserFactory for FmtSpanParserFactory { + type Parser = EnumValueParser; + + fn value_parser() -> Self::Parser { + EnumValueParser::::new() + } +} + +fn main() { + let opts = Opts::parse(); + println!("{opts:#?}"); +} diff --git a/clap-markdown/src/formatter.rs b/clap-markdown/src/formatter.rs new file mode 100644 index 00000000..c2c1fee0 --- /dev/null +++ b/clap-markdown/src/formatter.rs @@ -0,0 +1,387 @@ +use clap::builder::PossibleValue; +use clap::Arg; +use clap::ArgAction; +use clap::Command; + +use std::fmt; +use std::fmt::Write; + +#[derive(Default)] +pub struct FormatState { + in_description_list: bool, + section: Option, +} + +pub struct Formatter<'c, W> { + writer: W, + command: &'c Command, + state: FormatState, +} + +impl<'c, W> Formatter<'c, W> +where + W: Write, +{ + pub fn new(writer: W, command: &'c Command) -> Self { + Self { + writer, + command, + state: Default::default(), + } + } + + pub fn write(&mut self) -> std::fmt::Result { + //---------------------------------- + // Write the document title + //---------------------------------- + + let title_name = match self.command.get_display_name() { + Some(display_name) => display_name.to_owned(), + None => format!("`{}`", self.command.get_name()), + }; + + writeln!(self.writer, "# Command-line arguments for {title_name}\n")?; + + self.build_command_markdown()?; + + Ok(()) + } + + fn build_command_markdown(&mut self) -> std::fmt::Result { + // Don't document commands marked with `clap(hide = true)` (which includes + // `print-all-help`). + if self.command.is_hide_set() { + return Ok(()); + } + + let mut wrote_usage = false; + + if let Some(long_about) = self.command.get_long_about() { + if let Some(about) = self.command.get_about() { + writeln!(self.writer, "{}\n", about)?; + + self.write_usage()?; + wrote_usage = true; + + let long_about = long_about.to_string(); + let long_about = long_about + .strip_prefix(&about.to_string()) + .unwrap_or(&long_about); + writeln!(self.writer, "{}\n", long_about)?; + } else { + writeln!(self.writer, "{}\n", long_about)?; + } + } else if let Some(about) = self.command.get_about() { + writeln!(self.writer, "{}\n", about)?; + } + + // TODO(feature): Support printing custom before and after help texts. + assert!(self.command.get_before_help().is_none()); + assert!(self.command.get_after_help().is_none()); + + if !wrote_usage { + self.write_usage()?; + } + + //---------------------------------- + // Arguments + //---------------------------------- + + if self.command.get_positionals().next().is_some() { + self.state.section = None; + writeln!(self.writer, "## Arguments")?; + + for pos_arg in self.command.get_positionals() { + self.write_arg_markdown(pos_arg)?; + } + + self.end_description_list()?; + + writeln!(self.writer)?; + } + + //---------------------------------- + // Options + //---------------------------------- + + let non_pos: Vec<_> = self + .command + .get_arguments() + .filter(|arg| !arg.is_positional()) + .collect(); + + if !non_pos.is_empty() { + self.state.section = None; + writeln!(self.writer, "## Options")?; + + for arg in non_pos { + if arg.is_hide_set() { + continue; + } + + self.write_arg_markdown(arg)?; + } + + self.end_description_list()?; + + writeln!(self.writer)?; + } + + assert!( + self.command + .get_subcommands() + .collect::>() + .is_empty(), + "Documenting subcommands is unsupported" + ); + + Ok(()) + } + + fn write_usage(&mut self) -> fmt::Result { + let usage = self + .command + .clone() + .render_usage() + .to_string() + .replace("Usage: ", ""); + + writeln!(self.writer, "**Usage:** `{}`\n", usage) + } + + fn start_description_list(&mut self) -> fmt::Result { + if self.state.in_description_list { + Ok(()) + } else { + self.state.in_description_list = true; + writeln!(self.writer, "
\n") + } + } + + fn end_description_list(&mut self) -> fmt::Result { + if self.state.in_description_list { + self.state.in_description_list = false; + writeln!(self.writer, "\n
\n") + } else { + Ok(()) + } + } + + fn write_arg_markdown(&mut self, arg: &Arg) -> fmt::Result { + if let Some(heading) = arg.get_help_heading() { + if self + .state + .section + .as_deref() + .map(|current_heading| current_heading != heading) + .unwrap_or(true) + { + self.end_description_list()?; + + writeln!(self.writer, "## {heading}")?; + + self.state.section = Some(heading.to_owned()); + } + } + + self.start_description_list()?; + + self.write_arg_dt(arg)?; + + if let Some(help) = arg.get_long_help().or_else(|| arg.get_help()) { + writeln!(self.writer, "{help}")?; + } else { + writeln!(self.writer)?; + } + + self.write_default_values(arg)?; + + self.write_possible_values(arg)?; + + writeln!(self.writer, "\n")?; + + Ok(()) + } + + fn write_arg_values(&mut self, arg: &Arg) -> fmt::Result { + // Modified from a private `Arg` method. + + if !arg.get_action().takes_values() { + return Ok(()); + } + + let num_vals = arg.get_num_args().unwrap_or_else(|| 1.into()); + + let mut val_names = arg + .get_value_names() + .map(|names| { + names + .iter() + .map(|s| s.as_str().to_owned()) + .collect::>() + }) + .unwrap_or_else(|| vec![arg.get_id().as_str().to_owned()]); + + if val_names.len() == 1 { + let min = num_vals.min_values().max(1); + let val_name = val_names.pop().unwrap(); + val_names = vec![val_name; min]; + } + + for val_name in val_names.iter() { + let arg_name = if arg.is_positional() + && (num_vals.min_values() == 0 || !arg.get_default_values().is_empty()) + { + format!("[{val_name}]") + } else { + format!("<{val_name}>") + }; + + write!(self.writer, " {arg_name}")?; + } + + let mut extra_values = false; + extra_values |= val_names.len() < num_vals.max_values(); + if arg.is_positional() && matches!(*arg.get_action(), ArgAction::Append) { + extra_values = true; + } + if extra_values { + write!(self.writer, "...")?; + } + + Ok(()) + } + + /// Write the `
` tag for an argument, including anchor links. + fn write_arg_dt(&mut self, arg: &Arg) -> fmt::Result { + write!(self.writer, "
")?; + + if let Some(short) = arg.get_short() { + write!( + self.writer, + "-{short}" + )?; + let has_long = arg.get_long().is_none(); + if !has_long { + self.write_arg_values(arg)?; + } + write!(self.writer, "")?; + if has_long { + write!(self.writer, ", ")?; + } + } + + if let Some(long) = arg.get_long() { + write!( + self.writer, + "--{long}" + )?; + self.write_arg_values(arg)?; + write!(self.writer, "")?; + } + + if arg.is_positional() { + let id = arg + .get_value_names() + .and_then(|names| names.get(0)) + .map(|name| name.as_str()) + .unwrap_or_else(|| arg.get_id().as_str()); + + write!(self.writer, "")?; + self.write_arg_values(arg)?; + write!(self.writer, "")?; + } + + // Note: A blank line is needed between an HTML tag and Markdown for inline markup to + // render correctly. Looks clumsy in the rendered version but that's just how it is for + // now. + // https://github.com/pulldown-cmark/pulldown-cmark/issues/67 + write!(self.writer, "
\n\n")?; + + Ok(()) + } + + fn write_default_values(&mut self, arg: &Arg) -> fmt::Result { + if !arg.get_default_values().is_empty() { + let default_values: String = arg + .get_default_values() + .iter() + .map(|value| format!("`{}`", value.to_string_lossy())) + .collect::>() + .join(", "); + + if arg.get_default_values().len() > 1 { + // Plural + writeln!(self.writer, "\n Default values: {default_values}")?; + } else { + // Singular + writeln!(self.writer, "\n Default value: {default_values}")?; + } + } + + Ok(()) + } + + fn write_possible_values(&mut self, arg: &Arg) -> fmt::Result { + match arg.get_action() { + ArgAction::SetTrue + | ArgAction::SetFalse + | ArgAction::Help + | ArgAction::HelpShort + | ArgAction::HelpLong + | ArgAction::Version => { + return Ok(()); + } + _ => {} + } + + let possible_values: Vec = arg + .get_possible_values() + .into_iter() + .filter(|pv| !pv.is_hide_set()) + .collect(); + + if !possible_values.is_empty() { + let any_have_help: bool = possible_values.iter().any(|pv| pv.get_help().is_some()); + + if any_have_help { + // If any of the possible values have help text, print them + // as a separate item in a bulleted list, and include the + // help text for those that have it. E.g.: + // + // Possible values: + // - `value1`: + // The help text + // - `value2` + // - `value3`: + // The help text + + let text: String = possible_values + .iter() + .map(|pv| match pv.get_help() { + Some(help) => { + format!(" - `{}`:\n {}\n", pv.get_name(), help) + } + None => format!(" - `{}`\n", pv.get_name()), + }) + .collect::>() + .join(""); + + writeln!(self.writer, "\n Possible values:\n{text}")?; + } else { + // If none of the possible values have any documentation, print + // them all inline on a single line. + let text: String = possible_values + .iter() + // TODO: Show PossibleValue::get_help(), and PossibleValue::get_name_and_aliases(). + .map(|pv| format!("`{}`", pv.get_name())) + .collect::>() + .join(", "); + + writeln!(self.writer, "\n Possible values: {text}\n")?; + } + } + + Ok(()) + } +} diff --git a/clap-markdown/src/lib.rs b/clap-markdown/src/lib.rs new file mode 100644 index 00000000..19f19423 --- /dev/null +++ b/clap-markdown/src/lib.rs @@ -0,0 +1,31 @@ +//! Autogenerate Markdown documentation for clap command-line tools + +mod formatter; +use formatter::Formatter; + +/// Format the help information for `command` as Markdown. +pub fn help_markdown() -> String { + let command = C::command(); + + help_markdown_command(&command) +} + +/// Format the help information for `command` as Markdown. +pub fn help_markdown_command(command: &clap::Command) -> String { + let mut buffer = String::with_capacity(2048); + + Formatter::new(&mut buffer, command).write().unwrap(); + + buffer +} + +/// Format the help information for `command` as Markdown and print it. +/// +/// Output is printed to the standard output, using [`println!`]. +pub fn print_help_markdown() { + let command = C::command(); + + let markdown = help_markdown_command(&command); + + println!("{markdown}"); +} diff --git a/clap-markdown/tests/test_examples.rs b/clap-markdown/tests/test_examples.rs new file mode 100644 index 00000000..1bd98fb1 --- /dev/null +++ b/clap-markdown/tests/test_examples.rs @@ -0,0 +1,12 @@ +use expect_test::expect_file; + +#[test] +fn test_example_complex_app() { + mod complex_app { + include!("../examples/complex_app.rs"); + } + + let expected = expect_file!["../examples/complex_app.md"]; + + expected.assert_eq(&clap_markdown::help_markdown::()); +}