From e8647d5b6a5d4b8ae45016cf414eeb11ef623530 Mon Sep 17 00:00:00 2001 From: Sondre Nilsen Date: Wed, 15 Dec 2021 13:47:25 +0100 Subject: [PATCH 01/11] feat(man): Create clap_man to generate manpages --- Cargo.toml | 1 + clap_generate/Cargo.toml | 1 - clap_man/CONTRIBUTING.md | 7 ++ clap_man/Cargo.toml | 39 ++++++ clap_man/LICENSE-APACHE | 201 +++++++++++++++++++++++++++++++ clap_man/LICENSE-MIT | 21 ++++ clap_man/README.md | 20 +++ clap_man/examples/man-builder.rs | 39 ++++++ clap_man/examples/man.rs | 30 +++++ clap_man/src/lib.rs | 105 ++++++++++++++++ clap_man/src/man.rs | 62 ++++++++++ clap_man/src/render.rs | 195 ++++++++++++++++++++++++++++++ clap_man/tests/generate.rs | 29 +++++ src/build/app/mod.rs | 30 +++++ 14 files changed, 779 insertions(+), 1 deletion(-) create mode 100644 clap_man/CONTRIBUTING.md create mode 100644 clap_man/Cargo.toml create mode 100644 clap_man/LICENSE-APACHE create mode 100644 clap_man/LICENSE-MIT create mode 100644 clap_man/README.md create mode 100644 clap_man/examples/man-builder.rs create mode 100644 clap_man/examples/man.rs create mode 100644 clap_man/src/lib.rs create mode 100644 clap_man/src/man.rs create mode 100644 clap_man/src/render.rs create mode 100644 clap_man/tests/generate.rs diff --git a/Cargo.toml b/Cargo.toml index bc08fa36e0e..917fc6bcc2b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -5,6 +5,7 @@ members = [ "clap_complete_fig", "clap_generate", "clap_generate_fig", + "clap_man", ] [package] diff --git a/clap_generate/Cargo.toml b/clap_generate/Cargo.toml index 28c5534fb52..c6e68989aa1 100644 --- a/clap_generate/Cargo.toml +++ b/clap_generate/Cargo.toml @@ -16,7 +16,6 @@ keywords = [ "cli", "generate", "completion", - "manpage", ] categories = ["command-line-interface"] license = "MIT OR Apache-2.0" diff --git a/clap_man/CONTRIBUTING.md b/clap_man/CONTRIBUTING.md new file mode 100644 index 00000000000..fb6d976da01 --- /dev/null +++ b/clap_man/CONTRIBUTING.md @@ -0,0 +1,7 @@ +# How to Contribute + +See the [clap-wide CONTRIBUTING.md](../CONTRIBUTING.md). This will contain `clap_generate` specific notes. + +### Scope + +`clap_man` contains the generator for creating manpages. diff --git a/clap_man/Cargo.toml b/clap_man/Cargo.toml new file mode 100644 index 00000000000..beef77b260c --- /dev/null +++ b/clap_man/Cargo.toml @@ -0,0 +1,39 @@ +[package] +name = "clap_man" +version = "3.0.0-rc.4" +edition = "2018" +include = [ + "src/**/*", + "Cargo.toml", + "LICENSE-*", + "README.md" +] +description = "A generator library used with clap for manpages" +repository = "https://github.com/clap-rs/clap/tree/master/clap_generate" +documentation = "https://docs.rs/clap_generate" +keywords = [ + "clap", + "cli", + "generate", + "manpage", +] +categories = ["command-line-interface"] +license = "MIT OR Apache-2.0" +readme = "README.md" + +[lib] +bench = false + +[dependencies] +clap = { path = "../", version = "=3.0.0-rc.4", default-features = false, features = ["std"] } + +[dev-dependencies] +pretty_assertions = "1.0" +clap = { path = "../", version = "=3.0.0-rc.4", default-features = false, features = ["std", "derive"] } + +[features] +default = [] +debug = ["clap/debug"] + +[package.metadata.docs.rs] +targets = ["x86_64-unknown-linux-gnu"] diff --git a/clap_man/LICENSE-APACHE b/clap_man/LICENSE-APACHE new file mode 100644 index 00000000000..261eeb9e9f8 --- /dev/null +++ b/clap_man/LICENSE-APACHE @@ -0,0 +1,201 @@ + 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 + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/clap_man/LICENSE-MIT b/clap_man/LICENSE-MIT new file mode 100644 index 00000000000..5acedf04122 --- /dev/null +++ b/clap_man/LICENSE-MIT @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2015-2016 Kevin B. Knapp + +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. diff --git a/clap_man/README.md b/clap_man/README.md new file mode 100644 index 00000000000..031a63ac1b5 --- /dev/null +++ b/clap_man/README.md @@ -0,0 +1,20 @@ + +# clap_man + +> **Manpage generation for `clap`** + +[![Crates.io](https://img.shields.io/crates/v/clap_man?style=flat-square)](https://crates.io/crates/clap_man) +[![Crates.io](https://img.shields.io/crates/d/clap_man?style=flat-square)](https://crates.io/crates/clap_man) +[![License](https://img.shields.io/badge/license-Apache%202.0-blue?style=flat-square)](https://github.com/clap-rs/clap/blob/master/LICENSE-APACHE) +[![License](https://img.shields.io/badge/license-MIT-blue?style=flat-square)](https://github.com/clap-rs/clap/blob/master/LICENSE-MIT) + +Dual-licensed under [Apache 2.0](LICENSE-APACHE) or [MIT](LICENSE-MIT). + +1. [About](#about) +2. [API Reference](https://docs.rs/clap_man) +3. [Questions & Discussions](https://github.com/clap-rs/clap/discussions) +4. [CONTRIBUTING](CONTRIBUTING.md) +5. [Sponsors](../README.md#sponsors) + +## About + diff --git a/clap_man/examples/man-builder.rs b/clap_man/examples/man-builder.rs new file mode 100644 index 00000000000..979e9033522 --- /dev/null +++ b/clap_man/examples/man-builder.rs @@ -0,0 +1,39 @@ +use clap::{arg, App}; +use clap_man::Man; +use std::io; + +// Run this example as `cargo run --example man-builder | man -l -`. + +fn main() { + let mut app = App::new("myapp") + .version("1.0") + .author("Kevin K. ") + .about("Does awesome things") + .long_about("With a longer description to help clarify some things.") + .subcommand_help_heading("Commands") + .arg( + arg!(-c --config "Sets a custom config file") + .long_help("Some more text about how to set a custom config file") + .required(false) + .takes_value(true), + ) + .arg(arg!([output] "Sets an optional output file").index(1)) + .arg(arg!(-d --debug ... "Turn debugging information on")) + .subcommand( + App::new("test") + .about("does testing things") + .arg(arg!(-l --list "Lists test values")), + ); + + Man::new() + .section(1) + .manual("GNU") + .custom_section( + "Reference", + vec![ + "For more information about the config file syntax, look up the INI format.", + "To see the debug information, visit our website on GitHub.", + ], + ) + .render(&mut app, &mut io::stdout()); +} diff --git a/clap_man/examples/man.rs b/clap_man/examples/man.rs new file mode 100644 index 00000000000..8ac0e57c10f --- /dev/null +++ b/clap_man/examples/man.rs @@ -0,0 +1,30 @@ +use clap::{arg, App}; +use clap_man::generate_manpage; +use std::io; + +// Run this example as `cargo run --example man | man -l -`. + +fn main() { + let mut app = App::new("myapp") + .version("1.0") + .author("Kevin K. :Ola Nordmann ") + .about("Does awesome things") + .long_about("With a longer description to help clarify some things.") + .after_help("This is an extra section added to the end of the manpage.") + .after_long_help("With even more text added.") + .arg( + arg!(-c --config "Sets a custom config file") + .long_help("Some more text about how to set a custom config file") + .required(false) + .takes_value(true), + ) + .arg(arg!([output] "Sets an optional output file").index(1)) + .arg(arg!(-d --debug ... "Turn debugging information on")) + .subcommand( + App::new("test") + .about("does testing things") + .arg(arg!(-l --list "Lists test values")), + ); + + generate_manpage(&mut app, &mut io::stdout()); +} diff --git a/clap_man/src/lib.rs b/clap_man/src/lib.rs new file mode 100644 index 00000000000..c44c5d12a0b --- /dev/null +++ b/clap_man/src/lib.rs @@ -0,0 +1,105 @@ +#![doc(html_logo_url = "https://raw.githubusercontent.com/clap-rs/clap/master/assets/clap.png")] +#![doc = include_str!("../README.md")] +#![warn(missing_docs, trivial_casts, unused_allocation, trivial_numeric_casts)] +#![forbid(unsafe_code)] + +mod man; +mod render; + +use std::io::Write; + +/// Man page generator +#[derive(Debug, Clone)] +pub struct Man { + section: Option, + manual: Option, + sections: Vec<(String, Vec)>, +} + +impl Default for Man { + fn default() -> Self { + Self::new() + } +} + +/// Generate manpage for your application using sane defaults. +pub fn generate_manpage<'a>(app: &mut clap::App<'a>, buf: &mut dyn Write) { + let man = Man::new().section(1).manual("General Commands Manual"); + man.render(app, buf); +} + +impl Man { + /// Create a new builder for man pages. + pub fn new() -> Self { + Man { + section: None, + manual: None, + sections: Vec::new(), + } + } + + /// Add section for your man page, the most common being 1 for programs. + /// + /// 1. Executable programs or shell commands + /// 2. System calls (functions provided by the kernel) + /// 3. Library calls (functions within program libraries) + /// 4. Special files (usually found in /dev) + /// 5. File formats and conventions, e.g. /etc/passwd + /// 6. Games + /// 7. Miscellaneous (including macro packages and conventions), e.g. man(7), groff(7) + /// 8. System administration commands (usually only for root) + /// 9. Kernel routines [Non standard] + pub fn section(mut self, section: i8) -> Self { + self.section = Some(section); + self + } + + /// Set manual for where the document comes from, the most common being + /// `General Commands Manual`. + pub fn manual(mut self, manual: impl Into) -> Self { + self.manual = Some(manual.into()); + self + } + + /// Add a custom section to the man pages. + pub fn custom_section( + mut self, + title: impl Into, + body: Vec>, + ) -> Self { + self.sections + .push((title.into(), body.into_iter().map(|s| s.into()).collect())); + self + } + + /// Write the manpage to a buffer. + pub fn render(self, app: &mut clap::App, buf: &mut dyn std::io::Write) { + app._build_all(); + render::header(app, self.get_section(), self.manual.clone(), buf); + + // Set sentence_space_size to 0 to prevent extra space between sentences separated + // by a newline the alternative is to add \& at the end of the line + writeln!(buf, ".ss \\n[.ss] 0").unwrap(); + // Disable hyphenation + writeln!(buf, ".nh").unwrap(); + // Disable justification (adjust text to the left margin only) + writeln!(buf, ".ad l").unwrap(); + + render::about(app, buf); + render::description(app, buf); + render::synopsis(app, buf); + + render::options(app, buf); + render::subcommands(app, self.get_section(), buf); + + render::after_help(app, buf); + render::custom_sections(self.sections, buf); + + render::version(app, buf); + render::authors(app, buf); + } + + fn get_section(&self) -> i8 { + self.section.unwrap_or(1) + } +} diff --git a/clap_man/src/man.rs b/clap_man/src/man.rs new file mode 100644 index 00000000000..9d08018bbdc --- /dev/null +++ b/clap_man/src/man.rs @@ -0,0 +1,62 @@ +pub(crate) fn bold(input: &str) -> String { + format!(r"\fB{}\fR", input) +} + +pub(crate) fn italic(input: &str) -> String { + format!(r"\fI{}\fR", input) +} + +pub(crate) fn escape(str: &str) -> String { + str.replace("-", r"\-") +} + +pub(crate) fn indent(level: i8, input: &str) -> String { + format!(".RS {}\n{}\n.RE", level, input) +} + +pub(crate) fn section_title(title: &str) -> String { + format!(".SH \"{}\"\n", title.to_uppercase()) +} + +pub(crate) fn document_title( + app: &clap::App, + section: i8, + manual: Option, + date: Option, +) -> String { + let version = match app.get_version() { + Some(version) => format!(r#" "{} v{}""#, app.get_name(), version), + None => r#" """#.to_string(), + }; + + let manual = match manual { + Some(manual) => format!(r#" "{}""#, manual), + None => r#" """#.to_string(), + }; + + let date = match date { + Some(date) => format!(r#" "{}""#, date), + None => r#" """#.to_string(), + }; + + let name = if let Some(name) = app.get_bin_name() { + name + } else { + app.get_name() + }; + + format!(".TH {} {} {} {} {}\n", name, section, date, version, manual) +} + +pub(crate) fn list(title: &str, list: Vec>) -> String { + let mut res = String::new(); + + res.push_str(§ion_title(&escape(title))); + res.push_str(".P\n.RS 2\n.nf\n"); + for item in list { + res.push_str(&escape(&item.into())); + res.push('\n'); + } + + res +} diff --git a/clap_man/src/render.rs b/clap_man/src/render.rs new file mode 100644 index 00000000000..e90148e7461 --- /dev/null +++ b/clap_man/src/render.rs @@ -0,0 +1,195 @@ +use std::io::Write; + +use crate::man::{bold, document_title, escape, indent, italic, list, section_title}; + +use clap::ArgSettings; + +fn app_name(app: &clap::App) -> String { + if let Some(name) = app.get_bin_name() { + escape(name) + } else { + escape(app.get_name()) + } +} + +fn subcommand_heading(app: &clap::App) -> String { + match app.get_subommand_help_heading() { + Some(title) => escape(title), + None => "Subcommands".to_string(), + } +} + +pub(crate) fn header(app: &clap::App, section: i8, manual: Option, buf: &mut dyn Write) { + write!(buf, "{}", document_title(app, section, manual, None)).unwrap(); +} + +pub(crate) fn about(app: &clap::App, buf: &mut dyn Write) { + write!(buf, "{}", section_title("Name")).unwrap(); + write!(buf, "{}", bold(&app_name(app))).unwrap(); + + if let Some(about) = app.get_about() { + write!(buf, r" \- {}", escape(about)).unwrap(); + } + + writeln!(buf).unwrap(); +} + +pub(crate) fn description(app: &clap::App, buf: &mut dyn Write) { + if let Some(about) = app.get_long_about() { + writeln!(buf, "{}{}", section_title("Description"), escape(about)).unwrap(); + } +} + +pub(crate) fn synopsis(app: &clap::App, buf: &mut dyn Write) { + write!( + buf, + "{}{} ", + section_title("Synopsis"), + italic(&app_name(app)) + ) + .unwrap(); + + for opt in app.get_arguments() { + let options = match (opt.get_short(), opt.get_long()) { + (Some(short), Some(long)) => format!("[-{}|--{}]", short, long), + (Some(short), None) => format!("[-{}]", short), + (None, Some(long)) => format!("[--{}]", long), + (None, None) => "".to_string(), + }; + + write!(buf, "{} ", options).unwrap(); + } + + for arg in app.get_positionals() { + write!(buf, "{} ", format!("[{}]", arg.get_name())).unwrap(); + } + + if app.has_subcommands() { + write!(buf, "[{}]", subcommand_heading(app).to_lowercase()).unwrap(); + } + + writeln!(buf).unwrap(); +} + +// TODO: handle positional arguments in a different way? +pub(crate) fn options(app: &clap::App, buf: &mut dyn Write) { + let items: Vec<_> = app + .get_arguments() + .filter(|i| !i.is_set(ArgSettings::Hidden)) + .collect(); + + if items.is_empty() { + return; + } + + write!(buf, "{}", section_title("Options")).unwrap(); + for opt in items.iter().filter(|a| !a.is_positional()) { + let args = match (opt.get_short(), opt.get_long()) { + (Some(short), Some(long)) => format!("-{}, --{}", short, long), + (Some(short), None) => format!("-{}", short), + (None, Some(long)) => format!("--{}", long), + (None, None) => "".to_string(), + }; + + write!(buf, "{}", bold(&args)).unwrap(); + + if let Some(value) = &opt.get_value_names() { + write!(buf, " {}", italic(&value.join(" "))).unwrap(); + } + + writeln!(buf).unwrap(); + + if let Some(help) = opt.get_help() { + write!(buf, "{}", indent(4, help)).unwrap(); + } + + if let Some(help) = opt.get_long_help() { + write!(buf, "\n.sp\n.sp\n{}", indent(4, help)).unwrap(); + } + + writeln!(buf, "\n").unwrap(); + } + + for pos in items.iter().filter(|a| a.is_positional()) { + let required = pos.is_set(ArgSettings::Required); + let (rhs, lhs) = if required { ("<", ">") } else { ("[", "]") }; + let name = format!("{}{}{}", rhs, pos.get_name(), lhs); + + writeln!(buf, "{}", bold(&name)).unwrap(); + + if let Some(help) = pos.get_help() { + write!(buf, "{}", indent(4, help)).unwrap(); + } + + if let Some(help) = pos.get_long_help() { + write!(buf, "\n.sp\n.sp\n{}", indent(4, help)).unwrap(); + } + + writeln!(buf, "\n").unwrap(); + } +} + +pub(crate) fn subcommands(app: &clap::App, section: i8, buf: &mut dyn Write) { + let commands: Vec<_> = app.get_subcommands().collect(); + + if commands.is_empty() { + return; + } + + write!(buf, "{}", section_title(&subcommand_heading(app))).unwrap(); + for command in commands { + let name = format!("{}-{}", app_name(app), command.get_name()); + writeln!(buf, "{}({})", bold(&escape(&name)), section).unwrap(); + + if let Some(about) = command.get_about() { + writeln!(buf, ".br\n{}\n", about).unwrap(); + } + } +} + +pub(crate) fn authors(app: &clap::App, buf: &mut dyn Write) { + if let Some(authors) = app.get_author() { + let separator = ['\n', ':'].iter().find(|&&s| authors.contains(s)); + let authors = if let Some(sep) = separator { + authors.split(*sep).collect() + } else { + vec![authors] + }; + + let title = if authors.len() > 1 { + "Authors" + } else { + "Author" + }; + + write!(buf, "{}", list(title, authors)).unwrap(); + } +} + +pub(crate) fn version(app: &clap::App, buf: &mut dyn Write) { + if let Some(version) = app.get_version() { + write!(buf, "{}", section_title("Version")).unwrap(); + writeln!(buf, "v{}", escape(version)).unwrap(); + } +} + +pub(crate) fn custom_sections(sections: Vec<(String, Vec)>, buf: &mut dyn Write) { + for (title, body) in sections { + write!(buf, "{}", section_title(&title)).unwrap(); + + for paragraph in body { + writeln!(buf, ".sp\n{}", escape(¶graph)).unwrap(); + } + } +} + +pub(crate) fn after_help(app: &clap::App, buf: &mut dyn Write) { + if let Some(help) = app.get_after_help() { + write!(buf, "{}", section_title("Extra")).unwrap(); + writeln!(buf, ".sp\n{}", escape(help)).unwrap(); + + if let Some(long) = app.get_after_long_help() { + writeln!(buf, ".sp\n{}", escape(long)).unwrap(); + } + } +} diff --git a/clap_man/tests/generate.rs b/clap_man/tests/generate.rs new file mode 100644 index 00000000000..89bf385db7e --- /dev/null +++ b/clap_man/tests/generate.rs @@ -0,0 +1,29 @@ +use clap::{arg, App}; +use clap_man::generate_manpage; +use std::io; + +#[test] +fn render_manpage() { + let mut app = App::new("myapp") + .version("1.0") + .author("Kevin K. ") + .about("Does awesome things") + .long_about("With a longer description to help clarify some things.") + .after_help("This is an extra section added to the end of the manpage.") + .after_long_help("With even more text added.") + .arg( + arg!(-c --config "Sets a custom config file") + .long_help("Some more text about how to set a custom config file") + .required(false) + .takes_value(true), + ) + .arg(arg!([output] "Sets an optional output file").index(1)) + .arg(arg!(-d --debug ... "Turn debugging information on")) + .subcommand( + App::new("test") + .about("does testing things") + .arg(arg!(-l --list "Lists test values")), + ); + + generate_manpage(&mut app, &mut io::sink()); +} diff --git a/src/build/app/mod.rs b/src/build/app/mod.rs index 366e18307a7..9cda3d67c28 100644 --- a/src/build/app/mod.rs +++ b/src/build/app/mod.rs @@ -2106,6 +2106,18 @@ impl<'help> App<'help> { &self.name } + /// Get the version of the app. + #[inline] + pub fn get_version(&self) -> Option<&'help str> { + self.version + } + + /// Get the authors of the app. + #[inline] + pub fn get_author(&self) -> Option<&'help str> { + self.author + } + /// Get the short flag of the subcommand. #[inline] pub fn get_short_flag(&self) -> Option { @@ -2235,6 +2247,24 @@ impl<'help> App<'help> { !self.subcommands.is_empty() } + /// Returns the help heading for listing subcommands. + #[inline] + pub fn get_subommand_help_heading(&self) -> Option<&str> { + self.subcommand_heading + } + + /// Returns the help heading for listing subcommands. + #[inline] + pub fn get_after_help(&self) -> Option<&str> { + self.after_help + } + + /// Returns the help heading for listing subcommands. + #[inline] + pub fn get_after_long_help(&self) -> Option<&str> { + self.after_long_help + } + /// Find subcommand such that its name or one of aliases equals `name`. /// /// This does not recurse through subcommands of subcommands. From 66964d165bf4cc91cdef2f51a49e0651b4cd15c7 Mon Sep 17 00:00:00 2001 From: Sondre Nilsen Date: Wed, 15 Dec 2021 17:17:24 +0100 Subject: [PATCH 02/11] fix: Update metadata, create Secion enum --- clap_man/CONTRIBUTING.md | 3 -- clap_man/Cargo.toml | 10 +++--- clap_man/src/lib.rs | 67 ++++++++++++++++++++++++++++++---------- 3 files changed, 55 insertions(+), 25 deletions(-) diff --git a/clap_man/CONTRIBUTING.md b/clap_man/CONTRIBUTING.md index fb6d976da01..36eecb12114 100644 --- a/clap_man/CONTRIBUTING.md +++ b/clap_man/CONTRIBUTING.md @@ -2,6 +2,3 @@ See the [clap-wide CONTRIBUTING.md](../CONTRIBUTING.md). This will contain `clap_generate` specific notes. -### Scope - -`clap_man` contains the generator for creating manpages. diff --git a/clap_man/Cargo.toml b/clap_man/Cargo.toml index beef77b260c..6ca4e3f2e29 100644 --- a/clap_man/Cargo.toml +++ b/clap_man/Cargo.toml @@ -8,9 +8,9 @@ include = [ "LICENSE-*", "README.md" ] -description = "A generator library used with clap for manpages" -repository = "https://github.com/clap-rs/clap/tree/master/clap_generate" -documentation = "https://docs.rs/clap_generate" +description = "A manpage generator for clap" +repository = "https://github.com/clap-rs/clap/tree/master/clap_man" +documentation = "https://docs.rs/clap_man" keywords = [ "clap", "cli", @@ -25,11 +25,11 @@ readme = "README.md" bench = false [dependencies] -clap = { path = "../", version = "=3.0.0-rc.4", default-features = false, features = ["std"] } +clap = { path = "../", version = "=3.0.0-rc.4", default-features = false, features = ["std", "env"] } [dev-dependencies] pretty_assertions = "1.0" -clap = { path = "../", version = "=3.0.0-rc.4", default-features = false, features = ["std", "derive"] } +clap = { path = "../", version = "=3.0.0-rc.4", default-features = false, features = ["std"] } [features] default = [] diff --git a/clap_man/src/lib.rs b/clap_man/src/lib.rs index c44c5d12a0b..e185b552555 100644 --- a/clap_man/src/lib.rs +++ b/clap_man/src/lib.rs @@ -8,23 +8,66 @@ mod render; use std::io::Write; +/// Manpage sections, the most common is [`ManpageSection::Executable`]. +#[derive(Debug, Clone, Copy)] +pub enum Section { + /// Executable programs or shell commands + Executable, + /// System calls (functions provided by the kernel) + SystemCalls, + /// Library calls (functions within program libraries) + LibraryCalls, + /// Special files (usually found in /dev) + SpecialFiles, + /// File formats and conventions, e.g. /etc/passwd + FileFormats, + /// Games + Games, + /// Miscellaneous (including macro packages and conventions), e.g. man(7), groff(7) + Miscellaneous, + /// System administration commands (usually only for root) + SystemAdministrationCommands, + /// Kernel routines [Non standard] + KernelRoutines, +} + +impl Section { + fn value(&self) -> i8 { + match self { + Section::Executable => 1, + Section::SystemCalls => 2, + Section::LibraryCalls => 3, + Section::SpecialFiles => 4, + Section::FileFormats => 5, + Section::Games => 6, + Section::Miscellaneous => 7, + Section::SystemAdministrationCommands => 8, + Section::KernelRoutines => 9, + } + } +} + /// Man page generator #[derive(Debug, Clone)] pub struct Man { - section: Option, + section: Option
, manual: Option, sections: Vec<(String, Vec)>, } impl Default for Man { fn default() -> Self { - Self::new() + Self { + section: Some(Section::Executable), + manual: Some("General Commands Manual".to_string()), + sections: Vec::new(), + } } } -/// Generate manpage for your application using sane defaults. +/// Generate manpage for your application using the most common default values. pub fn generate_manpage<'a>(app: &mut clap::App<'a>, buf: &mut dyn Write) { - let man = Man::new().section(1).manual("General Commands Manual"); + let man = Man::default(); man.render(app, buf); } @@ -38,18 +81,8 @@ impl Man { } } - /// Add section for your man page, the most common being 1 for programs. - /// - /// 1. Executable programs or shell commands - /// 2. System calls (functions provided by the kernel) - /// 3. Library calls (functions within program libraries) - /// 4. Special files (usually found in /dev) - /// 5. File formats and conventions, e.g. /etc/passwd - /// 6. Games - /// 7. Miscellaneous (including macro packages and conventions), e.g. man(7), groff(7) - /// 8. System administration commands (usually only for root) - /// 9. Kernel routines [Non standard] - pub fn section(mut self, section: i8) -> Self { + /// Add section for your man page, see [`ManpageSection`]. + pub fn section(mut self, section: Section) -> Self { self.section = Some(section); self } @@ -100,6 +133,6 @@ impl Man { } fn get_section(&self) -> i8 { - self.section.unwrap_or(1) + self.section.unwrap_or(Section::Executable).value() } } From 2e1b4691962328caa82351639c69ab7668bbc044 Mon Sep 17 00:00:00 2001 From: Sondre Nilsen Date: Wed, 15 Dec 2021 17:18:13 +0100 Subject: [PATCH 03/11] feat: Show environment variable and defaults --- clap_man/examples/man-builder.rs | 5 +- clap_man/examples/man.rs | 8 +-- clap_man/src/render.rs | 87 +++++++++++++++++++++++--------- 3 files changed, 69 insertions(+), 31 deletions(-) diff --git a/clap_man/examples/man-builder.rs b/clap_man/examples/man-builder.rs index 979e9033522..681acf744a0 100644 --- a/clap_man/examples/man-builder.rs +++ b/clap_man/examples/man-builder.rs @@ -1,5 +1,5 @@ use clap::{arg, App}; -use clap_man::Man; +use clap_man::{Man, Section}; use std::io; // Run this example as `cargo run --example man-builder | man -l -`. @@ -9,7 +9,6 @@ fn main() { .version("1.0") .author("Kevin K. ") .about("Does awesome things") - .long_about("With a longer description to help clarify some things.") .subcommand_help_heading("Commands") .arg( arg!(-c --config "Sets a custom config file") @@ -26,7 +25,7 @@ fn main() { ); Man::new() - .section(1) + .section(Section::Executable) .manual("GNU") .custom_section( "Reference", diff --git a/clap_man/examples/man.rs b/clap_man/examples/man.rs index 8ac0e57c10f..36dab01b4e6 100644 --- a/clap_man/examples/man.rs +++ b/clap_man/examples/man.rs @@ -16,10 +16,12 @@ fn main() { arg!(-c --config "Sets a custom config file") .long_help("Some more text about how to set a custom config file") .required(false) - .takes_value(true), + .takes_value(true) + .default_value("config.toml") + .env("CONFIG_FILE"), ) - .arg(arg!([output] "Sets an optional output file").index(1)) - .arg(arg!(-d --debug ... "Turn debugging information on")) + .arg(arg!([output] "Sets an output file").default_value("result.txt")) + .arg(arg!(-d --debug ... "Turn debugging information on").env("DEBUG_ON")) .subcommand( App::new("test") .about("does testing things") diff --git a/clap_man/src/render.rs b/clap_man/src/render.rs index e90148e7461..de0a698ec20 100644 --- a/clap_man/src/render.rs +++ b/clap_man/src/render.rs @@ -4,21 +4,6 @@ use crate::man::{bold, document_title, escape, indent, italic, list, section_tit use clap::ArgSettings; -fn app_name(app: &clap::App) -> String { - if let Some(name) = app.get_bin_name() { - escape(name) - } else { - escape(app.get_name()) - } -} - -fn subcommand_heading(app: &clap::App) -> String { - match app.get_subommand_help_heading() { - Some(title) => escape(title), - None => "Subcommands".to_string(), - } -} - pub(crate) fn header(app: &clap::App, section: i8, manual: Option, buf: &mut dyn Write) { write!(buf, "{}", document_title(app, section, manual, None)).unwrap(); } @@ -27,7 +12,7 @@ pub(crate) fn about(app: &clap::App, buf: &mut dyn Write) { write!(buf, "{}", section_title("Name")).unwrap(); write!(buf, "{}", bold(&app_name(app))).unwrap(); - if let Some(about) = app.get_about() { + if let Some(about) = app.get_about().or_else(|| app.get_long_about()) { write!(buf, r" \- {}", escape(about)).unwrap(); } @@ -35,7 +20,7 @@ pub(crate) fn about(app: &clap::App, buf: &mut dyn Write) { } pub(crate) fn description(app: &clap::App, buf: &mut dyn Write) { - if let Some(about) = app.get_long_about() { + if let Some(about) = app.get_long_about().or_else(|| app.get_about()) { writeln!(buf, "{}{}", section_title("Description"), escape(about)).unwrap(); } } @@ -71,7 +56,6 @@ pub(crate) fn synopsis(app: &clap::App, buf: &mut dyn Write) { writeln!(buf).unwrap(); } -// TODO: handle positional arguments in a different way? pub(crate) fn options(app: &clap::App, buf: &mut dyn Write) { let items: Vec<_> = app .get_arguments() @@ -97,14 +81,18 @@ pub(crate) fn options(app: &clap::App, buf: &mut dyn Write) { write!(buf, " {}", italic(&value.join(" "))).unwrap(); } + if let Some(defs) = option_default_values(opt) { + write!(buf, " {}", defs).unwrap(); + } + writeln!(buf).unwrap(); - if let Some(help) = opt.get_help() { + if let Some(help) = opt.get_long_help().or_else(|| opt.get_help()) { write!(buf, "{}", indent(4, help)).unwrap(); } - if let Some(help) = opt.get_long_help() { - write!(buf, "\n.sp\n.sp\n{}", indent(4, help)).unwrap(); + if let Some(env) = option_environment(opt) { + writeln!(buf, "{}", indent(4, &env)).unwrap(); } writeln!(buf, "\n").unwrap(); @@ -115,14 +103,20 @@ pub(crate) fn options(app: &clap::App, buf: &mut dyn Write) { let (rhs, lhs) = if required { ("<", ">") } else { ("[", "]") }; let name = format!("{}{}{}", rhs, pos.get_name(), lhs); - writeln!(buf, "{}", bold(&name)).unwrap(); + write!(buf, "{}", bold(&name)).unwrap(); - if let Some(help) = pos.get_help() { + if let Some(defs) = option_default_values(pos) { + write!(buf, " {}", defs).unwrap(); + } + + writeln!(buf).unwrap(); + + if let Some(help) = pos.get_long_help().or_else(|| pos.get_help()) { write!(buf, "{}", indent(4, help)).unwrap(); } - if let Some(help) = pos.get_long_help() { - write!(buf, "\n.sp\n.sp\n{}", indent(4, help)).unwrap(); + if let Some(env) = option_environment(pos) { + writeln!(buf, "{}", indent(4, &env)).unwrap(); } writeln!(buf, "\n").unwrap(); @@ -193,3 +187,46 @@ pub(crate) fn after_help(app: &clap::App, buf: &mut dyn Write) { } } } + +fn option_environment(opt: &clap::Arg) -> Option { + if let Some(env) = opt.get_env() { + let env = bold(&escape(&env.to_string_lossy())); + let text = format!( + "May also be specified with the {} environment variable. ", + env + ); + return Some(format!("\n.sp\n{}", &text)); + } + + None +} + +fn option_default_values(opt: &clap::Arg) -> Option { + if !opt.get_default_values().is_empty() { + let values = opt + .get_default_values() + .iter() + .map(|s| s.to_string_lossy()) + .collect::>() + .join(","); + + return Some(format!("[default: {}]", values)); + } + + None +} + +fn app_name(app: &clap::App) -> String { + if let Some(name) = app.get_bin_name() { + escape(name) + } else { + escape(app.get_name()) + } +} + +fn subcommand_heading(app: &clap::App) -> String { + match app.get_subommand_help_heading() { + Some(title) => escape(title), + None => "Subcommands".to_string(), + } +} From 504cf843dc27713fe69fd0eb7789a3c509782b42 Mon Sep 17 00:00:00 2001 From: Sondre Nilsen Date: Wed, 15 Dec 2021 17:21:18 +0100 Subject: [PATCH 04/11] chore: Update contributing and sponsors link --- clap_man/Cargo.toml | 5 +++++ clap_man/README.md | 4 ++-- 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/clap_man/Cargo.toml b/clap_man/Cargo.toml index 6ca4e3f2e29..94bedc01027 100644 --- a/clap_man/Cargo.toml +++ b/clap_man/Cargo.toml @@ -21,6 +21,11 @@ categories = ["command-line-interface"] license = "MIT OR Apache-2.0" readme = "README.md" +[package.metadata.release] +pre-release-replacements = [ + {file="README.md", search="github.com/clap-rs/clap/blob/[^/]+/", replace="github.com/clap-rs/clap/blob/{{tag_name}}/", exactly=4, prerelease = true}, +] + [lib] bench = false diff --git a/clap_man/README.md b/clap_man/README.md index 031a63ac1b5..25e73110e2b 100644 --- a/clap_man/README.md +++ b/clap_man/README.md @@ -13,8 +13,8 @@ Dual-licensed under [Apache 2.0](LICENSE-APACHE) or [MIT](LICENSE-MIT). 1. [About](#about) 2. [API Reference](https://docs.rs/clap_man) 3. [Questions & Discussions](https://github.com/clap-rs/clap/discussions) -4. [CONTRIBUTING](CONTRIBUTING.md) -5. [Sponsors](../README.md#sponsors) +4. [CONTRIBUTING](https://github.com/clap-rs/clap/blob/v3.0.0-rc.4/clap_generate/CCONTRIBUTING.md) +5. [Sponsors](https://github.com/clap-rs/clap/blob/v3.0.0-rc.4/README.md#sponsors) ## About From 9605d5c4e3148d91034446e902b31691a52eb064 Mon Sep 17 00:00:00 2001 From: Sondre Nilsen Date: Wed, 15 Dec 2021 17:24:47 +0100 Subject: [PATCH 05/11] fix: Wrong name for section enum --- clap_man/src/lib.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/clap_man/src/lib.rs b/clap_man/src/lib.rs index e185b552555..5bb734db602 100644 --- a/clap_man/src/lib.rs +++ b/clap_man/src/lib.rs @@ -8,7 +8,7 @@ mod render; use std::io::Write; -/// Manpage sections, the most common is [`ManpageSection::Executable`]. +/// Manpage sections, the most common is [`Section::Executable`]. #[derive(Debug, Clone, Copy)] pub enum Section { /// Executable programs or shell commands @@ -81,7 +81,7 @@ impl Man { } } - /// Add section for your man page, see [`ManpageSection`]. + /// Add section for your man page, see [`Section`]. pub fn section(mut self, section: Section) -> Self { self.section = Some(section); self From ad9db15e7f4f85363a2d00062e0c012012ed6279 Mon Sep 17 00:00:00 2001 From: Sondre Nilsen Date: Fri, 17 Dec 2021 17:21:44 +0100 Subject: [PATCH 06/11] refactor(man): Use roff-rs crate to render manpage --- Cargo.toml | 3 + clap_man/Cargo.toml | 3 +- clap_man/examples/man-builder.rs | 12 +- clap_man/examples/man.rs | 6 +- clap_man/src/lib.rs | 129 ++++++++--------- clap_man/src/man.rs | 62 --------- clap_man/src/render.rs | 230 +++++++++++++------------------ 7 files changed, 168 insertions(+), 277 deletions(-) delete mode 100644 clap_man/src/man.rs diff --git a/Cargo.toml b/Cargo.toml index 917fc6bcc2b..e7efe198378 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -142,6 +142,9 @@ rustversion = "1" # Cutting out `filesystem` feature trycmd = { version = "0.9", default-features = false, features = ["color-auto", "diff", "examples"] } +[patch.crates-io] +roff = { git = "https://github.com/sondr3/roff-rs", branch = "updates" } + [[example]] name = "demo" required-features = ["derive"] diff --git a/clap_man/Cargo.toml b/clap_man/Cargo.toml index 94bedc01027..8affc4c18f1 100644 --- a/clap_man/Cargo.toml +++ b/clap_man/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "clap_man" -version = "3.0.0-rc.4" +version = "0.1.0" edition = "2018" include = [ "src/**/*", @@ -30,6 +30,7 @@ pre-release-replacements = [ bench = false [dependencies] +roff = "0.1.0" clap = { path = "../", version = "=3.0.0-rc.4", default-features = false, features = ["std", "env"] } [dev-dependencies] diff --git a/clap_man/examples/man-builder.rs b/clap_man/examples/man-builder.rs index 681acf744a0..3f97aae0040 100644 --- a/clap_man/examples/man-builder.rs +++ b/clap_man/examples/man-builder.rs @@ -1,5 +1,6 @@ use clap::{arg, App}; -use clap_man::{Man, Section}; +use clap_man::{roff::ManSection, Man}; +use roff::bold; use std::io; // Run this example as `cargo run --example man-builder | man -l -`. @@ -25,13 +26,14 @@ fn main() { ); Man::new() - .section(Section::Executable) + .section(ManSection::Executable) .manual("GNU") .custom_section( "Reference", - vec![ - "For more information about the config file syntax, look up the INI format.", - "To see the debug information, visit our website on GitHub.", + &[ + "For more information about the config file syntax, look up the INI format. ", + "To see the debug information, visit our website on ", + &bold("GitHub"), ], ) .render(&mut app, &mut io::stdout()); diff --git a/clap_man/examples/man.rs b/clap_man/examples/man.rs index 36dab01b4e6..90802fd07f0 100644 --- a/clap_man/examples/man.rs +++ b/clap_man/examples/man.rs @@ -9,7 +9,11 @@ fn main() { .version("1.0") .author("Kevin K. :Ola Nordmann ") .about("Does awesome things") - .long_about("With a longer description to help clarify some things.") + .long_about( + "With a longer description to help clarify some things. + + And a few newlines.", + ) .after_help("This is an extra section added to the end of the manpage.") .after_long_help("With even more text added.") .arg( diff --git a/clap_man/src/lib.rs b/clap_man/src/lib.rs index 5bb734db602..bd29dbd0bb0 100644 --- a/clap_man/src/lib.rs +++ b/clap_man/src/lib.rs @@ -3,62 +3,25 @@ #![warn(missing_docs, trivial_casts, unused_allocation, trivial_numeric_casts)] #![forbid(unsafe_code)] -mod man; mod render; -use std::io::Write; - -/// Manpage sections, the most common is [`Section::Executable`]. -#[derive(Debug, Clone, Copy)] -pub enum Section { - /// Executable programs or shell commands - Executable, - /// System calls (functions provided by the kernel) - SystemCalls, - /// Library calls (functions within program libraries) - LibraryCalls, - /// Special files (usually found in /dev) - SpecialFiles, - /// File formats and conventions, e.g. /etc/passwd - FileFormats, - /// Games - Games, - /// Miscellaneous (including macro packages and conventions), e.g. man(7), groff(7) - Miscellaneous, - /// System administration commands (usually only for root) - SystemAdministrationCommands, - /// Kernel routines [Non standard] - KernelRoutines, -} +pub use roff; -impl Section { - fn value(&self) -> i8 { - match self { - Section::Executable => 1, - Section::SystemCalls => 2, - Section::LibraryCalls => 3, - Section::SpecialFiles => 4, - Section::FileFormats => 5, - Section::Games => 6, - Section::Miscellaneous => 7, - Section::SystemAdministrationCommands => 8, - Section::KernelRoutines => 9, - } - } -} +use render::subcommand_heading; +use roff::{ManSection, Roff, Troffable}; +use std::io::Write; /// Man page generator -#[derive(Debug, Clone)] pub struct Man { - section: Option
, + section: Option, manual: Option, - sections: Vec<(String, Vec)>, + sections: Vec<(String, String)>, } impl Default for Man { fn default() -> Self { Self { - section: Some(Section::Executable), + section: Some(ManSection::Executable), manual: Some("General Commands Manual".to_string()), sections: Vec::new(), } @@ -82,7 +45,7 @@ impl Man { } /// Add section for your man page, see [`Section`]. - pub fn section(mut self, section: Section) -> Self { + pub fn section(mut self, section: ManSection) -> Self { self.section = Some(section); self } @@ -95,44 +58,68 @@ impl Man { } /// Add a custom section to the man pages. - pub fn custom_section( - mut self, - title: impl Into, - body: Vec>, - ) -> Self { - self.sections - .push((title.into(), body.into_iter().map(|s| s.into()).collect())); + pub fn custom_section<'a, I, C>(mut self, title: impl Into, content: I) -> Self + where + I: IntoIterator, + C: Troffable + 'a, + { + self.sections.push(( + title.into(), + content.into_iter().map(Troffable::render).collect(), + )); self } /// Write the manpage to a buffer. pub fn render(self, app: &mut clap::App, buf: &mut dyn std::io::Write) { app._build_all(); - render::header(app, self.get_section(), self.manual.clone(), buf); - // Set sentence_space_size to 0 to prevent extra space between sentences separated - // by a newline the alternative is to add \& at the end of the line - writeln!(buf, ".ss \\n[.ss] 0").unwrap(); - // Disable hyphenation - writeln!(buf, ".nh").unwrap(); - // Disable justification (adjust text to the left margin only) - writeln!(buf, ".ad l").unwrap(); + let mut page = Roff::new(app.get_name(), self.get_section()) + .section("Name", [&render::about(app)]) + .section("Synopsis", [&render::synopsis(app)]) + .section("Description", &render::description(app)); + + if app_has_arguments(app) { + page = page.section("Options", &render::options(app)); + } + + if app_has_subcommands(app) { + page = page.section( + &subcommand_heading(app), + &render::subcommands(app, self.get_section().value()), + ) + } - render::about(app, buf); - render::description(app, buf); - render::synopsis(app, buf); + if app.get_after_long_help().is_some() || app.get_after_help().is_some() { + page = page.section("Extra", &render::after_help(app)) + } - render::options(app, buf); - render::subcommands(app, self.get_section(), buf); + for (title, section) in self.sections { + page = page.section(&title, &[section]); + } + + if app.get_version().is_some() { + page = page.section("Version", &[render::version(app)]); + } - render::after_help(app, buf); - render::custom_sections(self.sections, buf); + if app.get_author().is_some() { + page = page.section("Author(s)", &[app.get_author().unwrap_or_default()]); + } - render::version(app, buf); - render::authors(app, buf); + buf.write_all(page.render().as_bytes()).unwrap(); } - fn get_section(&self) -> i8 { - self.section.unwrap_or(Section::Executable).value() + fn get_section(&self) -> ManSection { + self.section.unwrap_or(ManSection::Executable) } } + +fn app_has_arguments(app: &clap::App) -> bool { + app.get_arguments() + .any(|i| !i.is_set(clap::ArgSettings::Hidden)) +} + +fn app_has_subcommands(app: &clap::App) -> bool { + app.get_subcommands() + .any(|i| !i.is_set(clap::AppSettings::Hidden)) +} diff --git a/clap_man/src/man.rs b/clap_man/src/man.rs deleted file mode 100644 index 9d08018bbdc..00000000000 --- a/clap_man/src/man.rs +++ /dev/null @@ -1,62 +0,0 @@ -pub(crate) fn bold(input: &str) -> String { - format!(r"\fB{}\fR", input) -} - -pub(crate) fn italic(input: &str) -> String { - format!(r"\fI{}\fR", input) -} - -pub(crate) fn escape(str: &str) -> String { - str.replace("-", r"\-") -} - -pub(crate) fn indent(level: i8, input: &str) -> String { - format!(".RS {}\n{}\n.RE", level, input) -} - -pub(crate) fn section_title(title: &str) -> String { - format!(".SH \"{}\"\n", title.to_uppercase()) -} - -pub(crate) fn document_title( - app: &clap::App, - section: i8, - manual: Option, - date: Option, -) -> String { - let version = match app.get_version() { - Some(version) => format!(r#" "{} v{}""#, app.get_name(), version), - None => r#" """#.to_string(), - }; - - let manual = match manual { - Some(manual) => format!(r#" "{}""#, manual), - None => r#" """#.to_string(), - }; - - let date = match date { - Some(date) => format!(r#" "{}""#, date), - None => r#" """#.to_string(), - }; - - let name = if let Some(name) = app.get_bin_name() { - name - } else { - app.get_name() - }; - - format!(".TH {} {} {} {} {}\n", name, section, date, version, manual) -} - -pub(crate) fn list(title: &str, list: Vec>) -> String { - let mut res = String::new(); - - res.push_str(§ion_title(&escape(title))); - res.push_str(".P\n.RS 2\n.nf\n"); - for item in list { - res.push_str(&escape(&item.into())); - res.push('\n'); - } - - res -} diff --git a/clap_man/src/render.rs b/clap_man/src/render.rs index de0a698ec20..23c59dde9d8 100644 --- a/clap_man/src/render.rs +++ b/clap_man/src/render.rs @@ -1,101 +1,94 @@ -use std::io::Write; +use clap::{AppSettings, ArgSettings}; +use roff::{bold, escape, italic, list, paragraph}; -use crate::man::{bold, document_title, escape, indent, italic, list, section_title}; - -use clap::ArgSettings; - -pub(crate) fn header(app: &clap::App, section: i8, manual: Option, buf: &mut dyn Write) { - write!(buf, "{}", document_title(app, section, manual, None)).unwrap(); +pub(crate) fn subcommand_heading(app: &clap::App) -> String { + match app.get_subommand_help_heading() { + Some(title) => escape(title), + None => "Subcommands".to_string(), + } } -pub(crate) fn about(app: &clap::App, buf: &mut dyn Write) { - write!(buf, "{}", section_title("Name")).unwrap(); - write!(buf, "{}", bold(&app_name(app))).unwrap(); - - if let Some(about) = app.get_about().or_else(|| app.get_long_about()) { - write!(buf, r" \- {}", escape(about)).unwrap(); +pub(crate) fn about(app: &clap::App) -> String { + match app.get_about().or_else(|| app.get_long_about()) { + Some(about) => format!("{} - {}", app.get_name(), about), + None => app.get_name().to_string(), } - - writeln!(buf).unwrap(); } -pub(crate) fn description(app: &clap::App, buf: &mut dyn Write) { - if let Some(about) = app.get_long_about().or_else(|| app.get_about()) { - writeln!(buf, "{}{}", section_title("Description"), escape(about)).unwrap(); +pub(crate) fn description(app: &clap::App) -> Vec { + match app.get_long_about().or_else(|| app.get_about()) { + Some(about) => about + .lines() + .filter_map(|l| (!l.trim().is_empty()).then(|| paragraph(l.trim()))) + .collect(), + None => Vec::new(), } } -pub(crate) fn synopsis(app: &clap::App, buf: &mut dyn Write) { - write!( - buf, - "{}{} ", - section_title("Synopsis"), - italic(&app_name(app)) - ) - .unwrap(); +pub(crate) fn synopsis(app: &clap::App) -> String { + let mut res = String::new(); + + res.push_str(&italic(app.get_name())); + res.push(' '); for opt in app.get_arguments() { - let options = match (opt.get_short(), opt.get_long()) { - (Some(short), Some(long)) => format!("[-{}|--{}]", short, long), - (Some(short), None) => format!("[-{}]", short), - (None, Some(long)) => format!("[--{}]", long), + res.push_str(&match (opt.get_short(), opt.get_long()) { + (Some(short), Some(long)) => format!("[-{}|--{}] ", short, long), + (Some(short), None) => format!("[-{}] ", short), + (None, Some(long)) => format!("[--{}] ", long), (None, None) => "".to_string(), - }; - - write!(buf, "{} ", options).unwrap(); + }); } for arg in app.get_positionals() { - write!(buf, "{} ", format!("[{}]", arg.get_name())).unwrap(); + res.push_str(&format!("[{}] ", arg.get_name())); } if app.has_subcommands() { - write!(buf, "[{}]", subcommand_heading(app).to_lowercase()).unwrap(); + res.push_str(&format!("[{}] ", subcommand_heading(app).to_lowercase())); } - writeln!(buf).unwrap(); + res } -pub(crate) fn options(app: &clap::App, buf: &mut dyn Write) { +pub(crate) fn options(app: &clap::App) -> Vec { + let mut res = Vec::new(); let items: Vec<_> = app .get_arguments() .filter(|i| !i.is_set(ArgSettings::Hidden)) .collect(); - if items.is_empty() { - return; - } - - write!(buf, "{}", section_title("Options")).unwrap(); for opt in items.iter().filter(|a| !a.is_positional()) { - let args = match (opt.get_short(), opt.get_long()) { - (Some(short), Some(long)) => format!("-{}, --{}", short, long), - (Some(short), None) => format!("-{}", short), - (None, Some(long)) => format!("--{}", long), - (None, None) => "".to_string(), + let mut body = Vec::new(); + + let mut header = match (opt.get_short(), opt.get_long()) { + (Some(short), Some(long)) => { + vec![short_option(short), ", ".to_string(), long_option(long)] + } + (Some(short), None) => vec![short_option(short)], + (None, Some(long)) => vec![long_option(long)], + (None, None) => vec![], }; - write!(buf, "{}", bold(&args)).unwrap(); - if let Some(value) = &opt.get_value_names() { - write!(buf, " {}", italic(&value.join(" "))).unwrap(); + header.push(format!("={}", italic(&value.join(" ")))); } if let Some(defs) = option_default_values(opt) { - write!(buf, " {}", defs).unwrap(); + header.push(format!(" {}", defs)); } - writeln!(buf).unwrap(); - if let Some(help) = opt.get_long_help().or_else(|| opt.get_help()) { - write!(buf, "{}", indent(4, help)).unwrap(); + body.push(help.to_string()); } if let Some(env) = option_environment(opt) { - writeln!(buf, "{}", indent(4, &env)).unwrap(); + body.push(env); } - writeln!(buf, "\n").unwrap(); + body.push("\n".to_string()); + + res.push(list(&header, &body)); } for pos in items.iter().filter(|a| a.is_positional()) { @@ -103,99 +96,77 @@ pub(crate) fn options(app: &clap::App, buf: &mut dyn Write) { let (rhs, lhs) = if required { ("<", ">") } else { ("[", "]") }; let name = format!("{}{}{}", rhs, pos.get_name(), lhs); - write!(buf, "{}", bold(&name)).unwrap(); + let mut header = vec![bold(&name)]; + + let mut body = Vec::new(); if let Some(defs) = option_default_values(pos) { - write!(buf, " {}", defs).unwrap(); + header.push(format!(" {}", defs)); } - writeln!(buf).unwrap(); - if let Some(help) = pos.get_long_help().or_else(|| pos.get_help()) { - write!(buf, "{}", indent(4, help)).unwrap(); + body.push(help.to_string()); } if let Some(env) = option_environment(pos) { - writeln!(buf, "{}", indent(4, &env)).unwrap(); + body.push(env); } - writeln!(buf, "\n").unwrap(); - } -} - -pub(crate) fn subcommands(app: &clap::App, section: i8, buf: &mut dyn Write) { - let commands: Vec<_> = app.get_subcommands().collect(); - - if commands.is_empty() { - return; + res.push(list(&header, &body)) } - write!(buf, "{}", section_title(&subcommand_heading(app))).unwrap(); - for command in commands { - let name = format!("{}-{}", app_name(app), command.get_name()); - writeln!(buf, "{}({})", bold(&escape(&name)), section).unwrap(); - - if let Some(about) = command.get_about() { - writeln!(buf, ".br\n{}\n", about).unwrap(); - } - } + res } -pub(crate) fn authors(app: &clap::App, buf: &mut dyn Write) { - if let Some(authors) = app.get_author() { - let separator = ['\n', ':'].iter().find(|&&s| authors.contains(s)); - let authors = if let Some(sep) = separator { - authors.split(*sep).collect() - } else { - vec![authors] - }; - - let title = if authors.len() > 1 { - "Authors" - } else { - "Author" - }; - - write!(buf, "{}", list(title, authors)).unwrap(); - } +pub(crate) fn subcommands(app: &clap::App, section: i8) -> Vec { + app.get_subcommands() + .filter(|s| !s.is_set(AppSettings::Hidden)) + .map(|command| { + let name = format!("{}-{}({})", app.get_name(), command.get_name(), section); + + let mut body = match command.get_long_about().or_else(|| command.get_about()) { + Some(about) => about + .lines() + .filter_map(|l| (!l.trim().is_empty()).then(|| l.trim())) + .collect(), + None => Vec::new(), + }; + + body.push("\n"); + + list(&[bold(&name)], &body) + }) + .collect() } -pub(crate) fn version(app: &clap::App, buf: &mut dyn Write) { - if let Some(version) = app.get_version() { - write!(buf, "{}", section_title("Version")).unwrap(); - writeln!(buf, "v{}", escape(version)).unwrap(); - } +pub(crate) fn version(app: &clap::App) -> String { + format!("v{}", app.get_version().unwrap()) } -pub(crate) fn custom_sections(sections: Vec<(String, Vec)>, buf: &mut dyn Write) { - for (title, body) in sections { - write!(buf, "{}", section_title(&title)).unwrap(); - - for paragraph in body { - writeln!(buf, ".sp\n{}", escape(¶graph)).unwrap(); - } +pub(crate) fn after_help(app: &clap::App) -> Vec { + match app.get_after_long_help().or_else(|| app.get_after_help()) { + Some(about) => about + .lines() + .filter_map(|l| (!l.trim().is_empty()).then(|| paragraph(l.trim()))) + .collect(), + None => Vec::new(), } } -pub(crate) fn after_help(app: &clap::App, buf: &mut dyn Write) { - if let Some(help) = app.get_after_help() { - write!(buf, "{}", section_title("Extra")).unwrap(); - writeln!(buf, ".sp\n{}", escape(help)).unwrap(); +fn short_option(opt: char) -> String { + format!("-{}", bold(&opt.to_string())) +} - if let Some(long) = app.get_after_long_help() { - writeln!(buf, ".sp\n{}", escape(long)).unwrap(); - } - } +fn long_option(opt: &str) -> String { + format!("--{}", bold(&opt.to_string())) } fn option_environment(opt: &clap::Arg) -> Option { if let Some(env) = opt.get_env() { - let env = bold(&escape(&env.to_string_lossy())); - let text = format!( + return Some(paragraph(&format!( "May also be specified with the {} environment variable. ", - env - ); - return Some(format!("\n.sp\n{}", &text)); + bold(&env.to_string_lossy()) + ))); } None @@ -215,18 +186,3 @@ fn option_default_values(opt: &clap::Arg) -> Option { None } - -fn app_name(app: &clap::App) -> String { - if let Some(name) = app.get_bin_name() { - escape(name) - } else { - escape(app.get_name()) - } -} - -fn subcommand_heading(app: &clap::App) -> String { - match app.get_subommand_help_heading() { - Some(title) => escape(title), - None => "Subcommands".to_string(), - } -} From 80b3683b5b775e09d1e693fc75f67f743f8965ee Mon Sep 17 00:00:00 2001 From: Sondre Nilsen Date: Fri, 17 Dec 2021 17:29:01 +0100 Subject: [PATCH 07/11] chore: Use latest RC for clap --- clap_man/Cargo.toml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/clap_man/Cargo.toml b/clap_man/Cargo.toml index 8affc4c18f1..538b8bbf89f 100644 --- a/clap_man/Cargo.toml +++ b/clap_man/Cargo.toml @@ -31,11 +31,11 @@ bench = false [dependencies] roff = "0.1.0" -clap = { path = "../", version = "=3.0.0-rc.4", default-features = false, features = ["std", "env"] } +clap = { path = "../", version = "=3.0.0-rc.7", default-features = false, features = ["std", "env"] } [dev-dependencies] pretty_assertions = "1.0" -clap = { path = "../", version = "=3.0.0-rc.4", default-features = false, features = ["std"] } +clap = { path = "../", version = "=3.0.0-rc.7", default-features = false, features = ["std"] } [features] default = [] From 91714f0de9444fc26039f57bb17e398334c24167 Mon Sep 17 00:00:00 2001 From: Sondre Nilsen Date: Fri, 17 Dec 2021 17:44:39 +0100 Subject: [PATCH 08/11] feat(man): Wrap options correctly --- clap_man/src/render.rs | 23 ++++++++++++++++------- 1 file changed, 16 insertions(+), 7 deletions(-) diff --git a/clap_man/src/render.rs b/clap_man/src/render.rs index 23c59dde9d8..f68982ceab2 100644 --- a/clap_man/src/render.rs +++ b/clap_man/src/render.rs @@ -32,16 +32,18 @@ pub(crate) fn synopsis(app: &clap::App) -> String { res.push(' '); for opt in app.get_arguments() { + let (lhs, rhs) = optional_or_required_markers(opt); res.push_str(&match (opt.get_short(), opt.get_long()) { - (Some(short), Some(long)) => format!("[-{}|--{}] ", short, long), - (Some(short), None) => format!("[-{}] ", short), - (None, Some(long)) => format!("[--{}] ", long), + (Some(short), Some(long)) => format!("{}-{}|--{}{} ", lhs, short, long, rhs), + (Some(short), None) => format!("{}-{}{} ", lhs, short, rhs), + (None, Some(long)) => format!("{}--{}{} ", lhs, long, rhs), (None, None) => "".to_string(), }); } for arg in app.get_positionals() { - res.push_str(&format!("[{}] ", arg.get_name())); + let (lhs, rhs) = optional_or_required_markers(arg); + res.push_str(&format!("{}{}{} ", lhs, arg.get_name(), rhs)); } if app.has_subcommands() { @@ -92,9 +94,8 @@ pub(crate) fn options(app: &clap::App) -> Vec { } for pos in items.iter().filter(|a| a.is_positional()) { - let required = pos.is_set(ArgSettings::Required); - let (rhs, lhs) = if required { ("<", ">") } else { ("[", "]") }; - let name = format!("{}{}{}", rhs, pos.get_name(), lhs); + let (lhs, rhs) = optional_or_required_markers(pos); + let name = format!("{}{}{}", lhs, pos.get_name(), rhs); let mut header = vec![bold(&name)]; @@ -153,6 +154,14 @@ pub(crate) fn after_help(app: &clap::App) -> Vec { } } +fn optional_or_required_markers(opt: &clap::Arg) -> (String, String) { + if opt.is_set(ArgSettings::Required) { + ("<".to_string(), ">".to_string()) + } else { + ("[".to_string(), "]".to_string()) + } +} + fn short_option(opt: char) -> String { format!("-{}", bold(&opt.to_string())) } From c257bb4c63f8579ea5cf466621f9cb612c8399cb Mon Sep 17 00:00:00 2001 From: Sondre Nilsen Date: Sat, 18 Dec 2021 15:41:09 +0100 Subject: [PATCH 09/11] fix: Proper subcommand values, code review changes --- clap_man/examples/man.rs | 6 ++++- clap_man/src/lib.rs | 22 ++++++++++++++--- clap_man/src/render.rs | 52 ++++++++++++++++++++++++++++++---------- src/build/app/mod.rs | 12 ++++++++++ 4 files changed, 76 insertions(+), 16 deletions(-) diff --git a/clap_man/examples/man.rs b/clap_man/examples/man.rs index 90802fd07f0..7286bb55f94 100644 --- a/clap_man/examples/man.rs +++ b/clap_man/examples/man.rs @@ -25,7 +25,11 @@ fn main() { .env("CONFIG_FILE"), ) .arg(arg!([output] "Sets an output file").default_value("result.txt")) - .arg(arg!(-d --debug ... "Turn debugging information on").env("DEBUG_ON")) + .arg( + arg!(-d --debug ... "Turn debugging information on") + .env("DEBUG_ON") + .hide_env(true), + ) .subcommand( App::new("test") .about("does testing things") diff --git a/clap_man/src/lib.rs b/clap_man/src/lib.rs index bd29dbd0bb0..fb8890a79c8 100644 --- a/clap_man/src/lib.rs +++ b/clap_man/src/lib.rs @@ -50,8 +50,9 @@ impl Man { self } - /// Set manual for where the document comes from, the most common being - /// `General Commands Manual`. + /// Set manual for where the document comes from. + /// + /// The most common being `General Commands Manual`. pub fn manual(mut self, manual: impl Into) -> Self { self.manual = Some(manual.into()); self @@ -75,10 +76,19 @@ impl Man { app._build_all(); let mut page = Roff::new(app.get_name(), self.get_section()) + .source(&format!( + "{} {}", + app.get_name(), + app.get_version().unwrap_or_default() + )) .section("Name", [&render::about(app)]) .section("Synopsis", [&render::synopsis(app)]) .section("Description", &render::description(app)); + if let Some(manual) = &self.manual { + page = page.manual(manual); + } + if app_has_arguments(app) { page = page.section("Options", &render::options(app)); } @@ -98,7 +108,7 @@ impl Man { page = page.section(&title, &[section]); } - if app.get_version().is_some() { + if app_has_version(app) { page = page.section("Version", &[render::version(app)]); } @@ -114,6 +124,12 @@ impl Man { } } +fn app_has_version(app: &clap::App) -> bool { + app.get_long_version() + .or_else(|| app.get_version()) + .is_some() +} + fn app_has_arguments(app: &clap::App) -> bool { app.get_arguments() .any(|i| !i.is_set(clap::ArgSettings::Hidden)) diff --git a/clap_man/src/render.rs b/clap_man/src/render.rs index f68982ceab2..f191fc4545a 100644 --- a/clap_man/src/render.rs +++ b/clap_man/src/render.rs @@ -3,7 +3,7 @@ use roff::{bold, escape, italic, list, paragraph}; pub(crate) fn subcommand_heading(app: &clap::App) -> String { match app.get_subommand_help_heading() { - Some(title) => escape(title), + Some(title) => title.to_string(), None => "Subcommands".to_string(), } } @@ -32,7 +32,7 @@ pub(crate) fn synopsis(app: &clap::App) -> String { res.push(' '); for opt in app.get_arguments() { - let (lhs, rhs) = optional_or_required_markers(opt); + let (lhs, rhs) = option_markers(opt); res.push_str(&match (opt.get_short(), opt.get_long()) { (Some(short), Some(long)) => format!("{}-{}|--{}{} ", lhs, short, long, rhs), (Some(short), None) => format!("{}-{}{} ", lhs, short, rhs), @@ -42,12 +42,22 @@ pub(crate) fn synopsis(app: &clap::App) -> String { } for arg in app.get_positionals() { - let (lhs, rhs) = optional_or_required_markers(arg); + let (lhs, rhs) = option_markers(arg); res.push_str(&format!("{}{}{} ", lhs, arg.get_name(), rhs)); } if app.has_subcommands() { - res.push_str(&format!("[{}] ", subcommand_heading(app).to_lowercase())); + let (lhs, rhs) = subcommand_markers(app); + res.push_str(&format!( + "{}{}{} ", + lhs, + escape( + &app.get_subcommand_value_name() + .unwrap_or(&subcommand_heading(app)) + .to_lowercase() + ), + rhs + )); } res @@ -94,7 +104,7 @@ pub(crate) fn options(app: &clap::App) -> Vec { } for pos in items.iter().filter(|a| a.is_positional()) { - let (lhs, rhs) = optional_or_required_markers(pos); + let (lhs, rhs) = option_markers(pos); let name = format!("{}{}{}", lhs, pos.get_name(), rhs); let mut header = vec![bold(&name)]; @@ -125,7 +135,7 @@ pub(crate) fn subcommands(app: &clap::App, section: i8) -> Vec { .map(|command| { let name = format!("{}-{}({})", app.get_name(), command.get_name(), section); - let mut body = match command.get_long_about().or_else(|| command.get_about()) { + let mut body = match command.get_about().or_else(|| command.get_long_about()) { Some(about) => about .lines() .filter_map(|l| (!l.trim().is_empty()).then(|| l.trim())) @@ -141,7 +151,12 @@ pub(crate) fn subcommands(app: &clap::App, section: i8) -> Vec { } pub(crate) fn version(app: &clap::App) -> String { - format!("v{}", app.get_version().unwrap()) + format!( + "v{}", + app.get_long_version() + .or_else(|| app.get_version()) + .unwrap() + ) } pub(crate) fn after_help(app: &clap::App) -> Vec { @@ -154,11 +169,22 @@ pub(crate) fn after_help(app: &clap::App) -> Vec { } } -fn optional_or_required_markers(opt: &clap::Arg) -> (String, String) { - if opt.is_set(ArgSettings::Required) { - ("<".to_string(), ">".to_string()) +fn subcommand_markers(cmd: &clap::App) -> (&'static str, &'static str) { + markers( + cmd.is_set(AppSettings::SubcommandRequired) + || cmd.is_set(AppSettings::SubcommandRequiredElseHelp), + ) +} + +fn option_markers(opt: &clap::Arg) -> (&'static str, &'static str) { + markers(opt.is_set(ArgSettings::Required)) +} + +fn markers(required: bool) -> (&'static str, &'static str) { + if required { + ("<", ">") } else { - ("[".to_string(), "]".to_string()) + ("[", "]") } } @@ -171,7 +197,9 @@ fn long_option(opt: &str) -> String { } fn option_environment(opt: &clap::Arg) -> Option { - if let Some(env) = opt.get_env() { + if opt.is_set(ArgSettings::HideEnv) { + return None; + } else if let Some(env) = opt.get_env() { return Some(paragraph(&format!( "May also be specified with the {} environment variable. ", bold(&env.to_string_lossy()) diff --git a/src/build/app/mod.rs b/src/build/app/mod.rs index 9cda3d67c28..0047c1647af 100644 --- a/src/build/app/mod.rs +++ b/src/build/app/mod.rs @@ -2112,6 +2112,12 @@ impl<'help> App<'help> { self.version } + /// Get the long version of the app. + #[inline] + pub fn get_long_version(&self) -> Option<&'help str> { + self.long_version + } + /// Get the authors of the app. #[inline] pub fn get_author(&self) -> Option<&'help str> { @@ -2253,6 +2259,12 @@ impl<'help> App<'help> { self.subcommand_heading } + /// Returns the subcommand value name. + #[inline] + pub fn get_subcommand_value_name(&self) -> Option<&str> { + self.subcommand_value_name + } + /// Returns the help heading for listing subcommands. #[inline] pub fn get_after_help(&self) -> Option<&str> { From 46a4eafb03dfe96f52b85799e9ebd2948edf9135 Mon Sep 17 00:00:00 2001 From: Lars Wirzenius Date: Mon, 20 Dec 2021 17:18:51 +0200 Subject: [PATCH 10/11] feat: Port to roff 0.2.1 Use the new roff crate, from crates.io, not a local, modified version of it. The roff 0.2 series changes that crate's API completely: it now only concerns itself with ROFF, not with manual pages. This requires manual page generating code to change significantly. Separate manual page metadata (title, section, date, etc) to its own struct so it's better isolated from the contents of the manual page. This makes the clap__man code clearer, and isn't needed by users of the crate, if they use the generate_manpage function. Drop support for additional, custom sections that don't come from clap:App. If someone needs that, they'll almost certainly want to have more control over how manual pages are built, including the order of the sections. --- Cargo.toml | 3 - clap_man/Cargo.toml | 2 +- clap_man/examples/man-builder.rs | 26 ++--- clap_man/examples/man.rs | 6 +- clap_man/src/lib.rs | 153 ++++++++++++------------- clap_man/src/render.rs | 191 +++++++++++++++++-------------- clap_man/tests/generate.rs | 2 +- 7 files changed, 189 insertions(+), 194 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index e7efe198378..917fc6bcc2b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -142,9 +142,6 @@ rustversion = "1" # Cutting out `filesystem` feature trycmd = { version = "0.9", default-features = false, features = ["color-auto", "diff", "examples"] } -[patch.crates-io] -roff = { git = "https://github.com/sondr3/roff-rs", branch = "updates" } - [[example]] name = "demo" required-features = ["derive"] diff --git a/clap_man/Cargo.toml b/clap_man/Cargo.toml index 538b8bbf89f..d5079329427 100644 --- a/clap_man/Cargo.toml +++ b/clap_man/Cargo.toml @@ -30,7 +30,7 @@ pre-release-replacements = [ bench = false [dependencies] -roff = "0.1.0" +roff = "0.2.1" clap = { path = "../", version = "=3.0.0-rc.7", default-features = false, features = ["std", "env"] } [dev-dependencies] diff --git a/clap_man/examples/man-builder.rs b/clap_man/examples/man-builder.rs index 3f97aae0040..b5033975171 100644 --- a/clap_man/examples/man-builder.rs +++ b/clap_man/examples/man-builder.rs @@ -1,11 +1,9 @@ use clap::{arg, App}; -use clap_man::{roff::ManSection, Man}; -use roff::bold; -use std::io; +use clap_man::{Man, Meta}; // Run this example as `cargo run --example man-builder | man -l -`. -fn main() { +fn main() -> Result<(), std::io::Error> { let mut app = App::new("myapp") .version("1.0") .author("Kevin K. ") @@ -23,18 +21,14 @@ fn main() { App::new("test") .about("does testing things") .arg(arg!(-l --list "Lists test values")), + ) + .after_help( + "\ +For more information about the config file syntax, look up the INI format. +To see the debug information, visit our website on github.com" ); - Man::new() - .section(ManSection::Executable) - .manual("GNU") - .custom_section( - "Reference", - &[ - "For more information about the config file syntax, look up the INI format. ", - "To see the debug information, visit our website on ", - &bold("GitHub"), - ], - ) - .render(&mut app, &mut io::stdout()); + let meta = Meta::from_clap("1", "GNU", &app); + let man = Man::new(&meta, &mut app); + man.render(&mut std::io::stdout()) } diff --git a/clap_man/examples/man.rs b/clap_man/examples/man.rs index 7286bb55f94..3b0f3b631d6 100644 --- a/clap_man/examples/man.rs +++ b/clap_man/examples/man.rs @@ -4,7 +4,7 @@ use std::io; // Run this example as `cargo run --example man | man -l -`. -fn main() { +fn main() -> Result<(), std::io::Error> { let mut app = App::new("myapp") .version("1.0") .author("Kevin K. :Ola Nordmann ") @@ -12,7 +12,7 @@ fn main() { .long_about( "With a longer description to help clarify some things. - And a few newlines.", +And a few newlines.", ) .after_help("This is an extra section added to the end of the manpage.") .after_long_help("With even more text added.") @@ -36,5 +36,5 @@ fn main() { .arg(arg!(-l --list "Lists test values")), ); - generate_manpage(&mut app, &mut io::stdout()); + generate_manpage(&mut app, &mut io::stdout()) } diff --git a/clap_man/src/lib.rs b/clap_man/src/lib.rs index fb8890a79c8..a332fdfec04 100644 --- a/clap_man/src/lib.rs +++ b/clap_man/src/lib.rs @@ -2,139 +2,130 @@ #![doc = include_str!("../README.md")] #![warn(missing_docs, trivial_casts, unused_allocation, trivial_numeric_casts)] #![forbid(unsafe_code)] +#![deny(missing_docs)] mod render; pub use roff; use render::subcommand_heading; -use roff::{ManSection, Roff, Troffable}; +use roff::{roman, Roff}; use std::io::Write; -/// Man page generator -pub struct Man { - section: Option, - manual: Option, - sections: Vec<(String, String)>, +/// Generate a manual page and write it out. +pub fn generate_manpage<'a>(app: &mut clap::App<'a>, buf: &mut dyn Write) -> Result<(), std::io::Error> { + let meta = Meta::from_clap("1", "", app); + let man = Man::new(&meta, app); + man.render(buf) } -impl Default for Man { - fn default() -> Self { - Self { - section: Some(ManSection::Executable), - manual: Some("General Commands Manual".to_string()), - sections: Vec::new(), - } - } +/// Metadata about a manual page. +pub struct Meta { + title: String, + section: String, + date: String, + source: String, + manual: String, } -/// Generate manpage for your application using the most common default values. -pub fn generate_manpage<'a>(app: &mut clap::App<'a>, buf: &mut dyn Write) { - let man = Man::default(); - man.render(app, buf); -} - -impl Man { - /// Create a new builder for man pages. - pub fn new() -> Self { - Man { - section: None, - manual: None, - sections: Vec::new(), +impl Meta { + /// Create metadata from a clap::App. + pub fn from_clap(section: &str, manual: &str, app: &clap::App) -> Self { + Self { + title: app.get_name().to_string(), + section: section.to_string(), + date: "".to_string(), // FIXME + source: format!( + "{} {}", + app.get_name(), + app.get_version().unwrap_or_default() + ), + manual: manual.to_string(), } } - /// Add section for your man page, see [`Section`]. - pub fn section(mut self, section: ManSection) -> Self { - self.section = Some(section); - self - } - - /// Set manual for where the document comes from. - /// - /// The most common being `General Commands Manual`. - pub fn manual(mut self, manual: impl Into) -> Self { - self.manual = Some(manual.into()); - self + // Turn metadata into arguments for a .TH macro. + fn to_args(&self) -> Vec<&str> { + vec![ + &self.title, + &self.section, + &self.date, + &self.source, + &self.manual, + ] } +} - /// Add a custom section to the man pages. - pub fn custom_section<'a, I, C>(mut self, title: impl Into, content: I) -> Self - where - I: IntoIterator, - C: Troffable + 'a, - { - self.sections.push(( - title.into(), - content.into_iter().map(Troffable::render).collect(), - )); - self - } +/// A manual page as constructed from a clap::App. +pub struct Man { + roff: Roff, +} - /// Write the manpage to a buffer. - pub fn render(self, app: &mut clap::App, buf: &mut dyn std::io::Write) { +impl Man { + /// Create a new manual page. + pub fn new(meta: &Meta, app: &mut clap::App) -> Self { app._build_all(); - let mut page = Roff::new(app.get_name(), self.get_section()) - .source(&format!( - "{} {}", - app.get_name(), - app.get_version().unwrap_or_default() - )) - .section("Name", [&render::about(app)]) - .section("Synopsis", [&render::synopsis(app)]) - .section("Description", &render::description(app)); - - if let Some(manual) = &self.manual { - page = page.manual(manual); - } + let mut roff = Roff::default(); + roff.control("TH", meta.to_args()); + roff.control("SH", ["NAME"]); + render::about(&mut roff, app); + roff.control("SH", ["SYNOPSIS"]); + render::synopsis(&mut roff, app); + roff.control("SH", ["DESCRIPTION"]); + render::description(&mut roff, app); if app_has_arguments(app) { - page = page.section("Options", &render::options(app)); + roff.control("SH", ["OPTIONS"]); + render::options(&mut roff, app); } if app_has_subcommands(app) { - page = page.section( - &subcommand_heading(app), - &render::subcommands(app, self.get_section().value()), - ) + let heading = subcommand_heading(app); + roff.control("SH", [heading.as_str()]); + render::subcommands(&mut roff, app, &meta.section); } if app.get_after_long_help().is_some() || app.get_after_help().is_some() { - page = page.section("Extra", &render::after_help(app)) - } - - for (title, section) in self.sections { - page = page.section(&title, &[section]); + roff.control("SH", ["EXTRA"]); + render::after_help(&mut roff, app); } if app_has_version(app) { - page = page.section("Version", &[render::version(app)]); + let version = roman(&render::version(app)); + roff.control("SH", ["VERSION"]); + roff.text([version]); } if app.get_author().is_some() { - page = page.section("Author(s)", &[app.get_author().unwrap_or_default()]); + let author = roman(app.get_author().unwrap_or_default()); + roff.control("SH", ["AUTHORS"]); + roff.text([author]); } - buf.write_all(page.render().as_bytes()).unwrap(); + Self { roff } } - fn get_section(&self) -> ManSection { - self.section.unwrap_or(ManSection::Executable) + /// Render a manual page into writer. + pub fn render(&self, w: &mut dyn Write) -> Result<(), std::io::Error> { + self.roff.to_writer(w) } } +// Does the application have a version? fn app_has_version(app: &clap::App) -> bool { app.get_long_version() .or_else(|| app.get_version()) .is_some() } +// Does the application have any command line arguments? fn app_has_arguments(app: &clap::App) -> bool { app.get_arguments() .any(|i| !i.is_set(clap::ArgSettings::Hidden)) } +// Does the application have any subcommands? fn app_has_subcommands(app: &clap::App) -> bool { app.get_subcommands() .any(|i| !i.is_set(clap::AppSettings::Hidden)) diff --git a/clap_man/src/render.rs b/clap_man/src/render.rs index f191fc4545a..397ea2c08f6 100644 --- a/clap_man/src/render.rs +++ b/clap_man/src/render.rs @@ -1,81 +1,100 @@ use clap::{AppSettings, ArgSettings}; -use roff::{bold, escape, italic, list, paragraph}; +use roff::{roman, bold, italic, Inline, Roff}; pub(crate) fn subcommand_heading(app: &clap::App) -> String { match app.get_subommand_help_heading() { Some(title) => title.to_string(), - None => "Subcommands".to_string(), + None => "SUBCOMMANDS".to_string(), } } -pub(crate) fn about(app: &clap::App) -> String { - match app.get_about().or_else(|| app.get_long_about()) { +pub(crate) fn about(roff: &mut Roff, app: &clap::App) { + let s = match app.get_about().or_else(|| app.get_long_about()) { Some(about) => format!("{} - {}", app.get_name(), about), None => app.get_name().to_string(), - } + }; + roff.text([roman(&s)]); } -pub(crate) fn description(app: &clap::App) -> Vec { - match app.get_long_about().or_else(|| app.get_about()) { - Some(about) => about - .lines() - .filter_map(|l| (!l.trim().is_empty()).then(|| paragraph(l.trim()))) - .collect(), - None => Vec::new(), +pub(crate) fn description(roff: &mut Roff, app: &clap::App) { + if let Some(about) = app.get_long_about().or_else(|| app.get_about()) { + for line in about.lines() { + if line.trim().is_empty() { + roff.control("PP", []); + } else { + roff.text([roman(line)]); + } + } } } -pub(crate) fn synopsis(app: &clap::App) -> String { - let mut res = String::new(); +pub(crate) fn synopsis(roff: &mut Roff, app: &clap::App) { + let mut line = vec![ + bold(app.get_name()), + roman(" "), + ]; - res.push_str(&italic(app.get_name())); - res.push(' '); for opt in app.get_arguments() { let (lhs, rhs) = option_markers(opt); - res.push_str(&match (opt.get_short(), opt.get_long()) { - (Some(short), Some(long)) => format!("{}-{}|--{}{} ", lhs, short, long, rhs), - (Some(short), None) => format!("{}-{}{} ", lhs, short, rhs), - (None, Some(long)) => format!("{}--{}{} ", lhs, long, rhs), - (None, None) => "".to_string(), - }); + match (opt.get_short(), opt.get_long()) { + (Some(short), Some(long)) => { + line.push(roman(lhs)); + line.push(bold(&format!("-{}", short))); + line.push(roman("|")); + line.push(bold(&format!("--{}", long))); + line.push(roman(rhs)); + line.push(roman(" ")); + } + (Some(short), None) => { + line.push(roman(lhs)); + line.push(bold(&format!("-{} ", short))); + line.push(roman(rhs)); + line.push(roman(" ")); + } + (None, Some(long)) => { + line.push(roman(lhs)); + line.push(bold(&format!("--{}", long))); + line.push(roman(rhs)); + line.push(roman(" ")); + } + (None, None) => (), + }; } for arg in app.get_positionals() { let (lhs, rhs) = option_markers(arg); - res.push_str(&format!("{}{}{} ", lhs, arg.get_name(), rhs)); + line.push(roman(lhs)); + line.push(italic(arg.get_name())); + line.push(roman(rhs)); + line.push(roman(" ")); } if app.has_subcommands() { let (lhs, rhs) = subcommand_markers(app); - res.push_str(&format!( - "{}{}{} ", - lhs, - escape( - &app.get_subcommand_value_name() - .unwrap_or(&subcommand_heading(app)) - .to_lowercase() - ), - rhs - )); + line.push(roman(lhs)); + line.push(italic( + &app.get_subcommand_value_name() + .unwrap_or(&subcommand_heading(app)) + .to_lowercase())); + line.push(roman(rhs)); } - res + roff.text(line); } -pub(crate) fn options(app: &clap::App) -> Vec { - let mut res = Vec::new(); +pub(crate) fn options(roff: &mut Roff, app: &clap::App) { let items: Vec<_> = app .get_arguments() .filter(|i| !i.is_set(ArgSettings::Hidden)) .collect(); for opt in items.iter().filter(|a| !a.is_positional()) { - let mut body = Vec::new(); + let mut body = vec![]; let mut header = match (opt.get_short(), opt.get_long()) { (Some(short), Some(long)) => { - vec![short_option(short), ", ".to_string(), long_option(long)] + vec![short_option(short), roman(", "), long_option(long)] } (Some(short), None) => vec![short_option(short)], (None, Some(long)) => vec![long_option(long)], @@ -83,24 +102,26 @@ pub(crate) fn options(app: &clap::App) -> Vec { }; if let Some(value) = &opt.get_value_names() { - header.push(format!("={}", italic(&value.join(" ")))); + header.push(roman("=")); + header.push(italic(&value.join(" "))); } if let Some(defs) = option_default_values(opt) { - header.push(format!(" {}", defs)); + header.push(roman(" ")); + header.push(roman(&defs)); } if let Some(help) = opt.get_long_help().or_else(|| opt.get_help()) { - body.push(help.to_string()); + body.push(roman(help)); } - if let Some(env) = option_environment(opt) { - body.push(env); + if let Some(mut env) = option_environment(opt) { + body.append(&mut env); } - body.push("\n".to_string()); - - res.push(list(&header, &body)); + roff.control("TP", []); + roff.text(header); + roff.text(body); } for pos in items.iter().filter(|a| a.is_positional()) { @@ -109,45 +130,38 @@ pub(crate) fn options(app: &clap::App) -> Vec { let mut header = vec![bold(&name)]; - let mut body = Vec::new(); + let mut body = vec![]; if let Some(defs) = option_default_values(pos) { - header.push(format!(" {}", defs)); + header.push(roman(&format!(" {}", defs))); } if let Some(help) = pos.get_long_help().or_else(|| pos.get_help()) { - body.push(help.to_string()); + body.push(roman(&help.to_string())); } - if let Some(env) = option_environment(pos) { - body.push(env); + if let Some(mut env) = option_environment(pos) { + body.append(&mut env); } - res.push(list(&header, &body)) + roff.control("TP", []); + roff.text(body); } - - res } -pub(crate) fn subcommands(app: &clap::App, section: i8) -> Vec { - app.get_subcommands() - .filter(|s| !s.is_set(AppSettings::Hidden)) - .map(|command| { - let name = format!("{}-{}({})", app.get_name(), command.get_name(), section); - - let mut body = match command.get_about().or_else(|| command.get_long_about()) { - Some(about) => about - .lines() - .filter_map(|l| (!l.trim().is_empty()).then(|| l.trim())) - .collect(), - None => Vec::new(), - }; - - body.push("\n"); - - list(&[bold(&name)], &body) - }) - .collect() +pub(crate) fn subcommands(roff: &mut Roff, app: &clap::App, section: &str) { + for sub in app.get_subcommands().filter(|s| !s.is_set(AppSettings::Hidden)) { + roff.control("TP", []); + + let name = format!("{}-{}({})", app.get_name(), sub.get_name(), section); + roff.text([roman(&name)]); + + if let Some(about) = sub.get_about().or_else(|| sub.get_long_about()) { + for line in about.lines() { + roff.text([roman(line)]); + } + } + } } pub(crate) fn version(app: &clap::App) -> String { @@ -159,13 +173,11 @@ pub(crate) fn version(app: &clap::App) -> String { ) } -pub(crate) fn after_help(app: &clap::App) -> Vec { - match app.get_after_long_help().or_else(|| app.get_after_help()) { - Some(about) => about - .lines() - .filter_map(|l| (!l.trim().is_empty()).then(|| paragraph(l.trim()))) - .collect(), - None => Vec::new(), +pub(crate) fn after_help(roff: &mut Roff, app: &clap::App) { + if let Some(about) = app.get_after_long_help().or_else(|| app.get_after_help()) { + for line in about.lines() { + roff.text([roman(line)]); + } } } @@ -188,22 +200,23 @@ fn markers(required: bool) -> (&'static str, &'static str) { } } -fn short_option(opt: char) -> String { - format!("-{}", bold(&opt.to_string())) +fn short_option(opt: char) -> Inline { + bold(&format!("-{}", opt)) } -fn long_option(opt: &str) -> String { - format!("--{}", bold(&opt.to_string())) +fn long_option(opt: &str) -> Inline { + bold(&format!("--{}", opt)) } -fn option_environment(opt: &clap::Arg) -> Option { +fn option_environment(opt: &clap::Arg) -> Option> { if opt.is_set(ArgSettings::HideEnv) { return None; } else if let Some(env) = opt.get_env() { - return Some(paragraph(&format!( - "May also be specified with the {} environment variable. ", - bold(&env.to_string_lossy()) - ))); + return Some(vec![ + roman("May also be specified with the "), + bold(env.to_string_lossy().to_owned()), + roman(" environment variable. "), + ]); } None diff --git a/clap_man/tests/generate.rs b/clap_man/tests/generate.rs index 89bf385db7e..422f7d3f323 100644 --- a/clap_man/tests/generate.rs +++ b/clap_man/tests/generate.rs @@ -25,5 +25,5 @@ fn render_manpage() { .arg(arg!(-l --list "Lists test values")), ); - generate_manpage(&mut app, &mut io::sink()); + generate_manpage(&mut app, &mut io::sink()).unwrap(); } From 0b7aab5fec4ce8a8524737132e64cdea5c183cfe Mon Sep 17 00:00:00 2001 From: Sondre Nilsen Date: Fri, 28 Jan 2022 20:07:04 +0100 Subject: [PATCH 11/11] fix(man): Feedback from code review --- clap_man/CONTRIBUTING.md | 3 +-- clap_man/Cargo.toml | 4 ++-- clap_man/examples/man-builder.rs | 2 +- clap_man/src/lib.rs | 9 ++++++--- clap_man/src/render.rs | 18 +++++++++--------- 5 files changed, 19 insertions(+), 17 deletions(-) diff --git a/clap_man/CONTRIBUTING.md b/clap_man/CONTRIBUTING.md index 36eecb12114..e54a51d0e2b 100644 --- a/clap_man/CONTRIBUTING.md +++ b/clap_man/CONTRIBUTING.md @@ -1,4 +1,3 @@ # How to Contribute -See the [clap-wide CONTRIBUTING.md](../CONTRIBUTING.md). This will contain `clap_generate` specific notes. - +See the [clap-wide CONTRIBUTING.md](../CONTRIBUTING.md). This will contain `clap_man` specific notes. diff --git a/clap_man/Cargo.toml b/clap_man/Cargo.toml index d5079329427..01f7a36f070 100644 --- a/clap_man/Cargo.toml +++ b/clap_man/Cargo.toml @@ -31,11 +31,11 @@ bench = false [dependencies] roff = "0.2.1" -clap = { path = "../", version = "=3.0.0-rc.7", default-features = false, features = ["std", "env"] } +clap = { path = "../", version = "3.0", default-features = false, features = ["std", "env"] } [dev-dependencies] pretty_assertions = "1.0" -clap = { path = "../", version = "=3.0.0-rc.7", default-features = false, features = ["std"] } +clap = { path = "../", version = "3.0", default-features = false, features = ["std"] } [features] default = [] diff --git a/clap_man/examples/man-builder.rs b/clap_man/examples/man-builder.rs index b5033975171..e93eeabc53d 100644 --- a/clap_man/examples/man-builder.rs +++ b/clap_man/examples/man-builder.rs @@ -25,7 +25,7 @@ fn main() -> Result<(), std::io::Error> { .after_help( "\ For more information about the config file syntax, look up the INI format. -To see the debug information, visit our website on github.com" +To see the debug information, visit our website on github.com", ); let meta = Meta::from_clap("1", "GNU", &app); diff --git a/clap_man/src/lib.rs b/clap_man/src/lib.rs index a332fdfec04..cda156957a4 100644 --- a/clap_man/src/lib.rs +++ b/clap_man/src/lib.rs @@ -13,7 +13,10 @@ use roff::{roman, Roff}; use std::io::Write; /// Generate a manual page and write it out. -pub fn generate_manpage<'a>(app: &mut clap::App<'a>, buf: &mut dyn Write) -> Result<(), std::io::Error> { +pub fn generate_manpage<'a>( + app: &mut clap::App<'a>, + buf: &mut dyn Write, +) -> Result<(), std::io::Error> { let meta = Meta::from_clap("1", "", app); let man = Man::new(&meta, app); man.render(buf) @@ -114,8 +117,8 @@ impl Man { // Does the application have a version? fn app_has_version(app: &clap::App) -> bool { - app.get_long_version() - .or_else(|| app.get_version()) + app.get_version() + .or_else(|| app.get_long_version()) .is_some() } diff --git a/clap_man/src/render.rs b/clap_man/src/render.rs index 397ea2c08f6..9ffb792d148 100644 --- a/clap_man/src/render.rs +++ b/clap_man/src/render.rs @@ -1,5 +1,5 @@ use clap::{AppSettings, ArgSettings}; -use roff::{roman, bold, italic, Inline, Roff}; +use roff::{bold, italic, roman, Inline, Roff}; pub(crate) fn subcommand_heading(app: &clap::App) -> String { match app.get_subommand_help_heading() { @@ -16,7 +16,7 @@ pub(crate) fn about(roff: &mut Roff, app: &clap::App) { roff.text([roman(&s)]); } -pub(crate) fn description(roff: &mut Roff, app: &clap::App) { +pub(crate) fn description(roff: &mut Roff, app: &clap::App) { if let Some(about) = app.get_long_about().or_else(|| app.get_about()) { for line in about.lines() { if line.trim().is_empty() { @@ -29,11 +29,7 @@ pub(crate) fn description(roff: &mut Roff, app: &clap::App) { } pub(crate) fn synopsis(roff: &mut Roff, app: &clap::App) { - let mut line = vec![ - bold(app.get_name()), - roman(" "), - ]; - + let mut line = vec![bold(app.get_name()), roman(" ")]; for opt in app.get_arguments() { let (lhs, rhs) = option_markers(opt); @@ -76,7 +72,8 @@ pub(crate) fn synopsis(roff: &mut Roff, app: &clap::App) { line.push(italic( &app.get_subcommand_value_name() .unwrap_or(&subcommand_heading(app)) - .to_lowercase())); + .to_lowercase(), + )); line.push(roman(rhs)); } @@ -150,7 +147,10 @@ pub(crate) fn options(roff: &mut Roff, app: &clap::App) { } pub(crate) fn subcommands(roff: &mut Roff, app: &clap::App, section: &str) { - for sub in app.get_subcommands().filter(|s| !s.is_set(AppSettings::Hidden)) { + for sub in app + .get_subcommands() + .filter(|s| !s.is_set(AppSettings::Hidden)) + { roff.control("TP", []); let name = format!("{}-{}({})", app.get_name(), sub.get_name(), section);