clap-markdown-0.1.4/.cargo_vcs_info.json0000644000000001360000000000100135750ustar { "git": { "sha1": "1e1ae469444604d5b9ee650232abc2d3a0fa723b" }, "path_in_vcs": "" }clap-markdown-0.1.4/.github/workflows/BuildAndTestPR.yml000064400000000000000000000005061046102023000212720ustar 00000000000000name: Build and Test on: push: branches: [ "main" ] pull_request: branches: [ "main" ] env: CARGO_TERM_COLOR: always jobs: build: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - name: Build run: cargo build --verbose - name: Run tests run: cargo test --verbose clap-markdown-0.1.4/.gitignore000064400000000000000000000000241046102023000143510ustar 00000000000000/target /Cargo.lock clap-markdown-0.1.4/Cargo.toml0000644000000021530000000000100115740ustar # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies. # # If you are reading this file be aware that the original Cargo.toml # will likely look very different (and much more reasonable). # See Cargo.toml.orig for the original contents. [package] edition = "2021" name = "clap-markdown" version = "0.1.4" authors = ["Connor Gray "] description = "Autogenerate Markdown documentation for clap command-line tools" readme = "README.md" keywords = [ "clap", "markdown", "command-line", "help", ] categories = [ "command-line-interface", "command-line-utilities", "development-tools", "accessibility", ] license = "MIT OR Apache-2.0" repository = "https://github.com/ConnorGray/clap-markdown" [dependencies.clap] version = "4.*.*" [dev-dependencies.clap] version = "4.4.0" features = ["derive"] [dev-dependencies.pretty_assertions] version = "1.3.0" clap-markdown-0.1.4/Cargo.toml.orig000064400000000000000000000012701046102023000152540ustar 00000000000000[package] name = "clap-markdown" version = "0.1.4" 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.*.*" [dev-dependencies] clap = { version = "4.4.0", features = ["derive"] } pretty_assertions = "1.3.0" clap-markdown-0.1.4/LICENSE-APACHE000064400000000000000000000232021046102023000143100ustar 00000000000000 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 CONDITIONSclap-markdown-0.1.4/LICENSE-MIT000064400000000000000000000020531046102023000140210ustar 00000000000000MIT 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.clap-markdown-0.1.4/README.md000064400000000000000000000076221046102023000136530ustar 00000000000000# clap-markdown [![Crates.io](https://img.shields.io/crates/v/clap-markdown.svg)](https://crates.io/crates/clap-markdown) ![License](https://img.shields.io/crates/l/clap-markdown.svg) [![Documentation](https://docs.rs/clap-markdown/badge.svg)](https://docs.rs/clap-markdown) #### [API Documentation](https://docs.rs/clap-markdown) | [Changelog](./docs/CHANGELOG.md) | [Contributing](#contributing) Automatically generate Markdown documentation for [`clap`](https://crates.io/crates/clap) command-line tools. ## Examples Generate Markdown text for a basic `clap` app: ```rust #[derive(clap::Parser)] struct Cli { #[arg()] name: String, } let markdown: String = clap_markdown::help_markdown::(); ``` **Generated Markdown Examples:** See `clap` example programs and the corresponding Markdown generated by `clap-markdown`: | Program | Markdown | |------------------------------------------------------|--------------------------------------------------| | [`./complex_app.rs`](./docs/examples/complex_app.rs) | [complex-app.md](./docs/examples/complex-app.md) | ### Usage Convention: `CommandLineHelp.md` This section describes a suggested convention for using `clap-markdown` to generate a `CommandLineHelp.md` file, which can be committed to source control and viewed as online documentation. 1. Add a hidden `--markdown-help` option to your `clap` application: ```rust use clap::Parser; #[derive(Parser)] struct Cli { #[arg(long, hide = true)] markdown_help: bool, } fn main() { let args = Cli::parse(); // Invoked as: `$ my-app --markdown-help` if args.markdown_help { clap_markdown::print_help_markdown::(); } } ``` 2. Invoke `--markdown-help` to generate a `CommandLineHelp.md` file: ```shell $ cargo run -- --markdown-help > docs/CommandLineHelp.md ``` 3. Save `CommandLineHelp.md` in git, and link to it from the project's README.md or other relevant documentation. > For projects that have multiple associated executables, consider using the > command name as a suffix. For example: `CommandLineHelp-your-app.md`, > `CommandLineHelp-other-app.md`. > Comitting `CommandLineHelp.md` to version control makes it easy to track > user-visible changes to the command-line interface. #### Projects using `clap-markdown` The following projects use `clap-markdown` to generate a `CommandLineHelp.md` reference document: * [`wolfram-app-discovery`](https://crates.io/crates/wolfram-app-discovery) — [`CommandLineHelp.md`](https://github.com/WolframResearch/wolfram-app-discovery-rs/blob/master/docs/CommandLineHelp.md) * [`wolfram-cli`](https://github.com/ConnorGray/wolfram-cli) — [`CommandLineHelp.md`](https://github.com/ConnorGray/wolfram-cli/blob/main/docs/CommandLineHelp.md) To request the addition of a project to this list, please file an issue. ## Compatibility with clap When this crate adds support for a new MAJOR version of `clap`, the MAJOR version number of `clap-markdown` will be changed. **Compability History:** | `clap-markdown` | `clap` | |-----------------|-----------| | v0.0.1 – v0.1.4 | `"4.*.*"` | ## License Licensed under either of * Apache License, Version 2.0 ([LICENSE-APACHE](./LICENSE-APACHE) or ) * MIT license ([LICENSE-MIT](./LICENSE-MIT) or ) at your option. ## Contributing Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions. See [**Development.md**](./docs/Development.md) for instructions on how to perform common development tasks. See [*Maintenance.md*](./docs/Maintenance.md) for instructions on how to maintain this project. clap-markdown-0.1.4/docs/CHANGELOG.md000064400000000000000000000127671046102023000151430ustar 00000000000000# Changelog All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). ## [Unreleased] ## [0.1.4] — 2024-06-15 ### Added * Added `help_markdown_custom()` and `help_markdown_command_custom()`, for customizing the built Markdown using a new `MarkdownOptions` configuration structure. ([#25], co-authored-by [@morgante](https://github.com/morgante) and [@keturiosakys](https://github.com/keturiosakys)) Supported customization options include: - Contents of the command title header. - Whether to show the footer explaining the documentation was generated with `clap-markdown`. - Whether to show the command overview table of contents. * Added new CI build and test action to the repository, so that new PRs will be required automatically to pass all tests. ([#24]) ### Changed * `clap-markdown` will now respect the `Command.display_name` property, if set, and use it in the rendered Markdown when showing the name and usage of the command. ([#27], co-authored-by [@keturiosakys](https://github.com/keturiosakys) and [@hatchan](https://github.com/hatchan)) * The possible values of a flag that can only either be present or absent (true or false) will no longer be shown. ([#22], contributed by [@ilyagr](https://github.com/ilyagr)) * Hidden arguments (`Arg.hide == true`) will no longer be included in the rendered Markdown. ([#22], contributed by [@ilyagr](https://github.com/ilyagr)) * Long help text for commands will now be included in the rendered output. ([#26], contributed by [@morgante](https://github.com/morgante)) * Long help text for options will now be included in the rendered output. ([#23], contributed by [@ilyagr](https://github.com/ilyagr)) ## [0.1.3] - 2022-12-28 ### Added * For arguments that take a value, the argument value name ([`Arg::get_value_names()`](https://docs.rs/clap/4.0.32/clap/struct.Arg.html#method.get_value_names)) is now included in the generated Markdown. ([#11]) * For arguments that have default values ([`Arg::get_default_values()`](https://docs.rs/clap/4.0.32/clap/struct.Arg.html#method.get_default_values)) , those default values are mentioned in the generated Markdown. ([#11]) ### Changed * The rendered Markdown for [`PossibleValue`](https://docs.rs/clap/4.0.32/clap/builder/struct.PossibleValue.html) literal values now uses `code` styling instead of **emphasized** styling, for consistency with other literally-what-the-user-types help content (e.g. option or subcommand names). ([#11]) ## [0.1.2] - 2022-12-28 ### Added * Generated markdown for [`PossibleValue`](https://docs.rs/clap/4.0.32/clap/builder/struct.PossibleValue.html) values will now include the [`PossibleValue::get_help()`](https://docs.rs/clap/4.0.32/clap/builder/struct.PossibleValue.html#method.get_help) content, if it exists. ([#8]) This means that documentation comments present on enum variants that use `#[derive(clap::ValueEnum)]` will be summarized in the generated Markdown documentation. ## [0.1.1] - 2022-12-26 ### Added * Added new basic example to README.md. ([#4]) * Added new 'Usage Convention: CommandLineHelp.md' section to README.md ([#4]) * Add list of projects using `clap-markdown` and `CommandLineHelp.md` convention to README.md. ([#5]) ## [0.1.0] - 2022-12-17 ### Added * Added new [`./docs/examples/`](../docs/examples/) directory to the repository, with Rust source code for the `complex_app.rs` example program, and the generated `complex-app.md` Markdown content for that program. ([#1]) ### Changed * Modify generated Markdown. ([#1]) The following changes are present in the generated Markdown: - Added 'Command-Line Help for {name}' header - Include [`Arg::get_possible_values()`](https://docs.rs/clap/latest/clap/builder/struct.Arg.html#method.get_possible_values) information in arguments and options documentation. - Renamed 'Commands' label to 'Subcommands' - Added small footer at the bottom stating that the document was generated automatically by `clap-markdown`. ## [0.0.1] - 2022-12-13 Initial release of `clap-markdown`. [#1]: https://github.com/ConnorGray/clap-markdown/pull/1 [#4]: https://github.com/ConnorGray/clap-markdown/pull/4 [#5]: https://github.com/ConnorGray/clap-markdown/pull/5 [#8]: https://github.com/ConnorGray/clap-markdown/pull/8 [#11]: https://github.com/ConnorGray/clap-markdown/pull/11 [#22]: https://github.com/ConnorGray/clap-markdown/pull/22 [#23]: https://github.com/ConnorGray/clap-markdown/pull/23 [#24]: https://github.com/ConnorGray/clap-markdown/pull/24 [#25]: https://github.com/ConnorGray/clap-markdown/pull/25 [#26]: https://github.com/ConnorGray/clap-markdown/pull/26 [#27]: https://github.com/ConnorGray/clap-markdown/pull/27 [Unreleased]: https://github.com/ConnorGray/clap-markdown/compare/v0.1.4...HEAD [0.1.4]: https://github.com/ConnorGray/clap-markdown/compare/v0.1.3...v0.1.4 [0.1.3]: https://github.com/ConnorGray/clap-markdown/compare/v0.1.2...v0.1.3 [0.1.2]: https://github.com/ConnorGray/clap-markdown/compare/v0.1.1...v0.1.2 [0.1.1]: https://github.com/ConnorGray/clap-markdown/compare/v0.1.0...v0.1.1 [0.1.0]: https://github.com/ConnorGray/clap-markdown/compare/v0.0.1...v0.1.0 [0.0.1]: https://github.com/ConnorGray/clap-markdown/releases/tag/v0.0.1 clap-markdown-0.1.4/docs/Development.md000064400000000000000000000006001046102023000161150ustar 00000000000000# Development ## Quick Command Reference **Test that the examples are up-to-date:** The [`tests/test_examples.rs`](../tests/test_examples.rs) program contains tests that the Markdown generated for each sample program in [`./docs/examples`](../docs/examples/) matches the corresponding `.md` file. Test that the generated example Markdown is up to date: ```shell $ cargo test ``` clap-markdown-0.1.4/docs/Maintenance.md000064400000000000000000000007711046102023000160660ustar 00000000000000# Maintenance This document describes steps required to maintain the clap-markdown project. This document is informational and intended for the maintainer of this project; users of this project do not need to read this document. ## Release 1. Update the 'Compatibility History' table in README.md each time a new release is made. The `clap-markdown` column should contain the current crate version, and the `clap` column should contain the current `clap = "..."` version constraint value.clap-markdown-0.1.4/docs/examples/complex-app-custom.md000064400000000000000000000020641046102023000212140ustar 00000000000000# Some Custom Title for Complex App This document contains the help content for the `complex-app` command-line program. ## `complex-app` An example command-line tool **Usage:** `complex-app [OPTIONS] [NAME] [COMMAND]` ###### **Subcommands:** * `test` — does testing things * `only-hidden-options` — Demo that `Options` is not printed if all options are hidden ###### **Arguments:** * `` — Optional name to operate on Longer description ###### **Options:** * `-c`, `--config ` — Sets a custom config file * `--target ` Default value: `local` Possible values: - `local`: Do the operation locally - `remote` * `-d`, `--debug` — Turn debugging information on Repeat this option to see more and more debug information. ## `complex-app test` does testing things **Usage:** `complex-app test [OPTIONS]` ###### **Options:** * `-l`, `--list` — lists test values ## `complex-app only-hidden-options` Demo that `Options` is not printed if all options are hidden **Usage:** `complex-app only-hidden-options` clap-markdown-0.1.4/docs/examples/complex-app.md000064400000000000000000000026161046102023000177070ustar 00000000000000# Command-Line Help for `complex-app` This document contains the help content for the `complex-app` command-line program. **Command Overview:** * [`complex-app`↴](#complex-app) * [`complex-app test`↴](#complex-app-test) * [`complex-app only-hidden-options`↴](#complex-app-only-hidden-options) ## `complex-app` An example command-line tool **Usage:** `complex-app [OPTIONS] [NAME] [COMMAND]` ###### **Subcommands:** * `test` — does testing things * `only-hidden-options` — Demo that `Options` is not printed if all options are hidden ###### **Arguments:** * `` — Optional name to operate on Longer description ###### **Options:** * `-c`, `--config ` — Sets a custom config file * `--target ` Default value: `local` Possible values: - `local`: Do the operation locally - `remote` * `-d`, `--debug` — Turn debugging information on Repeat this option to see more and more debug information. ## `complex-app test` does testing things **Usage:** `complex-app test [OPTIONS]` ###### **Options:** * `-l`, `--list` — lists test values ## `complex-app only-hidden-options` Demo that `Options` is not printed if all options are hidden **Usage:** `complex-app only-hidden-options`
This document was generated automatically by clap-markdown. clap-markdown-0.1.4/docs/examples/complex_app.rs000064400000000000000000000022771046102023000200200ustar 00000000000000use std::path::PathBuf; use clap::{Parser, Subcommand}; /// An example command-line tool #[derive(Parser)] #[command(name = "complex-app")] pub struct Cli { /// Optional name to operate on /// /// Longer description name: Option, /// Sets a custom config file #[arg(short, long, value_name = "FILE")] config: Option, #[arg(long, default_value = "local")] target: Target, /// Turn debugging information on /// /// Repeat this option to see more and more debug information. #[arg(short, long, action = clap::ArgAction::Count)] debug: u8, #[arg(short, long, hide = true)] secret_arg: bool, #[command(subcommand)] command: Option, } #[derive(Subcommand)] enum Commands { /// does testing things Test { /// lists test values #[arg(short, long)] list: bool, }, /// Demo that `Options` is not printed if all options are hidden OnlyHiddenOptions { #[arg(short, long, hide = true)] secret: bool, }, } #[derive(clap::ValueEnum)] #[derive(Clone)] enum Target { /// Do the operation locally Local, // Intentionally undocumented. Remote, } clap-markdown-0.1.4/rustfmt.toml000064400000000000000000000002011046102023000147570ustar 00000000000000max_width = 80 match_block_trailing_comma = true blank_lines_upper_bound = 2 merge_derives = false overflow_delimited_expr = trueclap-markdown-0.1.4/src/lib.rs000064400000000000000000000422621046102023000142760ustar 00000000000000//! Autogenerate Markdown documentation for clap command-line tools //! //! See [**Examples**][Examples] for examples of the content `clap-markdown` //! generates. //! //! [Examples]: https://github.com/ConnorGray/clap-markdown#Examples //! // Ensure that doc tests in the README.md file get run. #[doc(hidden)] mod test_readme { #![doc = include_str!("../README.md")] } use std::fmt::{self, Write}; use clap::builder::PossibleValue; //====================================== // Public API types //====================================== /// Options to customize the structure of the output Markdown document. /// /// Used with [`help_markdown_custom()`]. #[non_exhaustive] pub struct MarkdownOptions { title: Option, show_footer: bool, show_table_of_contents: bool, } impl MarkdownOptions { /// Construct a default instance of `MarkdownOptions`. pub fn new() -> Self { return Self { title: None, show_footer: true, show_table_of_contents: true, }; } /// Set a custom title to use in the generated document. pub fn title(mut self, title: String) -> Self { self.title = Some(title); return self; } /// Whether to show the default footer advertising `clap-markdown`. pub fn show_footer(mut self, show: bool) -> Self { self.show_footer = show; return self; } /// Whether to show the default table of contents. pub fn show_table_of_contents(mut self, show: bool) -> Self { self.show_table_of_contents = show; return self; } } impl Default for MarkdownOptions { fn default() -> Self { return Self::new(); } } //====================================== // Public API functions //====================================== /// 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, with custom options. pub fn help_markdown_custom( options: &MarkdownOptions, ) -> String { let command = C::command(); return help_markdown_command_custom(&command, options); } /// Format the help information for `command` as Markdown. pub fn help_markdown_command(command: &clap::Command) -> String { return help_markdown_command_custom(command, &Default::default()); } /// Format the help information for `command` as Markdown, with custom options. pub fn help_markdown_command_custom( command: &clap::Command, options: &MarkdownOptions, ) -> String { let mut buffer = String::with_capacity(100); write_help_markdown(&mut buffer, &command, options); buffer } //====================================== // Markdown //====================================== /// 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 mut buffer = String::with_capacity(100); write_help_markdown(&mut buffer, &command, &Default::default()); println!("{}", buffer); } fn write_help_markdown( buffer: &mut String, command: &clap::Command, options: &MarkdownOptions, ) { //---------------------------------- // Write the document title //---------------------------------- let title_name = get_canonical_name(command); let title = match options.title { Some(ref title) => title.to_owned(), None => format!("Command-Line Help for `{title_name}`"), }; writeln!(buffer, "# {title}\n",).unwrap(); writeln!( buffer, "This document contains the help content for the `{}` command-line program.\n", title_name ).unwrap(); //---------------------------------- // Write the table of contents //---------------------------------- // writeln!(buffer, r#"
    "#).unwrap(); // build_table_of_contents_html(buffer, Vec::new(), command, 0).unwrap(); // writeln!(buffer, "
").unwrap(); if options.show_table_of_contents { writeln!(buffer, "**Command Overview:**\n").unwrap(); build_table_of_contents_markdown(buffer, Vec::new(), command, 0) .unwrap(); write!(buffer, "\n").unwrap(); } //---------------------------------------- // Write the commands/subcommands sections //---------------------------------------- build_command_markdown(buffer, Vec::new(), command, 0).unwrap(); //----------------- // Write the footer //----------------- if options.show_footer { write!(buffer, r#"
This document was generated automatically by clap-markdown. "#).unwrap(); } } fn build_table_of_contents_markdown( buffer: &mut String, // Parent commands of `command`. parent_command_path: Vec, command: &clap::Command, depth: usize, ) -> std::fmt::Result { // Don't document commands marked with `clap(hide = true)` (which includes // `print-all-help`). if command.is_hide_set() { return Ok(()); } let title_name = get_canonical_name(command); // Append the name of `command` to `command_path`. let command_path = { let mut command_path = parent_command_path; command_path.push(title_name); command_path }; writeln!( buffer, "* [`{}`↴](#{})", command_path.join(" "), command_path.join("-"), )?; //---------------------------------- // Recurse to write subcommands //---------------------------------- for subcommand in command.get_subcommands() { build_table_of_contents_markdown( buffer, command_path.clone(), subcommand, depth + 1, )?; } Ok(()) } /* fn build_table_of_contents_html( buffer: &mut String, // Parent commands of `command`. parent_command_path: Vec, command: &clap::Command, depth: usize, ) -> std::fmt::Result { // Don't document commands marked with `clap(hide = true)` (which includes // `print-all-help`). if command.is_hide_set() { return Ok(()); } // Append the name of `command` to `command_path`. let command_path = { let mut command_path = parent_command_path; command_path.push(command.get_name().to_owned()); command_path }; writeln!( buffer, "
  • {}
  • ", command_path.join("-"), command_path.join(" ") )?; //---------------------------------- // Recurse to write subcommands //---------------------------------- for subcommand in command.get_subcommands() { build_table_of_contents_html( buffer, command_path.clone(), subcommand, depth + 1, )?; } Ok(()) } */ fn build_command_markdown( buffer: &mut String, // Parent commands of `command`. parent_command_path: Vec, command: &clap::Command, depth: usize, ) -> std::fmt::Result { // Don't document commands marked with `clap(hide = true)` (which includes // `print-all-help`). if command.is_hide_set() { return Ok(()); } let title_name = get_canonical_name(command); // Append the name of `command` to `command_path`. let command_path = { let mut command_path = parent_command_path.clone(); command_path.push(title_name); command_path }; //---------------------------------- // Write the markdown heading //---------------------------------- // TODO: `depth` is now unused. Remove if no other use for it appears. /* if depth >= 6 { panic!( "command path nesting depth is deeper than maximum markdown header depth: `{}`", command_path.join(" ") ) } */ writeln!( buffer, "{} `{}`\n", // "#".repeat(depth + 1), "##", command_path.join(" "), )?; if let Some(long_about) = command.get_long_about() { writeln!(buffer, "{}\n", long_about)?; } else if let Some(about) = command.get_about() { writeln!(buffer, "{}\n", about)?; } if let Some(help) = command.get_before_long_help() { writeln!(buffer, "{}\n", help)?; } else if let Some(help) = command.get_before_help() { writeln!(buffer, "{}\n", help)?; } writeln!( buffer, "**Usage:** `{}{}`\n", if parent_command_path.is_empty() { String::new() } else { let mut s = parent_command_path.join(" "); s.push_str(" "); s }, command .clone() .render_usage() .to_string() .replace("Usage: ", "") )?; if let Some(help) = command.get_after_long_help() { writeln!(buffer, "{}\n", help)?; } else if let Some(help) = command.get_after_help() { writeln!(buffer, "{}\n", help)?; } //---------------------------------- // Subcommands //---------------------------------- if command.get_subcommands().next().is_some() { writeln!(buffer, "###### **Subcommands:**\n")?; for subcommand in command.get_subcommands() { if subcommand.is_hide_set() { continue; } let title_name = get_canonical_name(subcommand); let about = match subcommand.get_about() { Some(about) => about.to_string(), None => String::new(), }; writeln!(buffer, "* `{title_name}` — {about}",)?; } write!(buffer, "\n")?; } //---------------------------------- // Arguments //---------------------------------- if command.get_positionals().next().is_some() { writeln!(buffer, "###### **Arguments:**\n")?; for pos_arg in command.get_positionals() { write_arg_markdown(buffer, pos_arg)?; } write!(buffer, "\n")?; } //---------------------------------- // Options //---------------------------------- let non_pos: Vec<_> = command .get_arguments() .filter(|arg| !arg.is_positional() && !arg.is_hide_set()) .collect(); if !non_pos.is_empty() { writeln!(buffer, "###### **Options:**\n")?; for arg in non_pos { write_arg_markdown(buffer, arg)?; } write!(buffer, "\n")?; } //---------------------------------- // Recurse to write subcommands //---------------------------------- // Include extra space between commands. This is purely for the benefit of // anyone reading the source .md file. write!(buffer, "\n\n")?; for subcommand in command.get_subcommands() { build_command_markdown( buffer, command_path.clone(), subcommand, depth + 1, )?; } Ok(()) } fn write_arg_markdown(buffer: &mut String, arg: &clap::Arg) -> fmt::Result { // Markdown list item write!(buffer, "* ")?; let value_name: String = match arg.get_value_names() { // TODO: What if multiple names are provided? Some([name, ..]) => name.as_str().to_owned(), Some([]) => unreachable!( "clap Arg::get_value_names() returned Some(..) of empty list" ), None => arg.get_id().to_string().to_ascii_uppercase(), }; match (arg.get_short(), arg.get_long()) { (Some(short), Some(long)) => { if arg.get_action().takes_values() { write!(buffer, "`-{short}`, `--{long} <{value_name}>`")? } else { write!(buffer, "`-{short}`, `--{long}`")? } }, (Some(short), None) => { if arg.get_action().takes_values() { write!(buffer, "`-{short} <{value_name}>`")? } else { write!(buffer, "`-{short}`")? } }, (None, Some(long)) => { if arg.get_action().takes_values() { write!(buffer, "`--{} <{value_name}>`", long)? } else { write!(buffer, "`--{}`", long)? } }, (None, None) => { debug_assert!(arg.is_positional(), "unexpected non-positional Arg with neither short nor long name: {arg:?}"); write!(buffer, "`<{value_name}>`",)?; }, } if let Some(help) = arg.get_long_help() { // TODO: Parse formatting in the string buffer.push_str(&indent(&help.to_string(), " — ", " ")) } else if let Some(short_help) = arg.get_help() { writeln!(buffer, " — {short_help}")?; } else { writeln!(buffer)?; } //-------------------- // Arg default values //-------------------- 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!(buffer, "\n Default values: {default_values}")?; } else { // Singular writeln!(buffer, "\n Default value: {default_values}")?; } } //-------------------- // Arg possible values //-------------------- let possible_values: Vec = arg .get_possible_values() .into_iter() .filter(|pv| !pv.is_hide_set()) .collect(); // Print possible values for options that take a value, but not for flags // that can only be either present or absent and do not take a value. if !possible_values.is_empty() && !matches!(arg.get_action(), clap::ArgAction::SetTrue) { 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!(buffer, "\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!(buffer, "\n Possible values: {text}\n")?; } } Ok(()) } /// Utility function to get the canonical name of a command. /// /// It's logic is to get the display name if it exists, otherwise get the bin /// name if it exists, otherwise get the package name. /// /// Note that the default `Command.name` field of a clap command is typically /// meant for programmatic usage as well as for display (if no `display_name` /// override is set). fn get_canonical_name(command: &clap::Command) -> String { command .get_display_name() .or_else(|| command.get_bin_name()) .map(|name| name.to_owned()) .unwrap_or_else(|| command.get_name().to_owned()) } /// Indents non-empty lines. The output always ends with a newline. fn indent(s: &str, first: &str, rest: &str) -> String { if s.is_empty() { // For consistency. It's easiest to always add a newline at the end, and // there's little reason not to. return "\n".to_string(); } let mut result = String::new(); let mut first_line = true; for line in s.lines() { if !line.is_empty() { result.push_str(if first_line { first } else { rest }); result.push_str(line); first_line = false; } result.push('\n'); } result } #[cfg(test)] mod test { use pretty_assertions::assert_eq; #[test] fn test_indent() { use super::indent; assert_eq!( &indent("Header\n\nMore info", "___", "~~~~"), "___Header\n\n~~~~More info\n" ); assert_eq!( &indent("Header\n\nMore info\n", "___", "~~~~"), &indent("Header\n\nMore info", "___", "~~~~"), ); assert_eq!(&indent("", "___", "~~~~"), "\n"); assert_eq!(&indent("\n", "___", "~~~~"), "\n"); } } clap-markdown-0.1.4/tests/test_examples.rs000064400000000000000000000014661046102023000167610ustar 00000000000000use clap_markdown::MarkdownOptions; use pretty_assertions::assert_eq; /// Tests that the `complex-app` example featured in the README.md is /// up-to-date. #[test] fn test_example_complex_app() { mod complex_app { include!("../docs/examples/complex_app.rs"); } assert_eq!( clap_markdown::help_markdown::(), include_str!("../docs/examples/complex-app.md") ); assert_eq!( clap_markdown::help_markdown_custom::( &MarkdownOptions::new() .title(format!("Some Custom Title for Complex App")) .show_footer(false) .show_table_of_contents(false) ), include_str!("../docs/examples/complex-app-custom.md"), "Mismatch testing CUSTOM Markdown output" ); } clap-markdown-0.1.4/tests/test_markdown.rs000064400000000000000000000072661046102023000167710ustar 00000000000000use clap::{Arg, Command}; use clap_markdown::{help_markdown_command_custom, MarkdownOptions}; use pretty_assertions::assert_eq; /// Test behavior for an app that defines a: /// /// * `name` /// * `display_name` /// /// but no custom `bin_name`. #[test] fn test_title_behavior_for_name_and_display_name_app() { let mut app = Command::new("my-program-name") // Note: Intentionally not setting custom bin name. // .bin_name("my-program-bin-name") .display_name("my-program-display-name") .version("1.2.3") .about("This program does things.") .arg(Arg::new("foo").short('f')); let () = app.build(); //------------------------------------------------------------------- // Test the native behavior of `clap`, in terms of whether it prefers // the `name`, `bin_name`, and `display_name` properties are used. //------------------------------------------------------------------- assert_eq!( app.render_long_help().to_string(), "\ This program does things. Usage: my-program-name [OPTIONS] Options: -f -h, --help Print help -V, --version Print version " ); //------------------------------------------------------- // Test how clap-markdown handles the various name fields //------------------------------------------------------- assert_eq!( help_markdown_command_custom( &app, &MarkdownOptions::new().show_footer(false) ), "\ # Command-Line Help for `my-program-display-name` This document contains the help content for the `my-program-display-name` command-line program. **Command Overview:** * [`my-program-display-name`↴](#my-program-display-name) ## `my-program-display-name` This program does things. **Usage:** `my-program-name [OPTIONS]` ###### **Options:** * `-f ` * `-h`, `--help` — Print help * `-V`, `--version` — Print version " ); } /// Test behavior for an app that defines a: /// /// * `name` /// * `bin_name` /// * `display_name` #[test] fn test_title_behavior_for_name_bin_name_and_display_name_app() { let mut app = Command::new("my-program-name") .bin_name("my-program-bin-name") .display_name("my-program-display-name") .version("1.2.3") .about("This program does things.") .arg(Arg::new("foo").short('f')); let () = app.build(); //------------------------------------------------------------------- // Test the native behavior of `clap`, in terms of whether it prefers // the `name`, `bin_name`, and `display_name` properties are used. //------------------------------------------------------------------- assert_eq!( app.render_long_help().to_string(), "\ This program does things. Usage: my-program-bin-name [OPTIONS] Options: -f -h, --help Print help -V, --version Print version " ); //------------------------------------------------------- // Test how clap-markdown handles the various name fields //------------------------------------------------------- assert_eq!( help_markdown_command_custom( &app, &MarkdownOptions::new().show_footer(false) ), "\ # Command-Line Help for `my-program-display-name` This document contains the help content for the `my-program-display-name` command-line program. **Command Overview:** * [`my-program-display-name`↴](#my-program-display-name) ## `my-program-display-name` This program does things. **Usage:** `my-program-bin-name [OPTIONS]` ###### **Options:** * `-f ` * `-h`, `--help` — Print help * `-V`, `--version` — Print version " ); }