ctl-core 0.6.21

Shared clap chassis for the *ctl CLIs
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
//! Styled help extracted from Clap and rendered as a semantic document.

use std::io::{self, Write};

use clap::{Command, CommandFactory};

use crate::document::{Document, Role, Section, Table, Text};
use crate::render::RenderOptions;

const NARROW_HELP_WIDTH: u16 = 64;

/// Styled `-h` / `--help`. Returns `true` when help ran.
pub fn try_emit<C: CommandFactory>() -> io::Result<bool> {
    let raw = std::env::args_os().collect::<Vec<_>>();
    let color = crate::parser::parsed_output::<C>(&raw).color;
    try_emit_with_options::<C>(RenderOptions::new(color))
}

/// Styled help with rendering options supplied by the library owner.
pub fn try_emit_with_options<C: CommandFactory>(options: RenderOptions) -> io::Result<bool> {
    let args = std::env::args_os()
        .map(|arg| arg.to_string_lossy().into_owned())
        .collect::<Vec<_>>();
    try_emit_from_with_options::<C>(&args, options)
}

/// Same as [`try_emit`] with explicit argv.
pub fn try_emit_from<C: CommandFactory>(args: &[String]) -> io::Result<bool> {
    let raw = args
        .iter()
        .map(std::ffi::OsString::from)
        .collect::<Vec<_>>();
    let color = crate::parser::parsed_output::<C>(&raw).color;
    try_emit_from_with_options::<C>(args, RenderOptions::new(color))
}

/// Explicit-argv help with rendering options supplied by the owning library.
pub fn try_emit_from_with_options<C: CommandFactory>(
    args: &[String],
    options: RenderOptions,
) -> io::Result<bool> {
    let raw = args
        .iter()
        .map(std::ffi::OsString::from)
        .collect::<Vec<_>>();
    if !crate::parser::wants_help::<C>(&raw) {
        return Ok(false);
    }
    let command = help_command::<C>(args);
    let output = document(command).render(options);
    let mut stream = anstream::AutoStream::new(io::stdout().lock(), options.color().choice());
    stream.write_all(output.as_bytes())?;
    stream.flush()?;
    Ok(true)
}

/// Render root help to stderr with rendering options supplied by the owner.
pub fn emit_bare_with_options<C: CommandFactory>(options: RenderOptions) -> io::Result<()> {
    let output = document(C::command()).render(options);
    let mut stream = anstream::AutoStream::new(io::stderr().lock(), options.color().choice());
    stream.write_all(output.as_bytes())?;
    stream.flush()
}

fn help_command<C: CommandFactory>(args: &[String]) -> Command {
    let declared = C::command();
    let mut root = declared.clone();
    root.build();
    select_command(root, declared, args.get(1..).unwrap_or(&[]))
}

fn select_command(mut command: Command, mut declared: Command, args: &[String]) -> Command {
    for value in args {
        if value == "-h" || value == "--help" {
            break;
        }
        if value.starts_with('-') {
            continue;
        }
        let declared_next = declared
            .get_subcommands()
            .find(|subcommand| subcommand.get_name() == value)
            .cloned();
        if value == "help" && declared_next.is_none() {
            continue;
        }
        let Some(next) = command
            .get_subcommands()
            .find(|subcommand| subcommand.get_name() == value)
            .cloned()
        else {
            continue;
        };
        command = next;
        if let Some(next) = declared_next {
            declared = next;
        }
    }
    command
}

/// Extract one semantic help document from a Clap command.
#[must_use]
pub fn document(mut command: Command) -> Document {
    command.build();
    let usage = command.render_usage().to_string();
    let mut output =
        Document::new().paragraph(Text::new().span(Role::Heading, usage.trim().to_owned()));
    if let Some(about) = command.get_about() {
        output = output.paragraph(about.to_string());
    }

    let commands = command
        .get_subcommands()
        .filter(|subcommand| !subcommand.is_hide_set())
        .fold(Table::plain().token_column(0), |table, subcommand| {
            table.row([
                Text::plain(subcommand.get_name()),
                Text::plain(
                    subcommand
                        .get_about()
                        .map_or_else(String::new, ToString::to_string),
                ),
            ])
        });
    if !commands.is_empty() {
        output = output.section(Section::new(
            "Commands",
            Document::new().table(commands.stacked_below(NARROW_HELP_WIDTH, 1)),
        ));
    }

    let positionals = command
        .get_positionals()
        .filter(|arg| !arg.is_hide_set())
        .fold(Table::plain(), |table, arg| {
            table.row([
                Text::new(),
                Text::new().value(value_label(arg)),
                Text::new(),
                description(arg),
            ])
        });
    if !positionals.is_empty() {
        output = output.section(Section::new(
            "Arguments",
            Document::new().table(positionals.stacked_below(NARROW_HELP_WIDTH, 3)),
        ));
    }

    let mut headings = Vec::<String>::new();
    for arg in command
        .get_arguments()
        .filter(|arg| !arg.is_positional() && !arg.is_hide_set() && arg.get_id().as_str() != "help")
    {
        let heading = arg
            .get_help_heading()
            .map_or_else(|| "Options".to_owned(), ToString::to_string);
        if !headings.contains(&heading) {
            headings.push(heading);
        }
    }
    if command
        .get_arguments()
        .any(|arg| arg.get_id().as_str() == "help")
    {
        headings.push("Help".into());
    }
    for heading in headings {
        let rows = command
            .get_arguments()
            .filter(|arg| {
                if heading == "Help" {
                    return arg.get_id().as_str() == "help";
                }
                !arg.is_positional()
                    && !arg.is_hide_set()
                    && arg.get_id().as_str() != "help"
                    && arg.get_help_heading().map_or("Options", |value| value) == heading
            })
            .fold(Table::plain(), |table, arg| {
                table.row([
                    arg.get_short()
                        .map_or_else(Text::new, |value| Text::new().token(format!("-{value}"))),
                    arg.get_long()
                        .map_or_else(Text::new, |value| Text::new().token(format!("--{value}"))),
                    Text::new().value(value_label(arg)),
                    description(arg),
                ])
            });
        if !rows.is_empty() {
            output = output.section(Section::new(
                heading,
                Document::new().table(rows.stacked_below(NARROW_HELP_WIDTH, 3)),
            ));
        }
    }
    output
}

fn value_label(arg: &clap::Arg) -> String {
    if matches!(
        arg.get_action(),
        clap::ArgAction::SetTrue
            | clap::ArgAction::SetFalse
            | clap::ArgAction::Help
            | clap::ArgAction::Version
    ) {
        return String::new();
    }
    let names = arg
        .get_value_names()
        .map(|names| {
            names
                .iter()
                .map(ToString::to_string)
                .collect::<Vec<_>>()
                .join(" ")
        })
        .unwrap_or_default();
    let choices = arg
        .get_possible_values()
        .into_iter()
        .filter(|value| !value.is_hide_set())
        .map(|value| value.get_name().to_owned())
        .collect::<Vec<_>>();
    if choices.is_empty() {
        names
    } else {
        format!("[{}]", choices.join("|"))
    }
}

/// The help text, then `[default: …]` and `[env: …]` notes in muted style.
/// An option marked `hide_env` keeps its variable out of help, as in clap.
fn description(arg: &clap::Arg) -> Text {
    let description = arg.get_help().map_or_else(String::new, ToString::to_string);
    let defaults = arg
        .get_default_values()
        .iter()
        .map(|value| value.to_string_lossy())
        .collect::<Vec<_>>();
    let mut notes = Vec::new();
    if !defaults.is_empty()
        && !matches!(
            arg.get_action(),
            clap::ArgAction::SetTrue | clap::ArgAction::SetFalse
        )
    {
        notes.push(format!("[default: {}]", defaults.join(", ")));
    }
    if let Some(name) = arg.get_env().filter(|_| !arg.is_hide_env_set()) {
        notes.push(format!("[env: {}]", name.to_string_lossy()));
    }
    let mut separator = if description.is_empty() { "" } else { " " };
    let mut text = Text::plain(description);
    for note in notes {
        text = text.then(separator).muted(note);
        separator = " ";
    }
    text
}

#[cfg(test)]
mod tests {
    use clap::{CommandFactory, Parser};

    use super::{document, help_command, try_emit_from};
    use crate::color::ColorMode;
    use crate::flags::{DryRunArgs, OutputArgs};
    use crate::render::RenderOptions;

    #[derive(Parser)]
    #[command(version, about = "toy ctl", arg_required_else_help = true)]
    struct Toy {
        #[command(flatten)]
        output: OutputArgs,
        #[command(flatten)]
        dry: DryRunArgs,
        #[command(subcommand)]
        command: ToyCmd,
    }

    #[derive(clap::Subcommand)]
    enum ToyCmd {
        /// Show status.
        Status(StatusArgs),
        /// Group commands.
        Group {
            #[command(subcommand)]
            command: GroupCmd,
        },
    }

    #[derive(clap::Subcommand)]
    enum GroupCmd {
        /// Show a nested item.
        Show,
    }

    #[derive(clap::Args)]
    struct StatusArgs {
        /// Domain text that may begin with a hyphen.
        #[arg(short = 'm', long, allow_hyphen_values = true)]
        message: Option<String>,
    }

    #[test]
    fn document_lists_commands_and_flags() {
        let text = document(Toy::command()).render(RenderOptions::new(ColorMode::Never).width(80));
        assert!(text.contains("Commands"));
        assert!(text.contains("status"));
        assert!(text.contains("--dry-run"));
        assert!(text.contains("--format"));
        assert!(text.contains("--no-color"));
    }

    #[test]
    fn colorless_help_has_no_ansi() {
        let text = document(Toy::command()).render(RenderOptions::new(ColorMode::Never).width(80));
        assert!(!text.contains('\u{1b}'));
    }

    #[test]
    fn long_usage_wraps_to_the_render_width() {
        let command = clap::Command::new("refresh")
            .bin_name("forkctl patch refresh")
            .arg(
                clap::Arg::new("rewrite")
                    .long("rewrite-below")
                    .action(clap::ArgAction::SetTrue),
            )
            .arg(clap::Arg::new("name").value_name("NAME"));
        let text = document(command).render(RenderOptions::new(ColorMode::Never).width(40));
        assert!(text.lines().all(|line| line.chars().count() <= 40));
        assert_eq!(
            text.lines().take(2).collect::<Vec<_>>(),
            ["Usage: forkctl patch refresh [OPTIONS]", "[NAME]"]
        );
    }

    #[test]
    fn help_names_a_variable_unless_it_is_hidden() {
        let command = clap::Command::new("toy")
            .arg(clap::Arg::new("config").long("config").env("TOY_CONFIG"))
            .arg(
                clap::Arg::new("token")
                    .long("token")
                    .env("TOY_TOKEN")
                    .hide_env(true),
            );
        let text = document(command).render(RenderOptions::new(ColorMode::Never).width(80));
        assert!(text.contains("[env: TOY_CONFIG]"), "{text}");
        assert!(!text.contains("TOY_TOKEN"), "{text}");
    }

    #[test]
    fn help_subcommand_selects_the_requested_command() {
        let args = ["toy", "help", "status"].map(String::from);
        assert_eq!(help_command::<Toy>(&args).get_name(), "status");
    }

    #[test]
    fn subcommand_help_keeps_parent_usage_and_globals() {
        let command = help_command::<Toy>(&["toy", "status", "--help"].map(String::from));
        assert_eq!(command.get_bin_name(), Some("ctl-core status"));
        assert!(command.get_arguments().any(|arg| arg.get_id() == "format"));
    }

    #[test]
    fn nested_help_subcommand_selects_the_requested_command() {
        let args = ["toy", "group", "help", "show"].map(String::from);
        assert_eq!(help_command::<Toy>(&args).get_name(), "show");
    }

    #[test]
    fn try_emit_skips_without_help() {
        let args = ["toy", "status"]
            .into_iter()
            .map(String::from)
            .collect::<Vec<_>>();
        assert!(!try_emit_from::<Toy>(&args).unwrap());
    }

    #[test]
    fn try_emit_ignores_help_used_as_a_domain_value() {
        let args = ["toy", "status", "-m", "--help"]
            .into_iter()
            .map(String::from)
            .collect::<Vec<_>>();
        assert!(!try_emit_from::<Toy>(&args).unwrap());
    }

    #[test]
    fn try_emit_ignores_help_after_separator() {
        let args = ["toy", "status", "--", "--help"]
            .into_iter()
            .map(String::from)
            .collect::<Vec<_>>();
        assert!(!try_emit_from::<Toy>(&args).unwrap());
    }

    #[test]
    fn try_emit_does_not_claim_bare_invocation() {
        let args = ["toy"].map(String::from);
        assert!(!try_emit_from::<Toy>(&args).unwrap());
    }
}