Debian Codegraph @

debian/rust-vendor/clap_mangen/src/lib.rs

raw
1 #![doc = include_str!("../README.md")]
2 #![doc(html_logo_url = "https://raw.githubusercontent.com/clap-rs/clap/master/assets/clap.png")]
3 #![cfg_attr(docsrs, feature(doc_cfg))]
4 #![forbid(unsafe_code)]
5 #![warn(missing_docs)]
6 #![warn(clippy::print_stderr)]
7 #![warn(clippy::print_stdout)]
8
9 mod render;
10
11 pub use roff;
12
13 use render::subcommand_heading;
14 use roff::{Roff, roman};
15 use std::io::Write;
16
17 /// A manpage writer
18 pub struct Man {
19 cmd: clap::Command,
20 title: String,
21 section: String,
22 date: String,
23 source: String,
24 manual: String,
25 }
26
27 /// Build a [`Man`]
28 impl Man {
29 /// Create a new manual page.
30 pub fn new(mut cmd: clap::Command) -> Self {
31 cmd.build();
32 let title = cmd
33 .get_display_name()
34 .unwrap_or_else(|| cmd.get_name())
35 .to_owned();
36 let section = "1".to_owned();
37 let date = "".to_owned();
38 let source = format!(
39 "{} {}",
40 cmd.get_name(),
41 cmd.get_version().unwrap_or_default()
42 );
43 let manual = "".to_owned();
44 Self {
45 cmd,
46 title,
47 section,
48 date,
49 source,
50 manual,
51 }
52 }
53
54 /// Override the default man page title, written in all caps
55 pub fn title(mut self, title: impl Into<String>) -> Self {
56 self.title = title.into();
57 self
58 }
59
60 /// Override the default section this man page is placed in
61 ///
62 /// Common values:
63 ///
64 /// - `"1"`: User Commands
65 /// - `"2"`: System Calls
66 /// - `"3"`: C Library Functions
67 /// - `"4"`: Devices and Special Files
68 /// - `"5"`: File Formats and Conventions
69 /// - `"6"`: Games et. al.
70 /// - `"7"`: Miscellanea
71 /// - `"8"`: System Administration tools and Daemons
72 pub fn section(mut self, section: impl Into<String>) -> Self {
73 self.section = section.into();
74 self
75 }
76
77 /// Override the default date for the last non-trivial change to this man page
78 ///
79 /// Dates should be written in the form `YYYY-MM-DD`.
80 pub fn date(mut self, date: impl Into<String>) -> Self {
81 self.date = date.into();
82 self
83 }
84
85 /// Override the default source your command
86 ///
87 /// For those few man-pages pages in Sections 1 and 8, probably you just want to write GNU.
88 pub fn source(mut self, source: impl Into<String>) -> Self {
89 self.source = source.into();
90 self
91 }
92
93 /// Override the default manual this page is a member of
94 pub fn manual(mut self, manual: impl Into<String>) -> Self {
95 self.manual = manual.into();
96 self
97 }
98 }
99
100 /// Handle [`Man`] in relation to files
101 impl Man {
102 /// Generate the filename of the manual page
103 #[must_use]
104 pub fn get_filename(&self) -> String {
105 format!(
106 "{}.{}",
107 self.cmd
108 .get_display_name()
109 .unwrap_or_else(|| self.cmd.get_name()),
110 self.section
111 )
112 }
113
114 /// [Renders](Man::render) the manual page and writes it to a file
115 pub fn generate_to(
116 &self,
117 out_dir: impl AsRef<std::path::Path>,
118 ) -> Result<std::path::PathBuf, std::io::Error> {
119 let filepath = out_dir.as_ref().join(self.get_filename());
120 let mut file = std::fs::File::create(&filepath)?;
121 self.render(&mut file)?;
122 file.flush()?;
123 Ok(filepath)
124 }
125 }
126
127 /// Generate manual page files for the command with all subcommands
128 pub fn generate_to(
129 cmd: clap::Command,
130 out_dir: impl AsRef<std::path::Path>,
131 ) -> Result<(), std::io::Error> {
132 fn generate(cmd: clap::Command, out_dir: &std::path::Path) -> Result<(), std::io::Error> {
133 for cmd in cmd.get_subcommands().filter(|s| !s.is_hide_set()).cloned() {
134 generate(cmd, out_dir)?;
135 }
136 Man::new(cmd).generate_to(out_dir)?;
137 Ok(())
138 }
139
140 let mut cmd = cmd.disable_help_subcommand(true);
141 cmd.build();
142 generate(cmd, out_dir.as_ref())
143 }
144
145 /// Generate ROFF output
146 impl Man {
147 /// Render a full manual page into the writer.
148 ///
149 /// If customization is needed, you can call the individual sections you want and mix them into
150 /// your own ROFF content.
151 pub fn render(&self, w: &mut dyn Write) -> Result<(), std::io::Error> {
152 let mut roff = Roff::default();
153 self._render_title(&mut roff);
154 self._render_name_section(&mut roff);
155 self._render_synopsis_section(&mut roff);
156 self._render_description_section(&mut roff);
157
158 if app_has_arguments(&self.cmd) {
159 self._render_options_section(&mut roff);
160 }
161
162 if app_has_subcommands(&self.cmd) {
163 self._render_subcommands_section(&mut roff);
164 }
165
166 if self.cmd.get_after_long_help().is_some() || self.cmd.get_after_help().is_some() {
167 self._render_extra_section(&mut roff);
168 }
169
170 if app_has_version(&self.cmd) {
171 self._render_version_section(&mut roff);
172 }
173
174 if self.cmd.get_author().is_some() {
175 self._render_authors_section(&mut roff);
176 }
177
178 roff.to_writer(w)
179 }
180
181 /// Render the title into the writer.
182 pub fn render_title(&self, w: &mut dyn Write) -> Result<(), std::io::Error> {
183 let mut roff = Roff::default();
184 self._render_title(&mut roff);
185 roff.to_writer(w)
186 }
187
188 fn _render_title(&self, roff: &mut Roff) {
189 roff.control("TH", self.title_args());
190 }
191
192 // Turn metadata into arguments for a .TH macro.
193 fn title_args(&self) -> Vec<&str> {
194 vec![
195 &self.title,
196 &self.section,
197 &self.date,
198 &self.source,
199 &self.manual,
200 ]
201 }
202
203 /// Render the NAME section into the writer.
204 pub fn render_name_section(&self, w: &mut dyn Write) -> Result<(), std::io::Error> {
205 let mut roff = Roff::default();
206 self._render_name_section(&mut roff);
207 roff.to_writer(w)
208 }
209
210 fn _render_name_section(&self, roff: &mut Roff) {
211 roff.control("SH", ["NAME"]);
212 render::about(roff, &self.cmd);
213 }
214
215 /// Render the SYNOPSIS section into the writer.
216 pub fn render_synopsis_section(&self, w: &mut dyn Write) -> Result<(), std::io::Error> {
217 let mut roff = Roff::default();
218 self._render_synopsis_section(&mut roff);
219 roff.to_writer(w)
220 }
221
222 fn _render_synopsis_section(&self, roff: &mut Roff) {
223 roff.control("SH", ["SYNOPSIS"]);
224 render::synopsis(roff, &self.cmd);
225 }
226
227 /// Render the DESCRIPTION section into the writer.
228 pub fn render_description_section(&self, w: &mut dyn Write) -> Result<(), std::io::Error> {
229 let mut roff = Roff::default();
230 self._render_description_section(&mut roff);
231 roff.to_writer(w)
232 }
233
234 fn _render_description_section(&self, roff: &mut Roff) {
235 roff.control("SH", ["DESCRIPTION"]);
236 render::description(roff, &self.cmd);
237 }
238
239 /// Render the OPTIONS section into the writer.
240 pub fn render_options_section(&self, w: &mut dyn Write) -> Result<(), std::io::Error> {
241 let mut roff = Roff::default();
242 self._render_options_section(&mut roff);
243 roff.to_writer(w)
244 }
245
246 fn _render_options_section(&self, roff: &mut Roff) {
247 let help_headings = self
248 .cmd
249 .get_arguments()
250 .filter(|a| !a.is_hide_set())
251 .filter_map(|arg| arg.get_help_heading())
252 .fold(vec![], |mut acc, header| {
253 if !acc.contains(&header) {
254 acc.push(header);
255 }
256
257 acc
258 });
259
260 let (args, mut args_with_heading) =
261 self.cmd
262 .get_arguments()
263 .filter(|a| !a.is_hide_set())
264 .partition::<Vec<_>, _>(|a| a.get_help_heading().is_none());
265
266 if !args.is_empty() {
267 roff.control("SH", ["OPTIONS"]);
268 render::options(roff, &args);
269 }
270
271 for heading in help_headings {
272 let args;
273 (args, args_with_heading) = args_with_heading
274 .into_iter()
275 .partition(|&a| a.get_help_heading() == Some(heading));
276
277 roff.control("SH", [heading.to_uppercase().as_str()]);
278 render::options(roff, &args);
279 }
280 }
281
282 /// Render the SUBCOMMANDS section into the writer.
283 pub fn render_subcommands_section(&self, w: &mut dyn Write) -> Result<(), std::io::Error> {
284 let mut roff = Roff::default();
285 self._render_subcommands_section(&mut roff);
286 roff.to_writer(w)
287 }
288
289 fn _render_subcommands_section(&self, roff: &mut Roff) {
290 let heading = subcommand_heading(&self.cmd);
291 roff.control("SH", [heading]);
292 render::subcommands(roff, &self.cmd, &self.section);
293 }
294
295 /// Render the EXTRA section into the writer.
296 pub fn render_extra_section(&self, w: &mut dyn Write) -> Result<(), std::io::Error> {
297 let mut roff = Roff::default();
298 self._render_extra_section(&mut roff);
299 roff.to_writer(w)
300 }
301
302 fn _render_extra_section(&self, roff: &mut Roff) {
303 roff.control("SH", ["EXTRA"]);
304 render::after_help(roff, &self.cmd);
305 }
306
307 /// Render the VERSION section into the writer.
308 pub fn render_version_section(&self, w: &mut dyn Write) -> Result<(), std::io::Error> {
309 let mut roff = Roff::default();
310 self._render_version_section(&mut roff);
311 roff.to_writer(w)
312 }
313
314 fn _render_version_section(&self, roff: &mut Roff) {
315 let version = roman(render::version(&self.cmd));
316 roff.control("SH", ["VERSION"]);
317 roff.text([version]);
318 }
319
320 /// Render the AUTHORS section into the writer.
321 pub fn render_authors_section(&self, w: &mut dyn Write) -> Result<(), std::io::Error> {
322 let mut roff = Roff::default();
323 self._render_authors_section(&mut roff);
324 roff.to_writer(w)
325 }
326
327 fn _render_authors_section(&self, roff: &mut Roff) {
328 let author = roman(self.cmd.get_author().unwrap_or_default());
329 roff.control("SH", ["AUTHORS"]);
330 roff.text([author]);
331 }
332 }
333
334 // Does the application have a version?
335 fn app_has_version(cmd: &clap::Command) -> bool {
336 cmd.get_version()
337 .or_else(|| cmd.get_long_version())
338 .is_some()
339 }
340
341 // Does the application have any command line arguments?
342 fn app_has_arguments(cmd: &clap::Command) -> bool {
343 cmd.get_arguments().any(|i| !i.is_hide_set())
344 }
345
346 // Does the application have any subcommands?
347 fn app_has_subcommands(cmd: &clap::Command) -> bool {
348 cmd.get_subcommands().any(|i| !i.is_hide_set())
349 }
350
351 #[doc = include_str!("../README.md")]
352 #[cfg(doctest)]
353 pub struct ReadmeDoctests;