Debian Codegraph @

src/bin/uudoc.rs

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