Debian Codegraph @

src/bin/uudoc.rs

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