Debian Codegraph @

src/bin/uudoc.rs

raw ◀ ▶
Source reconstructed at patch state 1 of 2 — not the installed (fully patched) source.
2 Debian patches touch this file
1 // This file is part of the uutils coreutils package.
2 //
3 // For the full copyright and license information, please view the LICENSE
4 // file that was distributed with this source code.
5
6 // spell-checker:ignore mangen tldr mandoc uppercasing uppercased manpages DESTDIR
7
8 use std::{
9 collections::HashMap,
10 ffi::OsString,
11 fs::File,
12 io::{self, Read, Seek, Write},
13 process,
14 };
15
16 use clap::{Arg, Command};
17 use clap_complete::Shell;
18 use clap_mangen::Man;
19 use fluent_syntax::{
20 ast::{
21 Entry, Expression, InlineExpression, Message, Pattern,
22 PatternElement::{Placeable, TextElement},
23 },
24 parser,
25 };
26 use jiff::Zoned;
27 use regex::Regex;
28 use textwrap::{fill, indent, termwidth};
29 use zip::ZipArchive;
30
31 use coreutils::validation;
32 use uucore::Args;
33 use uucore::locale::get_message;
34
35 include!(concat!(env!("OUT_DIR"), "/uutils_map.rs"));
36
37 /// Post-process a generated manpage to fix mandoc lint issues
38 ///
39 /// This function:
40 /// - Fixes the TH header by uppercasing command names and adding a proper date
41 /// - Removes trailing whitespace from all lines
42 /// - Fixes redundant .br paragraph macros that cause mandoc warnings
43 /// - Removes .br before empty lines to avoid "br before sp" warnings
44 /// - Removes .br after empty lines to avoid "br after sp" warnings
45 /// - Fixes escape sequences (e.g., \\\\0 to \\0) to avoid "undefined escape" warnings
46 fn post_process_manpage(manpage: String, date: &str) -> String {
47 // Only match TH headers that have at least a command name on the same line
48 // Use [ \t] instead of \s to avoid matching newlines
49 // Use a date format that satisfies mandoc (YYYY-MM-DD)
50
51 let th_regex = Regex::new(r"(?m)^\.TH[ \t]+([^ \t\n]+)(?:[ \t]+[^\n]*)?$").unwrap();
52 let mut result = th_regex
53 .replace_all(&manpage, |caps: &regex::Captures| {
54 // Add date to satisfy mandoc - date must be quoted
55 format!(".TH {} 1 \"{date}\"", caps[1].to_uppercase())
56 })
57 .to_string();
58
59 // Process lines: remove trailing whitespace and fix .br issues in a single pass
60 let lines: Vec<&str> = result.lines().map(str::trim_end).collect();
61 let mut fixed_lines: Vec<&str> = Vec::with_capacity(lines.len());
62
63 for (i, &line) in lines.iter().enumerate() {
64 if line == ".br" {
65 let preceded_by_empty_line = lines.get(i - 1).is_some_and(|l| l.is_empty());
66 let line_next = lines.get(i + 1);
67 let followed_by_empty_line = line_next.is_some_and(|l| l.is_empty());
68 let followed_by_br = line_next == Some(&".br");
69
70 if preceded_by_empty_line || followed_by_empty_line || followed_by_br {
71 // skip this ".br"
72 continue;
73 }
74 }
75
76 fixed_lines.push(line);
77 }
78
79 result = fixed_lines.join("\n");
80
81 // Fix escape sequence issues
82 // \\\\0 appears when trying to represent literal \0 string
83 // In man pages, use \e for literal backslash
84 result = result.replace("\\\\\\\\0", "\\e0");
85 result = result.replace("\\\\0", "\\e0");
86
87 if !result.ends_with('\n') {
88 result.push('\n');
89 }
90
91 result
92 }
93
94 /// Print usage information for uudoc
95 fn usage<T: Args>(utils: &UtilityMap<T>) {
96 println!("uudoc - Documentation generator for uutils coreutils");
97 println!();
98 println!("Usage: uudoc [command] [args]");
99 println!();
100 println!("Commands:");
101 println!(" (no command) Generate mdbook documentation (default)");
102 println!(" manpage <utility> Generate manpage for a utility");
103 println!(" completion <utility> <shell> Generate shell completions for a utility");
104 println!();
105 println!("Available utilities:");
106 let all_utilities = validation::get_all_utilities(utils);
107 let display_list = all_utilities.join(", ");
108 let width = std::cmp::min(termwidth(), 100) - 4 * 2;
109 println!("{}", indent(&fill(&display_list, width), " "));
110 }
111
112 /// Generates the coreutils app for the utility map
113 fn gen_coreutils_app<T: Args>(util_map: &UtilityMap<T>) -> Command {
114 let mut command = Command::new("coreutils");
115 for (name, (_, sub_app)) in util_map {
116 // Recreate a small subcommand with only the relevant info
117 // (name & short description)
118 let about = sub_app()
119 .get_about()
120 .expect("Could not get the 'about'")
121 .to_string();
122 let sub_app = Command::new(name).about(about);
123 command = command.subcommand(sub_app);
124 }
125 command
126 }
127
128 /// Generate the manpage for the utility in the first parameter
129 fn gen_manpage<T: Args>(
130 tldr: &mut Option<ZipArchive<File>>,
131 args: impl Iterator<Item = OsString>,
132 util_map: &UtilityMap<T>,
133 ) -> ! {
134 uucore::set_utility_is_second_arg();
135 let all_utilities = validation::get_all_utilities(util_map);
136
137 let matches = Command::new("manpage")
138 .about("Prints manpage to stdout")
139 .arg(
140 Arg::new("utility")
141 .value_parser(clap::builder::PossibleValuesParser::new(&all_utilities))
142 .required(true),
143 )
144 .get_matches_from(std::iter::once(OsString::from("manpage")).chain(args));
145
146 let utility = matches.get_one::<String>("utility").unwrap();
147 let (command, raw_examples) = if utility == "coreutils" {
148 (gen_coreutils_app(util_map), None)
149 } else {
150 validation::setup_localization_or_exit(utility);
151 let mut cmd = util_map.get(utility).unwrap().1();
152 cmd.set_bin_name(utility.clone());
153 let cmd = cmd.display_name(utility);
154 let raw = tldr.as_mut().and_then(|zip| {
155 get_zip_content(zip, &format!("pages/common/{utility}.md"))
156 .or_else(|| get_zip_content(zip, &format!("pages/linux/{utility}.md")))
157 });
158 (cmd, raw)
159 };
160
161 // Generate the manpage to a buffer first so we can post-process it
162 let mut buffer = Vec::new();
163 let man = Man::new(command);
164 man.render(&mut buffer).expect("Man page generation failed");
165 if let Some(content) = raw_examples {
166 use clap_mangen::roff::{Roff, bold, roman};
167 let mut roff = Roff::default();
168 roff.control("SH", ["EXAMPLES"]);
169 for line in content.lines().skip_while(|l| !l.starts_with('-')) {
170 if let Some(desc) = line.strip_prefix("- ") {
171 roff.text([roman(desc)]);
172 } else if line.starts_with('`') {
173 let cmd = strip_placeholders(line.trim_matches('`'));
174 roff.text([bold(cmd)]);
175 } else if line.is_empty() {
176 roff.control("PP", []);
177 }
178 }
179 roff.control("PP", []);
180 roff.text([roman(
181 "The examples are provided by the tldr-pages project <https://tldr.sh> under the CC BY 4.0 License. Please note that, as uutils is a work in progress, some examples might fail.",
182 )]);
183 roff.to_writer(&mut buffer)
184 .expect("Man page generation failed");
185 }
186
187 // Convert to string for processing
188 let manpage = String::from_utf8(buffer).expect("Invalid UTF-8 in manpage");
189
190 // Post-process the manpage to fix mandoc lint issues
191 let date = Zoned::now().strftime("%Y-%m-%d").to_string();
192 let processed_manpage = post_process_manpage(manpage, &date);
193
194 // Write the processed manpage to stdout
195 io::stdout()
196 .write_all(processed_manpage.as_bytes())
197 .unwrap();
198 io::stdout().flush().unwrap();
199 process::exit(0);
200 }
201
202 /// Generate shell completions for the utility in the first parameter
203 fn gen_completions<T: Args>(args: impl Iterator<Item = OsString>, util_map: &UtilityMap<T>) -> ! {
204 let all_utilities = validation::get_all_utilities(util_map);
205
206 let matches = Command::new("completion")
207 .about("Prints completions to stdout")
208 .arg(
209 Arg::new("utility")
210 .value_parser(clap::builder::PossibleValuesParser::new(&all_utilities))
211 .required(true),
212 )
213 .arg(
214 Arg::new("shell")
215 .value_parser(clap::builder::EnumValueParser::<Shell>::new())
216 .required(true),
217 )
218 .get_matches_from(std::iter::once(OsString::from("completion")).chain(args));
219
220 let utility = matches.get_one::<String>("utility").unwrap();
221 let shell = *matches.get_one::<Shell>("shell").unwrap();
222
223 let mut command = if utility == "coreutils" {
224 gen_coreutils_app(util_map)
225 } else {
226 validation::setup_localization_or_exit(utility);
227 util_map.get(utility).unwrap().1()
228 };
229 let bin_name = std::env::var("PROG_PREFIX").unwrap_or_default() + utility;
230
231 clap_complete::generate(shell, &mut command, bin_name, &mut io::stdout());
232 io::stdout().flush().unwrap();
233 process::exit(0);
234 }
235
236 /// # Errors
237 /// Returns an error if the writer fails.
238 #[allow(clippy::too_many_lines)]
239 fn main() -> io::Result<()> {
240 let args: Vec<OsString> = uucore::args_os_filtered().collect();
241
242 let mut tldr_zip = File::open("docs/tldr.zip")
243 .ok()
244 .and_then(|f| ZipArchive::new(f).ok());
245
246 // Check for manpage/completion commands first
247 if args.len() > 1 {
248 let command = args.get(1).and_then(|s| s.to_str()).unwrap_or_default();
249 match command {
250 "manpage" => {
251 let args_iter = args.into_iter().skip(2);
252 gen_manpage(
253 &mut tldr_zip,
254 args_iter,
255 &util_map::<Box<dyn Iterator<Item = OsString>>>(),
256 );
257 }
258 "completion" => {
259 let args_iter = args.into_iter().skip(2);
260 gen_completions(args_iter, &util_map::<Box<dyn Iterator<Item = OsString>>>());
261 }
262 "--help" | "-h" => {
263 usage(&util_map::<Box<dyn Iterator<Item = OsString>>>());
264 process::exit(0);
265 }
266 _ => {
267 eprintln!("Unknown command: {command}");
268 eprintln!("Use 'uudoc --help' for usage information.");
269 process::exit(1);
270 }
271 }
272 }
273 let utils = util_map::<Box<dyn Iterator<Item = OsString>>>();
274 // Initialize localization for uucore common strings (used by tldr example attribution)
275 let _ = uucore::locale::setup_localization("uudoc");
276 match std::fs::create_dir("docs/src/utils/") {
277 Err(e) if e.kind() == io::ErrorKind::AlreadyExists => Ok(()),
278 x => x,
279 }?;
280
281 println!("Writing initial info to SUMMARY.md");
282 let mut summary = File::create("docs/src/SUMMARY.md")?;
283
284 let _ = write!(
285 summary,
286 "# Summary\n\
287 \n\
288 [Introduction](index.md)\n\
289 * [Installation](installation.md)\n\
290 * [Build from source](build.md)\n\
291 * [Platform support](platforms.md)\n\
292 * [Contributing](CONTRIBUTING.md)\n\
293 \t* [Development](DEVELOPMENT.md)\n\
294 \t* [Code of Conduct](CODE_OF_CONDUCT.md)\n\
295 \t* [Localization](l10n.md)\n\
296 * [GNU test coverage](test_coverage.md)\n\
297 * [Extensions](extensions.md)\n\
298 \t* [Error diagnostics](extensions-errors.md)\n\
299 \n\
300 # Reference\n\
301 * [Multi-call binary](multicall.md)\n",
302 );
303
304 println!("Gathering utils per platform");
305 let utils_per_platform = {
306 let mut map = HashMap::new();
307 for (platform, features) in [
308 ("unix", "feat_os_unix"),
309 ("windows", "feat_os_windows"),
310 ("unix_android", "feat_os_unix_android"),
311 ] {
312 let platform_utils: Vec<String> = String::from_utf8(
313 process::Command::new("./util/show-utils.sh")
314 .arg(format!("--features={features}"))
315 .output()?
316 .stdout,
317 )
318 .unwrap()
319 .trim()
320 .split(' ')
321 .map(ToString::to_string)
322 .collect();
323 map.insert(platform, platform_utils);
324 }
325
326 // Linux is a special case because it can support selinux
327 let platform_utils: Vec<String> = String::from_utf8(
328 process::Command::new("./util/show-utils.sh")
329 .arg("--features=feat_os_unix feat_selinux")
330 .output()?
331 .stdout,
332 )
333 .unwrap()
334 .trim()
335 .split(' ')
336 .map(ToString::to_string)
337 .collect();
338 map.insert("linux", platform_utils);
339
340 map
341 };
342
343 let mut utils = utils.entries().collect::<Vec<_>>();
344 utils.sort();
345
346 println!("Writing util per platform table");
347 {
348 let mut platform_table_file = File::create("docs/src/platform_table.md").unwrap();
349
350 // sum, cksum, b2sum, etc. are all available on all platforms, but not in the data structure
351 // otherwise, we check the map for the util name.
352 let check_supported = |name: &str, platform: &str| {
353 if name.ends_with("sum") || utils_per_platform[platform].iter().any(|u| u == name) {
354 "✓"
355 } else {
356 " "
357 }
358 };
359 writeln!(
360 platform_table_file,
361 "| util | Linux | macOS | Windows | FreeBSD | Android |\n\
362 | ---------------- | ----- | ----- | ------- | ------- | ------- |"
363 )?;
364 for &(&name, _) in &utils {
365 if name == "[" {
366 continue;
367 }
368 // The alignment is not necessary, but makes the output a bit more
369 // pretty when viewed as plain markdown.
370 writeln!(
371 platform_table_file,
372 "| {:<16} | {:<5} | {:<5} | {:<7} | {:<7} | {:<7} |",
373 format!("**{name}**"),
374 check_supported(name, "linux"),
375 check_supported(name, "unix"),
376 check_supported(name, "windows"),
377 check_supported(name, "unix"),
378 check_supported(name, "unix_android"),
379 )?;
380 }
381 }
382
383 println!("Writing to utils");
384 for (&name, (_, command)) in utils {
385 let (utils_name, usage_name, command) = match name {
386 "[" => {
387 continue;
388 }
389 n => (n, n, command),
390 };
391 let p = format!("docs/src/utils/{usage_name}.md");
392
393 let fluent = File::open(format!("src/uu/{utils_name}/locales/en-US.ftl"))
394 .and_then(|mut f: File| {
395 let mut s = String::new();
396 f.read_to_string(&mut s)?;
397 Ok(s)
398 })
399 .ok();
400
401 if let Ok(f) = File::create(&p) {
402 MDWriter {
403 w: Box::new(f),
404 command: command(),
405 name: usage_name,
406 tldr_zip: &mut tldr_zip,
407 utils_per_platform: &utils_per_platform,
408 fluent,
409 fluent_key: utils_name.to_string(),
410 }
411 .markdown()?;
412 println!("Wrote to '{p}'");
413 } else {
414 println!("Error writing to {p}");
415 }
416 writeln!(summary, "* [{usage_name}](utils/{usage_name}.md)")?;
417 }
418 Ok(())
419 }
420
421 fn fix_usage(name: &str, usage: String) -> String {
422 match name {
423 "test" => {
424 // replace to [ but not the first two line
425 usage
426 .lines()
427 .enumerate()
428 .map(|(i, l)| {
429 if i > 1 {
430 l.replace("test", "[")
431 } else {
432 l.to_string()
433 }
434 })
435 .collect::<Vec<_>>()
436 .join("\n")
437 }
438 _ => usage,
439 }
440 }
441
442 struct MDWriter<'a, 'b> {
443 w: Box<dyn Write>,
444 command: Command,
445 name: &'a str,
446 tldr_zip: &'b mut Option<ZipArchive<File>>,
447 utils_per_platform: &'b HashMap<&'b str, Vec<String>>,
448 fluent: Option<String>,
449 fluent_key: String,
450 }
451
452 impl MDWriter<'_, '_> {
453 /// # Errors
454 /// Returns an error if the writer fails.
455 fn markdown(&mut self) -> io::Result<()> {
456 write!(self.w, "# {}\n\n", self.name)?;
457 self.additional()?;
458 self.usage()?;
459 self.about()?;
460 self.options()?;
461 self.after_help()?;
462 self.examples()
463 }
464
465 /// Extract value for a Fluent key from the .ftl content
466 fn extract_fluent_value(&self, key: &str) -> Option<String> {
467 let content = self.fluent.as_ref()?;
468 let resource = parser::parse(content.clone()).ok()?;
469
470 for entry in resource.body {
471 if let Entry::Message(Message {
472 id,
473 value: Some(Pattern { elements }),
474 ..
475 }) = entry
476 && id.name == key
477 {
478 // Simple text extraction - just concatenate text elements
479 let mut result = String::new();
480 for element in elements {
481 if let TextElement { ref value } = element {
482 result.push_str(value);
483 }
484 if let Placeable {
485 expression:
486 Expression::Inline(InlineExpression::StringLiteral { ref value }),
487 } = element
488 {
489 result.push_str(value);
490 }
491 }
492 return Some(result);
493 }
494 }
495 None
496 }
497
498 /// # Errors
499 /// Returns an error if the writer fails.
500 fn additional(&mut self) -> io::Result<()> {
501 writeln!(self.w, "<div class=\"additional\">")?;
502 self.platforms()?;
503 self.version()?;
504 writeln!(self.w, "</div>")
505 }
506
507 /// # Errors
508 /// Returns an error if the writer fails.
509 fn platforms(&mut self) -> io::Result<()> {
510 writeln!(self.w, "<div class=\"platforms\">")?;
511 for (feature, icon) in [
512 ("linux", "linux"),
513 // freebsd is disabled for now because mdbook does not use font-awesome 5 yet.
514 // ("unix", "freebsd"),
515 // macOS uses the same feature set as generic Unix.
516 ("unix", "apple"),
517 ("windows", "windows"),
518 ] {
519 if self.name.contains("sum")
520 || self.utils_per_platform[feature]
521 .iter()
522 .any(|u| u == self.name)
523 {
524 writeln!(self.w, "<i class=\"fa-brands fa-{icon}\"></i>")?;
525 }
526 }
527 writeln!(self.w, "</div>")?;
528
529 Ok(())
530 }
531
532 /// # Errors
533 /// Returns an error if the writer fails.
534 /// # Panics
535 /// Panics if the version is not found.
536 fn version(&mut self) -> io::Result<()> {
537 writeln!(
538 self.w,
539 "<div class=\"version\">v{}</div>",
540 self.command.render_version().split_once(' ').unwrap().1
541 )
542 }
543
544 /// # Errors
545 /// Returns an error if the writer fails.
546 fn usage(&mut self) -> io::Result<()> {
547 if let Some(usage) = self.extract_fluent_value(&format!("{}-usage", self.fluent_key)) {
548 let usage = fix_usage(self.name, usage);
549 writeln!(self.w, "\n```")?;
550 writeln!(self.w, "{usage}")?;
551 writeln!(self.w, "```")
552 } else {
553 Ok(())
554 }
555 }
556
557 /// # Errors
558 /// Returns an error if the writer fails.
559 fn about(&mut self) -> io::Result<()> {
560 if let Some(about) = self.extract_fluent_value(&format!("{}-about", self.fluent_key)) {
561 writeln!(self.w, "{about}")
562 } else {
563 Ok(())
564 }
565 }
566
567 /// # Errors
568 /// Returns an error if the writer fails.
569 fn after_help(&mut self) -> io::Result<()> {
570 if let Some(after_help) =
571 self.extract_fluent_value(&format!("{}-after-help", self.fluent_key))
572 {
573 writeln!(self.w, "\n\n{after_help}")
574 } else {
575 Ok(())
576 }
577 }
578
579 /// # Errors
580 /// Returns an error if the writer fails.
581 fn examples(&mut self) -> io::Result<()> {
582 if let Some(zip) = self.tldr_zip
583 && let Ok(examples) = write_zip_examples(zip, self.name, true)
584 {
585 writeln!(self.w, "{examples}")?;
586 }
587 Ok(())
588 }
589
590 /// # Errors
591 /// Returns an error if the writer fails.
592 fn options(&mut self) -> io::Result<()> {
593 writeln!(self.w)?;
594 writeln!(self.w, "## Options")?;
595 writeln!(self.w)?;
596 write!(self.w, "<dl>")?;
597 for arg in self.command.get_arguments() {
598 write!(self.w, "<dt>")?;
599 let mut first = true;
600 for l in arg.get_long_and_visible_aliases().unwrap_or_default() {
601 if first {
602 first = false;
603 } else {
604 write!(self.w, ", ")?;
605 }
606 write!(self.w, "<code>")?;
607 write!(self.w, "--{l}")?;
608 if let Some(names) = arg.get_value_names() {
609 write!(
610 self.w,
611 "={}",
612 names
613 .iter()
614 .map(|x| format!("&lt;{x}&gt;"))
615 .collect::<Vec<_>>()
616 .join(" ")
617 )?;
618 }
619 write!(self.w, "</code>")?;
620 }
621 for s in arg.get_short_and_visible_aliases().unwrap_or_default() {
622 if first {
623 first = false;
624 } else {
625 write!(self.w, ", ")?;
626 }
627 write!(self.w, "<code>")?;
628 write!(self.w, "-{s}")?;
629 if let Some(names) = arg.get_value_names() {
630 write!(
631 self.w,
632 " {}",
633 names
634 .iter()
635 .map(|x| format!("&lt;{x}&gt;"))
636 .collect::<Vec<_>>()
637 .join(" ")
638 )?;
639 }
640 write!(self.w, "</code>")?;
641 }
642 writeln!(self.w, "</dt>")?;
643 let help_text = arg.get_help().unwrap_or_default().to_string();
644 // Try to resolve Fluent key if it looks like one, otherwise use as-is
645 let resolved_help = if help_text.starts_with(&format!("{}-help-", self.fluent_key)) {
646 self.extract_fluent_value(&help_text).unwrap_or(help_text)
647 } else {
648 help_text
649 };
650 writeln!(
651 self.w,
652 "<dd>\n\n{}\n\n</dd>",
653 resolved_help.replace('\n', "<br />")
654 )?;
655 }
656 writeln!(self.w, "</dl>\n")
657 }
658 }
659
660 fn strip_placeholders(s: &str) -> String {
661 let mut result = s.to_string();
662 loop {
663 if let (Some(start), Some(rel_end)) = (result.find("{{"), result.find("}}")) {
664 if start < rel_end {
665 let inner = result[start + 2..rel_end].to_string();
666 result = format!("{}{}{}", &result[..start], inner, &result[rel_end + 2..]);
667 continue;
668 }
669 }
670 break;
671 }
672 result
673 }
674
675 /// # Panics
676 /// Panics if the archive is not ok
677 fn get_zip_content(archive: &mut ZipArchive<impl Read + Seek>, name: &str) -> Option<String> {
678 let mut s = String::new();
679 archive.by_name(name).ok()?.read_to_string(&mut s).unwrap();
680 Some(s)
681 }
682
683 /// Extract examples for tldr.zip. The file docs/tldr.zip must exists
684 ///
685 /// ```sh
686 /// curl https://tldr.sh/assets/tldr.zip -o docs/tldr.zip
687 /// ```
688 ///
689 /// # Errors
690 ///
691 /// Returns an error if the tldr.zip file cannot be opened or read
692 fn write_zip_examples(
693 archive: &mut ZipArchive<impl Read + Seek>,
694 name: &str,
695 output_markdown: bool,
696 ) -> io::Result<String> {
697 let content = if let Some(f) = get_zip_content(archive, &format!("pages/common/{name}.md")) {
698 f
699 } else if let Some(f) = get_zip_content(archive, &format!("pages/linux/{name}.md")) {
700 f
701 } else {
702 return Err(io::Error::new(
703 io::ErrorKind::NotFound,
704 format!("Could not find tldr examples for {name}"),
705 ));
706 };
707
708 match format_examples(content, output_markdown) {
709 Err(e) => Err(io::Error::other(format!(
710 "Failed to format the tldr examples of {name}: {e}"
711 ))),
712 Ok(s) => Ok(s),
713 }
714 }
715
716 /// Format examples using std::fmt::Write
717 fn format_examples(content: String, output_markdown: bool) -> Result<String, std::fmt::Error> {
718 use std::fmt::Write;
719 let mut s = String::new();
720 writeln!(s)?;
721 writeln!(s, "## Examples")?;
722 writeln!(s)?;
723 for line in content.lines().skip_while(|l| !l.starts_with('-')) {
724 if let Some(l) = line.strip_prefix("- ") {
725 writeln!(s, "{l}")?;
726 } else if line.starts_with('`') {
727 if output_markdown {
728 writeln!(s, "```shell\n{}\n```", line.trim_matches('`'))?;
729 } else {
730 writeln!(s, "{}", line.trim_matches('`'))?;
731 }
732 } else if line.is_empty() {
733 writeln!(s)?;
734 } else {
735 // println!("Not sure what to do with this line:");
736 // println!("{line}");
737 }
738 }
739 writeln!(s)?;
740 writeln!(s, "> {}", get_message("uudoc-tldr-attribution"))?;
741 writeln!(s, ">")?;
742 writeln!(s, "> {}", get_message("uudoc-tldr-disclaimer"))?;
743 Ok(s)
744 }
745
746 #[cfg(test)]
747 mod tests {
748 use super::*;
749
750 #[test]
751 fn test_post_process_manpage_fixes_th_header() {
752 // Test that command names are uppercased and date is removed
753 let input =
754 ".TH cat 1 \"cat (uutils coreutils) 0.7.0\"\n.SH NAME\ncat - concatenate files\n";
755 let expected = ".TH CAT 1 \"2024-01-01\"\n.SH NAME\ncat - concatenate files\n";
756
757 let result = post_process_manpage(input.to_string(), "2024-01-01");
758 assert_eq!(result, expected);
759 }
760
761 #[test]
762 fn test_post_process_manpage_removes_trailing_whitespace() {
763 // Test that trailing whitespace is removed from lines
764 let input = ".TH TEST 1 \nSome text with trailing spaces \n.SH SECTION \n";
765 let expected = ".TH TEST 1 \"2024-01-01\"\nSome text with trailing spaces\n.SH SECTION\n";
766
767 let result = post_process_manpage(input.to_string(), "2024-01-01");
768 assert_eq!(result, expected);
769 }
770
771 #[test]
772 fn test_post_process_manpage_fixes_double_br() {
773 // Test that redundant .br macros are removed
774 let input = ".TH TEST 1\n.br\n.br\nSome text\n";
775 let expected = ".TH TEST 1 \"2024-01-01\"\n.br\nSome text\n";
776
777 let result = post_process_manpage(input.to_string(), "2024-01-01");
778 assert_eq!(result, expected);
779 }
780
781 #[test]
782 fn test_post_process_manpage_fixes_br_with_empty_line() {
783 // Test that .br with empty line patterns are fixed
784 // Both .br macros should be removed (first because followed by empty, second because preceded by empty)
785 let input = ".TH TEST 1\n.br\n\n.br\nSome text\n";
786 let expected = ".TH TEST 1 \"2024-01-01\"\n\nSome text\n";
787
788 let result = post_process_manpage(input.to_string(), "2024-01-01");
789 assert_eq!(result, expected);
790 }
791
792 #[test]
793 fn test_post_process_manpage_preserves_single_br() {
794 // Test that single .br macros are preserved
795 let input = ".TH TEST 1\nLine 1\n.br\nLine 2\n";
796 let expected = ".TH TEST 1 \"2024-01-01\"\nLine 1\n.br\nLine 2\n";
797
798 let result = post_process_manpage(input.to_string(), "2024-01-01");
799 assert_eq!(result, expected);
800 }
801
802 #[test]
803 fn test_post_process_manpage_handles_mixed_case_command() {
804 // Test that mixed case command names are uppercased
805 let input = ".TH CaT 1 \"some version info\"\nContent\n";
806 let expected = ".TH CAT 1 \"2024-01-01\"\nContent\n";
807
808 let result = post_process_manpage(input.to_string(), "2024-01-01");
809 assert_eq!(result, expected);
810 }
811
812 #[test]
813 fn test_post_process_manpage_handles_no_th_header() {
814 // Test that manpages without TH headers are handled gracefully
815 let input = ".SH NAME\ntest - a test utility\n";
816 let expected = ".SH NAME\ntest - a test utility\n";
817
818 let result = post_process_manpage(input.to_string(), "2024-01-01");
819 assert_eq!(result, expected);
820 }
821
822 #[test]
823 fn test_post_process_manpage_complex_br_pattern() {
824 // Test complex .br patterns with multiple occurrences
825 let input =
826 ".TH TEST 1\nSection 1\n.br\n\n.br\nMiddle\n.br\n.br\nSection 2\n.br\n\n.br\nEnd\n";
827 // .br followed/preceded by empty lines should be removed, consecutive .br should have one removed
828 let expected = ".TH TEST 1 \"2024-01-01\"\nSection 1\n\nMiddle\n.br\nSection 2\n\nEnd\n";
829
830 let result = post_process_manpage(input.to_string(), "2024-01-01");
831 assert_eq!(result, expected);
832 }
833
834 #[test]
835 fn test_post_process_manpage_malformed_th_header() {
836 // Test that malformed TH headers don't cause panics and are handled gracefully
837 let input1 = ".TH\nContent\n"; // Missing command name
838 let expected1 = ".TH\nContent\n";
839 let result1 = post_process_manpage(input1.to_string(), "2024-01-01");
840 assert_eq!(result1, expected1);
841
842 // TH header with special characters
843 let input2 = ".TH test-cmd 1 \"version 1.0\"\nContent\n";
844 let expected2 = ".TH TEST-CMD 1 \"2024-01-01\"\nContent\n";
845 let result2 = post_process_manpage(input2.to_string(), "2024-01-01");
846 assert_eq!(result2, expected2);
847
848 // TH header at end of file without newline
849 let input3 = "Content\n.TH test 1";
850 let expected3 = "Content\n.TH TEST 1 \"2024-01-01\"\n";
851 let result3 = post_process_manpage(input3.to_string(), "2024-01-01");
852 assert_eq!(result3, expected3);
853
854 // Multiple TH headers (only first should be processed due to ^anchor)
855 let input4 = ".TH first 1\nMiddle\n.TH second 1\n";
856 let expected4 = ".TH FIRST 1 \"2024-01-01\"\nMiddle\n.TH SECOND 1 \"2024-01-01\"\n";
857 let result4 = post_process_manpage(input4.to_string(), "2024-01-01");
858 assert_eq!(result4, expected4);
859 }
860
861 #[test]
862 fn test_post_process_manpage_removes_br_before_empty_line() {
863 // Test that .br is removed when followed by empty line (which becomes .sp)
864 let input = ".TH TEST 1\nSome text\n.br\n\nMore text\n";
865 let expected = ".TH TEST 1 \"2024-01-01\"\nSome text\n\nMore text\n";
866
867 let result = post_process_manpage(input.to_string(), "2024-01-01");
868 assert_eq!(result, expected);
869 }
870
871 #[test]
872 fn test_post_process_manpage_complex_br_before_empty() {
873 // Test multiple .br before empty line patterns
874 let input = ".TH TEST 1\nSection 1\n.br\n\nSection 2\n.br\n\nSection 3\n";
875 let expected = ".TH TEST 1 \"2024-01-01\"\nSection 1\n\nSection 2\n\nSection 3\n";
876
877 let result = post_process_manpage(input.to_string(), "2024-01-01");
878 assert_eq!(result, expected);
879 }
880
881 #[test]
882 fn test_post_process_manpage_removes_br_after_empty_line() {
883 // Test that .br is removed when preceded by empty line (which becomes .sp)
884 let input = ".TH TEST 1\nSome text\n\n.br\nMore text\n";
885 let expected = ".TH TEST 1 \"2024-01-01\"\nSome text\n\nMore text\n";
886
887 let result = post_process_manpage(input.to_string(), "2024-01-01");
888 assert_eq!(result, expected);
889 }
890
891 #[test]
892 fn test_post_process_manpage_fixes_escape_sequences() {
893 // Test that \\\\0 and \\0 are fixed to \e0 (literal backslash-zero)
894 let input = ".TH TEST 1\nText with \\\\\\\\0 and \\\\0 escape\n";
895 let expected = ".TH TEST 1 \"2024-01-01\"\nText with \\e0 and \\e0 escape\n";
896
897 let result = post_process_manpage(input.to_string(), "2024-01-01");
898 assert_eq!(result, expected);
899 }
900 }