clapdown 0.3.0

Generate well-structured Markdown documentation from a clap CLI.
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
//! The core recursive renderer.
//!
//! Everything funnels through [`render`], which walks the command tree and
//! writes headings whose level tracks nesting depth so the outline never skips
//! a level. Flavor-dependent pieces are isolated in small helpers so future
//! flavors can be added with minimal churn.

use std::fmt::Write;

use clap::{Arg, ArgAction, Command};

use crate::options::{Flavor, MetadataStyle, Options};

/// Render `root` to Markdown using `opts`.
pub(crate) fn render(root: &Command, opts: &Options) -> String {
    let mut buf = String::new();
    let path = vec![canonical_name(root)];

    if emits_metadata(opts) {
        write_yaml_metadata(&mut buf, &path, opts);
    }

    if opts.table_of_contents {
        buf.push_str("**Contents:**\n\n");
        write_toc(&mut buf, root, &path, 0);
        buf.push('\n');
    }

    render_command(&mut buf, root, &path, 0, opts);

    if opts.footer {
        buf.push_str("---\n\n");
        buf.push_str("_Generated by [clapdown](https://crates.io/crates/clapdown)._\n");
    }

    // Normalize to a single trailing newline.
    let trimmed = buf.trim_end();
    format!("{trimmed}\n")
}

/// Recursively render a command and its subcommands.
fn render_command(buf: &mut String, cmd: &Command, path: &[String], depth: usize, opts: &Options) {
    let level = opts.base_heading_level as usize + depth;

    // Heading. The root heading can be overridden by `title`, and is omitted
    // entirely when a YAML metadata block already carries the title.
    if depth != 0 || !emits_metadata(opts) {
        let heading = if depth == 0 {
            match &opts.title {
                Some(title) => title.clone(),
                None => format!("`{}`", path.join(" ")),
            }
        } else {
            format!("`{}`", path.join(" "))
        };
        write_heading(buf, level, &heading);
    }

    // Description: prefer the long about, fall back to the short about.
    if let Some(about) = cmd.get_long_about().or_else(|| cmd.get_about()) {
        let _ = writeln!(buf, "{about}\n");
    }

    // Usage.
    let _ = writeln!(buf, "**Usage:** `{}`\n", usage_line(cmd, path));

    // Aliases.
    if opts.aliases {
        let aliases: Vec<_> = cmd.get_visible_aliases().collect();
        if !aliases.is_empty() {
            let label = if aliases.len() == 1 {
                "Alias"
            } else {
                "Aliases"
            };
            let joined = aliases
                .iter()
                .map(|a| format!("`{a}`"))
                .collect::<Vec<_>>()
                .join(", ");
            let _ = writeln!(buf, "**{label}:** {joined}\n");
        }
    }

    // Arguments (positionals).
    let positionals: Vec<&Arg> = cmd
        .get_arguments()
        .filter(|a| a.is_positional() && !a.is_hide_set())
        .collect();
    if !positionals.is_empty() {
        write_heading(buf, level + 1, "Arguments");
        for arg in positionals {
            buf.push_str(&render_arg(arg, opts.flavor));
            buf.push('\n');
        }
    }

    // Options (everything non-positional except the auto help/version flags).
    let options: Vec<&Arg> = cmd
        .get_arguments()
        .filter(|a| !a.is_positional() && !a.is_hide_set())
        .filter(|a| a.get_id() != "help" && a.get_id() != "version")
        .collect();
    if !options.is_empty() {
        write_heading(buf, level + 1, "Options");
        for arg in options {
            buf.push_str(&render_arg(arg, opts.flavor));
            buf.push('\n');
        }
    }

    // Subcommands: each recurses one level deeper, so its heading is a sibling
    // of this command's Arguments/Options headings.
    for sub in cmd.get_subcommands().filter(|s| !s.is_hide_set()) {
        let mut child_path = path.to_vec();
        child_path.push(sub.get_name().to_string());
        render_command(buf, sub, &child_path, depth + 1, opts);
    }
}

/// Whether a Pandoc YAML metadata block is emitted for these options.
fn emits_metadata(opts: &Options) -> bool {
    opts.flavor == Flavor::Pandoc && opts.metadata
}

/// Write the leading Pandoc YAML metadata block: the document `title` followed
/// by any custom fields, in insertion order.
fn write_yaml_metadata(buf: &mut String, path: &[String], opts: &Options) {
    let title = opts.title.clone().unwrap_or_else(|| path.join(" "));
    buf.push_str("---\n");
    let _ = writeln!(buf, "title: {}", yaml_scalar(&title, MetadataStyle::Auto));
    for (key, value, style) in &opts.metadata_fields {
        // `title` is owned by `opts.title`; skip duplicates.
        if key == "title" {
            continue;
        }
        let _ = writeln!(buf, "{key}: {}", yaml_scalar(value, *style));
    }
    buf.push_str("---\n\n");
}

/// Preserve multiline strings with literal blocks so YAML cannot fold away
/// their line breaks.
fn yaml_scalar(value: &str, style: MetadataStyle) -> String {
    let needs_escapes = value.chars().any(|c| {
        (c.is_control() && !matches!(c, '\n' | '\t')) || matches!(c, '\u{2028}' | '\u{2029}')
    });
    if !needs_escapes && (style != MetadataStyle::Auto || value.contains('\n')) {
        return yaml_block(value, style);
    }
    if is_plain_scalar(value) {
        value.to_string()
    } else {
        let mut quoted = String::from("\"");
        for c in value.chars() {
            match c {
                '\\' => quoted.push_str("\\\\"),
                '"' => quoted.push_str("\\\""),
                '\n' => quoted.push_str("\\n"),
                '\r' => quoted.push_str("\\r"),
                '\t' => quoted.push_str("\\t"),
                c if c.is_control() || matches!(c, '\u{2028}' | '\u{2029}') => {
                    let _ = write!(quoted, "\\u{:04X}", c as u32);
                }
                c => quoted.push(c),
            }
        }
        if style != MetadataStyle::Auto && !value.is_empty() && !value.ends_with('\n') {
            quoted.push_str("\\n");
        }
        quoted.push('"');
        quoted
    }
}

fn yaml_block(value: &str, style: MetadataStyle) -> String {
    let indicator = if style == MetadataStyle::Folded {
        '>'
    } else {
        '|'
    };
    let trailing_newlines = value.chars().rev().take_while(|&c| c == '\n').count();
    let chomping =
        if trailing_newlines > 1 || (!value.is_empty() && value.trim_matches('\n').is_empty()) {
            "+"
        } else if trailing_newlines == 0 && style == MetadataStyle::Auto {
            "-"
        } else {
            ""
        };
    // YAML otherwise infers indentation from the content and can consume
    // spaces that belong to an indented Markdown code block.
    let indentation = if value
        .split('\n')
        .find(|line| !line.is_empty())
        .is_some_and(|line| line.starts_with([' ', '\t']))
    {
        "2"
    } else {
        ""
    };
    let mut block = format!("{indicator}{indentation}{chomping}");
    for line in value.split_terminator('\n') {
        let _ = write!(block, "\n  {line}");
    }
    block
}

/// Whether `value` is safe to emit as an unquoted YAML plain scalar.
fn is_plain_scalar(value: &str) -> bool {
    if value.is_empty() || value != value.trim() {
        return false;
    }
    let first = value.chars().next().unwrap();
    if "-?:,[]{}#&*!|>'\"%@`".contains(first) {
        return false;
    }
    if value.ends_with(':') || value.contains(": ") || value.contains(" #") {
        return false;
    }
    !value
        .chars()
        .any(|c| c.is_control() || matches!(c, '\u{2028}' | '\u{2029}'))
}

/// Write a heading, or a bold label if the level would exceed h6.
fn write_heading(buf: &mut String, level: usize, text: &str) {
    if level <= 6 {
        let _ = writeln!(buf, "{} {text}\n", "#".repeat(level));
    } else {
        let _ = writeln!(buf, "**{text}**\n");
    }
}

/// Render one argument using the target flavor's list syntax.
fn render_arg(arg: &Arg, flavor: Flavor) -> String {
    let term = arg_term(arg);
    let mut blocks: Vec<String> = Vec::new();

    if let Some(help) = arg.get_long_help().or_else(|| arg.get_help()) {
        blocks.push(help.to_string());
    }

    let defaults: Vec<String> = arg
        .get_default_values()
        .iter()
        .map(|v| format!("`{}`", v.to_string_lossy()))
        .collect();
    if !defaults.is_empty() {
        let label = if defaults.len() == 1 {
            "Default value"
        } else {
            "Default values"
        };
        blocks.push(format!("{label}: {}", defaults.join(", ")));
    }

    if !matches!(arg.get_action(), ArgAction::SetTrue | ArgAction::SetFalse) {
        let possible: Vec<_> = arg
            .get_possible_values()
            .into_iter()
            .filter(|pv| !pv.is_hide_set())
            .collect();
        if !possible.is_empty() {
            if possible.iter().any(|pv| pv.get_help().is_some()) {
                let mut list = String::from("Possible values:\n");
                for pv in &possible {
                    match pv.get_help() {
                        Some(help) => {
                            let _ = write!(list, "\n- `{}`: {help}", pv.get_name());
                        }
                        None => {
                            let _ = write!(list, "\n- `{}`", pv.get_name());
                        }
                    }
                }
                blocks.push(list);
            } else {
                let names = possible
                    .iter()
                    .map(|pv| format!("`{}`", pv.get_name()))
                    .collect::<Vec<_>>()
                    .join(", ");
                blocks.push(format!("Possible values: {names}"));
            }
        }
    }

    if flavor == Flavor::CommonMark {
        bullet(&term, &blocks)
    } else {
        definition(&term, &blocks)
    }
}

fn bullet(term: &str, blocks: &[String]) -> String {
    let mut out = format!("- **{term}**\n");
    for block in blocks {
        out.push('\n');
        for line in block.lines() {
            if !line.is_empty() {
                let _ = write!(out, "  {line}");
            }
            out.push('\n');
        }
    }
    out
}

/// Format the invocation term for an argument, e.g. `` `-o`, `--output <OUT>` ``.
fn arg_term(arg: &Arg) -> String {
    if arg.is_positional() {
        return format!("`{}`", positional_name(arg));
    }

    let mut tokens: Vec<String> = Vec::new();
    if let Some(short) = arg.get_short() {
        tokens.push(format!("-{short}"));
    }
    if let Some(long) = arg.get_long() {
        tokens.push(format!("--{long}"));
    }
    if takes_value(arg)
        && let Some(last) = tokens.last_mut()
    {
        let _ = write!(last, " <{}>", value_name(arg));
    }
    tokens
        .into_iter()
        .map(|t| format!("`{t}`"))
        .collect::<Vec<_>>()
        .join(", ")
}

/// Assemble a definition-list item: a term line followed by an indented,
/// possibly multi-block, definition.
fn definition(term: &str, blocks: &[String]) -> String {
    let mut out = String::new();
    let _ = writeln!(out, "{term}");

    let body = blocks.join("\n\n");
    let mut wrote_marker = false;
    for line in body.lines() {
        if !wrote_marker {
            if line.is_empty() {
                out.push_str(":\n");
            } else {
                let _ = writeln!(out, ":   {line}");
            }
            wrote_marker = true;
        } else if line.is_empty() {
            out.push('\n');
        } else {
            let _ = writeln!(out, "    {line}");
        }
    }

    // A term with no definition is not a valid definition list; emit an empty
    // definition marker so the structure holds.
    if !wrote_marker {
        out.push_str(":\n");
    }

    out
}

/// The display name for a positional, including a trailing `...` if variadic.
fn positional_name(arg: &Arg) -> String {
    let mut name = format!("<{}>", value_name(arg));
    if is_variadic(arg) {
        name.push_str("...");
    }
    name
}

/// The value placeholder for an argument (first value name, else the upper-cased id).
fn value_name(arg: &Arg) -> String {
    if let Some(names) = arg.get_value_names()
        && let Some(first) = names.first()
    {
        return first.to_string();
    }
    arg.get_id().as_str().to_uppercase()
}

/// Whether the argument consumes a value.
fn takes_value(arg: &Arg) -> bool {
    matches!(arg.get_action(), ArgAction::Set | ArgAction::Append)
}

/// Whether the argument accepts more than one value.
fn is_variadic(arg: &Arg) -> bool {
    arg.get_num_args()
        .map(|r| r.max_values() > 1)
        .unwrap_or(false)
}

/// Build the usage string, prefixing the parent command path.
fn usage_line(cmd: &Command, path: &[String]) -> String {
    let usage = cmd.clone().render_usage().to_string();
    let body = usage.strip_prefix("Usage: ").unwrap_or(&usage).trim();
    if path.len() > 1 {
        format!("{} {body}", path[..path.len() - 1].join(" "))
    } else {
        body.to_string()
    }
}

/// Resolve a command's display string.
fn canonical_name(cmd: &Command) -> String {
    cmd.get_display_name()
        .or_else(|| cmd.get_bin_name())
        .unwrap_or_else(|| cmd.get_name())
        .to_string()
}

/// Write a nested table-of-contents bullet list.
fn write_toc(buf: &mut String, cmd: &Command, path: &[String], indent: usize) {
    let text = path.join(" ");
    let anchor = slug(&format!("`{text}`"));
    let _ = writeln!(buf, "{}- [`{text}`](#{anchor})", "  ".repeat(indent));
    for sub in cmd.get_subcommands().filter(|s| !s.is_hide_set()) {
        let mut child_path = path.to_vec();
        child_path.push(sub.get_name().to_string());
        write_toc(buf, sub, &child_path, indent + 1);
    }
}

/// Slugify heading text the way mdBook builds heading anchors.
fn slug(text: &str) -> String {
    let mut out = String::new();
    for c in text.chars() {
        if c.is_alphanumeric() {
            out.extend(c.to_lowercase());
        } else if c == ' ' || c == '-' || c == '_' {
            out.push('-');
        }
    }
    out
}