ctl-core 0.7.0

A framework for clap programs: typed results, help, and terminal or JSON output
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
//! Styled help extracted from Clap and rendered as a semantic document.
//!
//! [`App`] prints help for you. These functions serve a CLI that
//! drives its own lifecycle. [`document`] turns a Clap command into a
//! [`Document`], and the `try_emit` functions print it when the arguments
//! ask for help. Help uses the same renderer, theme, and width policy as
//! command output.
//!
//! ```
//! use clap::Parser;
//! use ctl_core::help::document;
//!
//! #[derive(Parser)]
//! #[command(name = "toy", about = "A toy")]
//! struct Cli {}
//!
//! let help = document(<Cli as clap::CommandFactory>::command());
//! assert!(!help.is_empty());
//! ```
#![cfg_attr(feature = "app", doc = "", doc = "[`App`]: crate::App")]
#![cfg_attr(not(feature = "app"), doc = "", doc = "[`App`]: crate#cargo-features")]

use std::io;

use clap::{Command, CommandFactory};
use ctl_term::Stream;

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

const NARROW_HELP_WIDTH: u16 = 64;

/// Print styled help to stdout when the process argv asks for it, and return
/// `true`. Return `false` and print nothing otherwise.
///
/// Colour comes from the `--color` and `--no-color` flags in argv. Use
/// [`try_emit_with_options`] to control the width and style policy.
///
/// # Errors
///
/// Returns the error from writing help to stdout.
///
/// # Panics
///
/// Panics when the command disables `-h/--help` or `-V/--version`.
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))
}

/// Like [`try_emit`], rendering with `options` in place of the defaults.
///
/// # Errors
///
/// Returns the error from writing help to stdout.
///
/// # Panics
///
/// Panics when the command disables `-h/--help` or `-V/--version`.
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)
}

/// Like [`try_emit`], reading `args` in place of the process argv. The first
/// item is the binary name.
///
/// # Errors
///
/// Returns the error from writing help to stdout.
///
/// # Panics
///
/// Panics when the command disables `-h/--help` or `-V/--version`.
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))
}

/// Like [`try_emit`], reading `args` and rendering with `options`.
///
/// # Errors
///
/// Returns the error from writing help to stdout.
///
/// # Panics
///
/// Panics when the command disables `-h/--help` or `-V/--version`.
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);
    }
    emit_selected::<C>(args, options)?;
    Ok(true)
}

/// Print the root command's help to stderr, as shown for a bare invocation of
/// a command that requires input.
///
/// Colour and width are decided for stderr, not stdout. Help printed after a
/// usage error then fits the terminal stderr writes to, even when stdout is a
/// pipe.
///
/// # Errors
///
/// Returns the error from writing help to stderr.
pub fn emit_bare_with_options<C: CommandFactory>(options: RenderOptions) -> io::Result<()> {
    options.print_for(Stream::Stderr, &document(C::command()))
}

/// Help for the command `args` select, to stdout, as a help request prints it.
pub(crate) fn emit_selected<C: CommandFactory>(
    args: &[String],
    options: RenderOptions,
) -> io::Result<()> {
    options.print_for(Stream::Stdout, &document(help_command::<C>(args)))
}

/// Help for the command `args` select, to stderr. Clap asks for it when a
/// command that requires an argument or a subcommand gets neither.
#[cfg(feature = "app")]
pub(crate) fn emit_selected_to_stderr<C: CommandFactory>(
    args: &[String],
    options: RenderOptions,
) -> io::Result<()> {
    options.print_for(Stream::Stderr, &document(help_command::<C>(args)))
}

fn help_command<C: CommandFactory>(args: &[String]) -> Command {
    let declared = C::command();
    let mut root = crate::parser::with_help(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
}

/// Build the help document of a Clap command.
///
/// The document holds the usage line, the about text, a `Commands` section,
/// an `Arguments` section, and one section per option help heading
/// (`Options` when an option names none). ctl-core's `-h/--help` flag and
/// `help` subcommand are added, and the command is built first, so derived
/// values such as the version flag are present. Hidden subcommands,
/// arguments, and options are left out.
///
/// # Panics
///
/// In a debug build, panics when Clap's `debug_assert` finds an invalid
/// command definition, as [`parser::verify`](crate::parser::verify) does.
#[must_use]
pub fn document(command: Command) -> Document {
    let mut command = crate::parser::with_help(command);
    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());
    }
}