usage-lib 3.2.0

Library for working with usage specs
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
use crate::docs::models::{Spec, SpecArg, SpecCommand, SpecFlag};
use crate::error::UsageErr;
use itertools::Itertools;
use roff::{bold, italic, roman, Roff};

/// Renderer for generating Unix man pages from Usage specifications
#[derive(Debug, Clone)]
pub struct ManpageRenderer {
    spec: Spec,
    section: u8,
}

impl ManpageRenderer {
    /// Create a new manpage renderer for the given spec
    pub fn new(spec: crate::Spec) -> Self {
        Self {
            spec: spec.into(),
            section: 1,
        }
    }

    /// Set the manual section number (default: 1)
    ///
    /// Common sections:
    /// - 1: User commands
    /// - 5: File formats
    /// - 7: Miscellaneous
    /// - 8: System administration commands
    pub fn with_section(mut self, section: u8) -> Self {
        self.section = section;
        self
    }

    /// Render the complete man page
    pub fn render(&self) -> Result<String, UsageErr> {
        let mut roff = Roff::new();

        // TH (Title Header) - program name, section, date, source, manual
        let section_str = self.section.to_string();
        roff.control(
            "TH",
            [self.spec.name.to_uppercase().as_str(), section_str.as_str()],
        );

        // NAME section
        self.render_name(&mut roff);

        // SYNOPSIS section
        self.render_synopsis(&mut roff);

        // DESCRIPTION section
        self.render_description(&mut roff);

        // Render the main command
        self.render_command(&mut roff, &self.spec.cmd, true);

        // Render detailed sections for each subcommand
        self.render_subcommand_details(&mut roff, &self.spec.cmd, &self.spec.bin);

        // EXAMPLES section (spec-level)
        if !self.spec.examples.is_empty() {
            roff.control("SH", ["EXAMPLES"]);
            for (i, example) in self.spec.examples.iter().enumerate() {
                // Add spacing between examples (but not before the first one)
                if i > 0 {
                    roff.control("PP", [] as [&str; 0]);
                }
                if let Some(header) = &example.header {
                    roff.text([bold(header)]);
                }
                if let Some(help) = &example.help {
                    roff.text([roman(help.as_str())]);
                }
                roff.control("PP", [] as [&str; 0]);
                roff.control("RS", ["4"]);
                roff.text([roman(example.code.as_str())]);
                roff.control("RE", [] as [&str; 0]);
            }
        }

        // AUTHOR section (if present)
        if let Some(author) = &self.spec.author {
            roff.control("SH", ["AUTHOR"]);
            roff.text([roman(author)]);
        }

        Ok(roff.to_roff())
    }

    fn render_name(&self, roff: &mut Roff) {
        roff.control("SH", ["NAME"]);
        let description = self
            .spec
            .about
            .as_deref()
            .unwrap_or("No description available");
        roff.text([roman(format!("{} - {}", self.spec.name, description))]);
    }

    fn render_synopsis(&self, roff: &mut Roff) {
        roff.control("SH", ["SYNOPSIS"]);

        let synopsis = self.build_synopsis(&self.spec.cmd, &self.spec.bin);
        roff.text([bold(&self.spec.bin), roman(" "), roman(&synopsis)]);
    }

    fn build_synopsis(&self, cmd: &SpecCommand, _prefix: &str) -> String {
        let mut parts = Vec::new();

        // Add flags summary
        if !cmd.flags.is_empty() {
            parts.push("[OPTIONS]".to_string());
        }

        // Add arguments
        for arg in &cmd.args {
            if arg.required {
                parts.push(format!("<{}>", arg.name));
            } else {
                parts.push(format!("[<{}>]", arg.name));
            }
            if arg.var {
                parts.push("...".to_string());
            }
        }

        // Add subcommands indicator
        if !cmd.subcommands.is_empty() {
            if cmd.subcommand_required {
                parts.push("<COMMAND>".to_string());
            } else {
                parts.push("[COMMAND]".to_string());
            }
        }

        parts.join(" ")
    }

    fn render_description(&self, roff: &mut Roff) {
        roff.control("SH", ["DESCRIPTION"]);

        if let Some(about) = &self.spec.about_long.as_ref().or(self.spec.about.as_ref()) {
            // Split into paragraphs and render each
            for paragraph in about.split("\n\n") {
                roff.text([roman(paragraph.trim())]);
                roff.control("PP", [] as [&str; 0]);
            }
        }

        if let Some(help) = &self
            .spec
            .cmd
            .help_long
            .as_ref()
            .or(self.spec.cmd.help.as_ref())
        {
            for paragraph in help.split("\n\n") {
                roff.text([roman(paragraph.trim())]);
                roff.control("PP", [] as [&str; 0]);
            }
        }
    }

    fn render_command(&self, roff: &mut Roff, cmd: &SpecCommand, is_root: bool) {
        // OPTIONS section
        if !cmd.flags.is_empty() {
            roff.control("SH", ["OPTIONS"]);
            for flag in &cmd.flags {
                self.render_flag(roff, flag);
            }
        }

        // ARGUMENTS section (if not root or has notable args)
        if !cmd.args.is_empty()
            && (!is_root
                || cmd
                    .args
                    .iter()
                    .any(|a| a.help.is_some() || a.help_long.is_some()))
        {
            if is_root {
                roff.control("SH", ["ARGUMENTS"]);
            }
            for arg in &cmd.args {
                self.render_arg(roff, arg);
            }
        }

        // SUBCOMMANDS section - show all subcommands recursively
        let all_subcommands = cmd.all_subcommands();
        if !all_subcommands.is_empty() {
            roff.control("SH", ["COMMANDS"]);
            self.render_all_subcommands(roff, &self.spec.cmd, "");
        }

        // EXAMPLES section
        if !cmd.examples.is_empty() {
            roff.control("SH", ["EXAMPLES"]);
            for (i, example) in cmd.examples.iter().enumerate() {
                // Add spacing between examples (but not before the first one)
                if i > 0 {
                    roff.control("PP", [] as [&str; 0]);
                }
                if let Some(header) = &example.header {
                    roff.text([bold(header)]);
                }
                if let Some(help) = &example.help {
                    roff.text([roman(help.as_str())]);
                }
                roff.control("PP", [] as [&str; 0]);
                roff.control("RS", ["4"]);
                roff.text([roman(example.code.as_str())]);
                roff.control("RE", [] as [&str; 0]);
            }
        }
    }

    fn render_flag(&self, roff: &mut Roff, flag: &SpecFlag) {
        roff.control("TP", [] as [&str; 0]);

        // Build flag usage line
        let mut flag_parts = Vec::new();

        for short in &flag.short {
            flag_parts.push(format!("-{}", short));
        }
        for long in &flag.long {
            flag_parts.push(format!("--{}", long));
        }

        let flag_usage = flag_parts.join(", ");

        if let Some(arg) = &flag.arg {
            roff.text([
                bold(&flag_usage),
                roman(" "),
                italic(format!("<{}>", arg.name)),
            ]);
        } else {
            roff.text([bold(&flag_usage)]);
        }

        // Flag help text
        if let Some(help) = &flag.help_long.as_ref().or(flag.help.as_ref()) {
            roff.text([roman(help.as_str())]);
        }

        // Default value
        if !flag.default.is_empty() {
            roff.control("RS", [] as [&str; 0]);
            let default_str = flag.default.join(", ");
            roff.text([italic("Default: "), roman(default_str.as_str())]);
            roff.control("RE", [] as [&str; 0]);
        }

        // Environment variable
        if let Some(env) = &flag.env {
            roff.control("RS", [] as [&str; 0]);
            roff.text([italic("Environment: "), bold(env.as_str())]);
            roff.control("RE", [] as [&str; 0]);
        }
    }

    fn render_arg(&self, roff: &mut Roff, arg: &SpecArg) {
        if arg.help.is_none() && arg.help_long.is_none() {
            return;
        }

        roff.control("TP", [] as [&str; 0]);
        roff.text([bold(format!("<{}>", arg.name))]);

        if let Some(help) = &arg.help_long.as_ref().or(arg.help.as_ref()) {
            roff.text([roman(help.as_str())]);
        }

        if !arg.default.is_empty() {
            roff.control("RS", [] as [&str; 0]);
            let default_str = arg.default.join(", ");
            roff.text([italic("Default: "), roman(default_str.as_str())]);
            roff.control("RE", [] as [&str; 0]);
        }
    }

    fn render_all_subcommands(&self, roff: &mut Roff, cmd: &SpecCommand, prefix: &str) {
        for (name, subcmd) in &cmd.subcommands {
            if subcmd.hide {
                continue;
            }

            let full_name = if prefix.is_empty() {
                name.to_string()
            } else {
                format!("{} {}", prefix, name)
            };

            self.render_subcommand_summary(roff, &full_name, subcmd);

            // Recursively render nested subcommands
            self.render_all_subcommands(roff, subcmd, &full_name);
        }
    }

    fn render_subcommand_details(&self, roff: &mut Roff, cmd: &SpecCommand, prefix: &str) {
        for (name, subcmd) in &cmd.subcommands {
            if subcmd.hide {
                continue;
            }

            let full_name = if prefix.is_empty() {
                name.to_string()
            } else {
                format!("{} {}", prefix, name)
            };

            // Only render detailed section if the subcommand has flags, args with help, or examples
            let has_flags = !subcmd.flags.is_empty();
            let has_documented_args = subcmd
                .args
                .iter()
                .any(|a| a.help.is_some() || a.help_long.is_some());
            let has_examples = !subcmd.examples.is_empty();

            if has_flags || has_documented_args || has_examples {
                // Section header for this subcommand
                roff.control("SH", [full_name.to_uppercase().as_str()]);

                // Description
                if let Some(help) = &subcmd.help_long.as_ref().or(subcmd.help.as_ref()) {
                    roff.text([roman(help.as_str())]);
                    roff.control("PP", [] as [&str; 0]);
                }

                // Synopsis
                let synopsis = self.build_synopsis(subcmd, &full_name);
                roff.text([
                    bold("Usage:"),
                    roman(" "),
                    roman(&full_name),
                    roman(" "),
                    roman(&synopsis),
                ]);
                roff.control("PP", [] as [&str; 0]);

                // Render flags if any
                if !subcmd.flags.is_empty() {
                    roff.text([bold("Options:")]);
                    roff.control("PP", [] as [&str; 0]);
                    for flag in &subcmd.flags {
                        self.render_flag(roff, flag);
                    }
                }

                // Render args if any with help
                if has_documented_args {
                    roff.text([bold("Arguments:")]);
                    roff.control("PP", [] as [&str; 0]);
                    for arg in &subcmd.args {
                        self.render_arg(roff, arg);
                    }
                }

                // Render examples if any
                if has_examples {
                    roff.text([bold("Examples:")]);
                    roff.control("PP", [] as [&str; 0]);
                    for (i, example) in subcmd.examples.iter().enumerate() {
                        // Add spacing between examples (but not before the first one)
                        if i > 0 {
                            roff.control("PP", [] as [&str; 0]);
                        }
                        if let Some(header) = &example.header {
                            roff.text([bold(header)]);
                        }
                        if let Some(help) = &example.help {
                            roff.text([roman(help.as_str())]);
                        }
                        roff.control("PP", [] as [&str; 0]);
                        roff.control("RS", ["4"]);
                        roff.text([roman(example.code.as_str())]);
                        roff.control("RE", [] as [&str; 0]);
                    }
                }
            }

            // Recursively render nested subcommands
            self.render_subcommand_details(roff, subcmd, &full_name);
        }
    }

    fn render_subcommand_summary(&self, roff: &mut Roff, name: &str, cmd: &SpecCommand) {
        roff.control("TP", [] as [&str; 0]);
        roff.text([bold(name)]);

        // Prefer help_long, fall back to help
        if let Some(help) = &cmd.help_long.as_ref().or(cmd.help.as_ref()) {
            // Take just the first line for the summary
            let first_line = help.lines().next().unwrap_or("");
            roff.text([roman(first_line)]);
        }

        // Show aliases if any
        if !cmd.aliases.is_empty() {
            let aliases = cmd.aliases.iter().join(", ");
            roff.control("RS", [] as [&str; 0]);
            roff.text([italic("Aliases: "), roman(aliases.as_str())]);
            roff.control("RE", [] as [&str; 0]);
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::Spec;

    #[test]
    fn test_basic_manpage() {
        let spec: Spec = r#"
            name "mycli"
            bin "mycli"
            about "A sample CLI tool"

            flag "-v --verbose" help="Enable verbose output"
            flag "-o --output <file>" help="Output file path"
            arg "<input>" help="Input file to process"
        "#
        .parse()
        .unwrap();

        let renderer = ManpageRenderer::new(spec);
        let output = renderer.render().unwrap();

        println!("Generated manpage:\n{}", output);

        // Basic checks
        assert!(output.contains(".TH MYCLI 1"));
        assert!(output.contains(".SH NAME"));
        assert!(output.contains(".SH SYNOPSIS"));
        assert!(output.contains(".SH DESCRIPTION"));
        assert!(output.contains(".SH OPTIONS"));
        assert!(output.contains("verbose"));
        assert!(output.contains("output"));
    }

    #[test]
    fn test_with_custom_section() {
        let spec: Spec = r#"
            name "myconfig"
            bin "myconfig"
            about "A configuration file format"
        "#
        .parse()
        .unwrap();

        let renderer = ManpageRenderer::new(spec).with_section(5);
        let output = renderer.render().unwrap();

        assert!(output.contains(".TH MYCONFIG 5"));
    }

    #[test]
    fn test_with_subcommands() {
        let spec: Spec = r#"
            name "git"
            bin "git"
            about "The Git version control system"

            cmd "clone" help="Clone a repository"
            cmd "commit" help="Record changes to the repository"
        "#
        .parse()
        .unwrap();

        let renderer = ManpageRenderer::new(spec);
        let output = renderer.render().unwrap();

        assert!(output.contains(".SH COMMANDS"));
        assert!(output.contains("clone"));
        assert!(output.contains("commit"));
    }

    #[test]
    fn test_arguments_with_only_long_help() {
        let spec: Spec = r#"
            name "mycli"
            bin "mycli"
            about "A CLI tool"

            arg "<input>" help_long="This is a long help text for the input argument"
        "#
        .parse()
        .unwrap();

        let renderer = ManpageRenderer::new(spec);
        let output = renderer.render().unwrap();

        // Should include ARGUMENTS section even though only help_long is present
        assert!(output.contains(".SH ARGUMENTS"));
        assert!(output.contains("<input>"));
        assert!(output.contains("long help text"));
    }

    #[test]
    fn test_subcommand_with_only_long_help() {
        let spec: Spec = r#"
            name "mycli"
            bin "mycli"
            about "A CLI tool"

            cmd "deploy" help_long="This is a detailed deployment command description that should appear in the summary"
        "#
        .parse()
        .unwrap();

        let renderer = ManpageRenderer::new(spec);
        let output = renderer.render().unwrap();

        // Should use help_long for subcommand summary
        assert!(output.contains("deploy"));
        assert!(output.contains("detailed deployment command"));
    }

    #[test]
    fn test_subcommand_prefers_long_over_short_help() {
        let spec: Spec = r#"
            name "mycli"
            bin "mycli"
            about "A CLI tool"

            cmd "test" help="Short help" help_long="Long detailed help that should be preferred"
        "#
        .parse()
        .unwrap();

        let renderer = ManpageRenderer::new(spec);
        let output = renderer.render().unwrap();

        // Should prefer help_long over help
        assert!(output.contains("Long detailed help"));
    }
}