diff --git a/PLAN.md b/PLAN.md index 6248c89b9..1b8f84526 100644 --- a/PLAN.md +++ b/PLAN.md @@ -540,7 +540,10 @@ Groups are the opposite case: `Command::get_groups`, `ArgGroup::get_args` and through KDL and the clap bridge and are honored by Rust and Go help output. - [x] **`next_line_help`.** Command-wide block layout survives typed metadata, KDL, the clap bridge, and both Rust and generated Go help renderers. -- [ ] **`help_template` and `flatten_help`.** +- [x] **`flatten_help`.** Visible subcommands can be expanded into their parent's + usage synopsis and help sections across typed Rust, KDL, the clap bridge, + and Rust and generated Go help. +- [ ] **`help_template`.** - [x] **`subcommand_help_heading` / `subcommand_value_name`.** Custom subcommand section labels and synopsis placeholders survive KDL, typed Rust, generated Go, and the clap bridge and are rendered by both help implementations. diff --git a/argv/src/help.rs b/argv/src/help.rs index e10098a47..eb0be6da6 100644 --- a/argv/src/help.rs +++ b/argv/src/help.rs @@ -114,7 +114,9 @@ fn help_structure( if !page_examples(spec, meta).is_empty() { headings.push("Examples".to_string()); } - if meta.subcommands.iter().any(|sub| !sub.hide) { + if meta.flatten_help { + flat_help_headings(&path[1.min(path.len())..], meta, &mut headings); + } else if meta.subcommands.iter().any(|sub| !sub.hide) { headings.push( meta.subcommand_help_heading .unwrap_or("Commands") @@ -182,6 +184,19 @@ fn help_structure( (headings, flag_usages, synopsis) } +fn flat_help_headings(path: &[&str], meta: &CommandMeta<'_>, headings: &mut Vec) { + let mut visible: Vec<_> = meta.subcommands.iter().filter(|sub| !sub.hide).collect(); + visible.sort_by_key(|sub| sub.cmd.name); + for sub in visible { + let mut sub_path = path.to_vec(); + sub_path.push(sub.cmd.name); + headings.push(sub_path.join(" ")); + if sub.flatten_help { + flat_help_headings(&sub_path, sub, headings); + } + } +} + fn styled_help( page: &str, style: Style, @@ -254,6 +269,14 @@ fn styled_help( /// assert_eq!(usage_line(&["mise", "use"], &META), "mise use [--force] "); /// ``` pub fn usage_line(path: &[&str], meta: &CommandMeta<'_>) -> String { + usage_line_with_subcommands(path, meta, true) +} + +fn usage_line_with_subcommands( + path: &[&str], + meta: &CommandMeta<'_>, + include_subcommands: bool, +) -> String { let mut out = String::new(); for (i, part) in path.iter().enumerate() { if i > 0 { @@ -299,7 +322,7 @@ pub fn usage_line(path: &[&str], meta: &CommandMeta<'_>) -> String { } } - if !meta.cmd.subcommands.is_empty() { + if include_subcommands && !meta.cmd.subcommands.is_empty() { let name = meta.subcommand_value_name.unwrap_or("SUBCOMMAND"); let _ = write!(out, " <{name}>"); } @@ -317,7 +340,27 @@ fn usage_section(out: &mut String, spec: &Spec<'_>, path: &[&str], meta: &Comman return; } } - let _ = writeln!(out, "Usage: {}", usage_line(path, meta)); + let mut visible: Vec<_> = meta.subcommands.iter().filter(|sub| !sub.hide).collect(); + visible.sort_by_key(|sub| sub.cmd.name); + if meta.flatten_help && !visible.is_empty() { + let mut lines = Vec::new(); + if !meta.subcommand_required || meta.cmd.args_conflicts_with_subcommands { + lines.push(usage_line_with_subcommands(path, meta, false)); + } + for sub in visible { + let mut sub_path = path.to_vec(); + sub_path.push(sub.cmd.name); + lines.push(usage_line(&sub_path, sub)); + } + if let Some((first, rest)) = lines.split_first() { + let _ = writeln!(out, "Usage: {first}"); + for line in rest { + let _ = writeln!(out, " {line}"); + } + } + } else { + let _ = writeln!(out, "Usage: {}", usage_line(path, meta)); + } } /// How one flag appears in the usage line: `-f --force`, plus its value if it takes one. @@ -615,7 +658,9 @@ pub fn short_help(spec: &Spec<'_>, path: &[&str], chain: &[&CommandMeta<'_>]) -> // The path without the binary, which is what a listed subcommand shows: usage-lib prints // `tool-alias get ` under `mise tool-alias`, the whole path from the root rather // than the child's own name. - commands_section(&mut out, &path[1.min(path.len())..], meta); + if !meta.flatten_help { + commands_section(&mut out, &path[1.min(path.len())..], meta); + } // The short page lines its columns up too. It did not: every description began directly // after the name it belonged to, so nothing in `-h` lined up with anything — and `-h` is @@ -737,6 +782,9 @@ pub fn short_help(spec: &Spec<'_>, path: &[&str], chain: &[&CommandMeta<'_>]) -> |_| None, |out, (f, usage)| short_entry(out, f, usage.clone()), ); + if meta.flatten_help { + flat_commands_short(&mut out, &path[1.min(path.len())..], meta); + } examples_section(&mut out, spec, meta); if let Some(after) = meta.after_help.or(spec.root.after_help) { let _ = writeln!(out, "\n{after}"); @@ -816,6 +864,98 @@ fn commands_section(out: &mut String, path: &[&str], meta: &CommandMeta<'_>) { } } +fn flat_commands_short(out: &mut String, path: &[&str], meta: &CommandMeta<'_>) { + let mut visible: Vec<_> = meta.subcommands.iter().filter(|sub| !sub.hide).collect(); + visible.sort_by_key(|sub| sub.cmd.name); + for sub in visible { + let mut sub_path = path.to_vec(); + sub_path.push(sub.cmd.name); + let _ = writeln!(out, "\n{}:", sub_path.join(" ")); + if let Some(about) = sub.about.filter(|about| !about.trim().is_empty()) { + let _ = writeln!(out, "{}", about.trim_end()); + } + + let args: Vec<_> = sub + .args + .iter() + .filter(|arg| !arg.hide && !arg.hide_short_help) + .collect(); + let flags: Vec<&FlagMeta<'_>> = sub + .flags + .iter() + .filter(|flag| !flag.flag.global && !flag.hide && !flag.hide_short_help) + .collect(); + let arg_col = args + .iter() + .map(|arg| arg_usage(arg).chars().count()) + .max() + .unwrap_or(0); + let flag_col = flags + .iter() + .map(|flag| column_usage(flag).chars().count()) + .max() + .unwrap_or(0); + for arg in args { + let usage = arg_usage(arg); + if let Some(help) = arg.help.filter(|help| !help.trim().is_empty()) { + if meta.next_line_help { + let _ = writeln!(out, " {usage}"); + write_indented(out, help, 4); + } else { + let _ = write!(out, " {usage:( out: &mut String, @@ -1044,7 +1184,9 @@ pub fn long_help(spec: &Spec<'_>, path: &[&str], chain: &[&CommandMeta<'_>]) -> } usage_section(&mut out, spec, path, meta); - long_commands_section(&mut out, &path[1.min(path.len())..], meta); + if !meta.flatten_help { + long_commands_section(&mut out, &path[1.min(path.len())..], meta); + } // One column width per section, over its visible entries — the same two the reference // computes, and separately, so a long flag does not push the arguments out. @@ -1145,6 +1287,9 @@ pub fn long_help(spec: &Spec<'_>, path: &[&str], chain: &[&CommandMeta<'_>]) -> ); }, ); + if meta.flatten_help { + flat_commands_long(&mut out, &path[1.min(path.len())..], meta, width); + } let examples = page_examples(spec, meta); if !examples.is_empty() { @@ -1332,6 +1477,96 @@ fn long_commands_section(out: &mut String, path: &[&str], meta: &CommandMeta<'_> ); } +fn flat_commands_long(out: &mut String, path: &[&str], meta: &CommandMeta<'_>, width: usize) { + let mut visible: Vec<_> = meta.subcommands.iter().filter(|sub| !sub.hide).collect(); + visible.sort_by_key(|sub| sub.cmd.name); + for sub in visible { + let mut sub_path = path.to_vec(); + sub_path.push(sub.cmd.name); + let _ = writeln!(out, "\n{}:", sub_path.join(" ")); + if let Some(about) = sub + .long_about + .or(sub.about) + .filter(|about| !about.trim().is_empty()) + { + let _ = writeln!(out, "{}", about.trim_end()); + } + + let args: Vec<_> = sub + .args + .iter() + .filter(|arg| !arg.hide && !arg.hide_long_help) + .collect(); + let flags: Vec<&FlagMeta<'_>> = sub + .flags + .iter() + .filter(|flag| !flag.flag.global && !flag.hide && !flag.hide_long_help) + .collect(); + let arg_col = args + .iter() + .map(|arg| arg_usage(arg).chars().count()) + .max() + .unwrap_or(0); + let flag_col = flags + .iter() + .map(|flag| column_usage(flag).chars().count()) + .max() + .unwrap_or(0); + for arg in args { + entry( + out, + &arg_usage(arg), + arg.long_help.or(arg.help), + arg_col, + width, + meta.next_line_help, + ); + long_annotations( + out, + if arg.hide_possible_values { + &[] + } else { + arg.choices + }, + if arg.hide_env { None } else { arg.env }, + if arg.hide_default_value { + &[] + } else { + arg.default + }, + ); + } + for flag in flags { + entry( + out, + &column_usage(flag), + flag.long_help.or(flag.help), + flag_col, + width, + meta.next_line_help, + ); + long_annotations( + out, + if flag.hide_possible_values { + &[] + } else { + flag.choices + }, + if flag.hide_env { None } else { flag.env }, + if flag.hide_default_value { + &[] + } else { + flag.default + }, + ); + } + if sub.flatten_help { + flat_commands_long(out, &sub_path, sub, width); + } + out.push('\n'); + } +} + /// The path and metadata for a command, found by identity within a spec. /// /// [`Error::Help`](crate::Error::Help) carries the `Command` the request was about, because the diff --git a/argv/src/spec.rs b/argv/src/spec.rs index 7a57ea3e7..a631dac87 100644 --- a/argv/src/spec.rs +++ b/argv/src/spec.rs @@ -726,6 +726,8 @@ pub struct CommandMeta<'a> { pub subcommand_value_name: Option<&'a str>, /// Put each argument, flag, and subcommand description on the following line. pub next_line_help: bool, + /// Expand each visible subcommand's summary and arguments into this command's help page. + pub flatten_help: bool, /// Fixed help width. Zero disables wrapping. pub term_width: Option, /// Maximum detected terminal width when `term_width` is unset. Zero disables the cap. @@ -770,6 +772,7 @@ impl CommandMeta<'_> { subcommand_help_heading: None, subcommand_value_name: None, next_line_help: false, + flatten_help: false, term_width: None, max_term_width: None, args_override_self: true, @@ -1221,6 +1224,9 @@ impl Spec<'_> { if self.root.next_line_help { writeln!(out, "next_line_help #true")?; } + if self.root.flatten_help { + writeln!(out, "flatten_help #true")?; + } if let Some(width) = self.root.term_width { writeln!(out, "term_width {width}")?; } @@ -1473,6 +1479,9 @@ fn write_command<'a>( if meta.next_line_help { out.push_str(" next_line_help=#true"); } + if meta.flatten_help { + out.push_str(" flatten_help=#true"); + } if let Some(width) = meta.term_width { write!(out, " term_width={width}")?; } diff --git a/clap_usage/src/report.rs b/clap_usage/src/report.rs index b85123c9b..fbcc7c542 100644 --- a/clap_usage/src/report.rs +++ b/clap_usage/src/report.rs @@ -12,8 +12,6 @@ pub enum FidelityFeature { NonUtf8Default, ValueArity, DistinctValueNames, - FlattenHelp, - NextLineHelp, DisableHelpFlag, DisableHelpSubcommand, DisableVersionFlag, @@ -75,11 +73,6 @@ fn visit(cmd: &Command, ancestors: &[String], losses: &mut BTreeSet TokenStream { let subcommand_help_heading = option_str(cli.subcommand_help_heading.as_deref()); let subcommand_value_name = option_str(cli.subcommand_value_name.as_deref()); let next_line_help = cli.next_line_help; + let flatten_help = cli.flatten_help; let term_width = option_usize(cli.term_width); let max_term_width = option_usize(cli.max_term_width); let usage = option_str(cli.usage.as_deref()); @@ -472,6 +473,7 @@ pub fn emit(cli: &Cli) -> TokenStream { subcommand_help_heading: #subcommand_help_heading, subcommand_value_name: #subcommand_value_name, next_line_help: #next_line_help, + flatten_help: #flatten_help, term_width: #term_width, max_term_width: #max_term_width, args_override_self: #args_override_self, @@ -3571,6 +3573,7 @@ pub fn emit_args(cli: &Cli) -> TokenStream { let subcommand_help_heading = option_str(cli.subcommand_help_heading.as_deref()); let subcommand_value_name = option_str(cli.subcommand_value_name.as_deref()); let next_line_help = cli.next_line_help; + let flatten_help = cli.flatten_help; let term_width = option_usize(cli.term_width); let max_term_width = option_usize(cli.max_term_width); let unknown_flags = unknown_flags_tokens(cli); @@ -3720,6 +3723,7 @@ pub fn emit_args(cli: &Cli) -> TokenStream { subcommand_help_heading: #subcommand_help_heading, subcommand_value_name: #subcommand_value_name, next_line_help: #next_line_help, + flatten_help: #flatten_help, term_width: #term_width, max_term_width: #max_term_width, args_override_self: #args_override_self, diff --git a/derive/src/lib.rs b/derive/src/lib.rs index 9775945c7..0ade813da 100644 --- a/derive/src/lib.rs +++ b/derive/src/lib.rs @@ -204,6 +204,8 @@ //! `verbatim_doc_comment` — preserve doc-comment line breaks and whitespace — //! `default_subcommand`, `multicall` — argv[0]'s basename selects a subcommand — //! `arg_required_else_help` — a selected command with no argv of its own shows short help — +//! `next_line_help` — put descriptions below each entry — `flatten_help` — expand visible +//! subcommands into the current help page — //! `dont_delimit_trailing_values` — preserve delimiters after the trailing boundary — //! `args_override_self = false` — reject repeated scalar flags instead of letting the later //! occurrence correct the earlier one — diff --git a/derive/src/model.rs b/derive/src/model.rs index 2c93945c3..07c5d6b64 100644 --- a/derive/src/model.rs +++ b/derive/src/model.rs @@ -125,6 +125,7 @@ pub struct Cli { pub subcommand_help_heading: Option, pub subcommand_value_name: Option, pub next_line_help: bool, + pub flatten_help: bool, pub term_width: Option, pub max_term_width: Option, /// Declared descriptions, for the case a doc comment cannot express: a long form that does @@ -587,6 +588,7 @@ impl Cli { subcommand_help_heading: None, subcommand_value_name: None, next_line_help: false, + flatten_help: false, term_width: None, max_term_width: None, about_attr: None, @@ -749,6 +751,7 @@ impl Cli { cli.subcommand_value_name = Some(string_value(&meta)?) } "next_line_help" => cli.next_line_help = flag_value(&meta)?, + "flatten_help" => cli.flatten_help = flag_value(&meta)?, "term_width" => cli.term_width = Some(int_value(&meta)?), "max_term_width" => cli.max_term_width = Some(int_value(&meta)?), "restart_token" => cli.restart_token = Some(string_value(&meta)?), @@ -763,7 +766,7 @@ impl Cli { "unknown option `{other}` on a struct; usage::Cli takes \ `name`, `name_spec`, `bin`, `bin_spec`, `version`, `version_spec`, `author`, `license`, `repository`, `usage`, `verbatim_doc_comment`, `unknown_flags`, \ `default_subcommand`, `multicall`, `no_binary_name`, `arg_required_else_help`, `dont_delimit_trailing_values`, `args_override_self`, `subcommand_negates_reqs`, `args_conflicts_with_subcommands`, `subcommand_precedence_over_arg`, `allow_missing_positional`, \ - `next_help_heading`, `subcommand_help_heading`, `next_line_help`, `term_width`, `max_term_width`, \ + `next_help_heading`, `subcommand_help_heading`, `next_line_help`, `flatten_help`, `term_width`, `max_term_width`, \ `subcommand_value_name`, `restart_token`, `mount` and \ `group` here, and the description comes from the doc \ comment" diff --git a/docs/rust/clap-compatibility.md b/docs/rust/clap-compatibility.md index 05d1ab8f3..9cecee509 100644 --- a/docs/rust/clap-compatibility.md +++ b/docs/rust/clap-compatibility.md @@ -116,7 +116,8 @@ the Rust declaration, not only from generated KDL, wherever the bridge column sa | `verbatim_doc_comment` | yes | n/a | yes | yes | yes | n/a | Commands, fields, and variants preserve line breaks and indentation when requested. | | `rename_all`, `rename_all_env` | yes | n/a | yes | yes | yes | n/a | Full clap casing vocabulary; bare `env` uses the environment casing policy. | | `next_line_help` | yes | yes | yes | yes | yes | yes | Put command, argument, and flag descriptions below their usage instead of beside it. | -| `help_template`, `flatten_help` | no | n/a | no | no | no | no | No equivalent yet. | +| `flatten_help` | yes | yes | yes | yes | yes | yes | Expand visible subcommands into their parent's usage synopsis and help page. | +| `help_template` | no | n/a | no | no | no | no | No equivalent yet. | | `term_width`, `max_term_width` | yes | yes | yes | yes | yes | no | Fixed width overrides a detected-width cap; clap exposes no bridge getters for these settings. | | help styles and color | n/a | n/a | n/a | yes | lossy | no | Help and diagnostics use automatic ANSI styles; clap's custom style palette is not portable. | | built-in help/version action and flag control | no | no | no | no | no | no | Custom actions and disabling or relocating built-ins are not represented. | diff --git a/docs/rust/help.md b/docs/rust/help.md index 71f81c1d3..24d25f3ff 100644 --- a/docs/rust/help.md +++ b/docs/rust/help.md @@ -54,6 +54,8 @@ convenience entry point for CLIs that want immediate print-and-exit behavior. - `help_heading` on a field groups it under a heading. - `next_line_help` on a command puts every argument, flag, and subcommand description beneath its usage instead of in an aligned column beside it. +- `flatten_help` replaces the command list with a synopsis and argument summary for every + visible subcommand. - `hide` removes an entry from help, docs, and completions while still parsing. The rendered output matches what usage-lib renders from the same spec — the two renderers are diff --git a/docs/rust/migrating-from-clap.md b/docs/rust/migrating-from-clap.md index 5413d4987..1bce31fc0 100644 --- a/docs/rust/migrating-from-clap.md +++ b/docs/rust/migrating-from-clap.md @@ -208,7 +208,8 @@ Command-level presentation settings keep their clap spellings: #[command( subcommand_help_heading = "Actions", subcommand_value_name = "ACTION", - next_line_help + next_line_help, + flatten_help )] struct Cli { #[command(subcommand)] diff --git a/docs/spec/reference/cmd.md b/docs/spec/reference/cmd.md index 75729f100..bc141bf84 100644 --- a/docs/spec/reference/cmd.md +++ b/docs/spec/reference/cmd.md @@ -11,6 +11,7 @@ cmd "config" hide=#true // hide command from docs and completions cmd "config" subcommand_required=#true // subcommand is not optional cmd "config" subcommand_help_heading="Actions" subcommand_value_name="ACTION" cmd "config" next_line_help=#true // put descriptions below each entry +cmd "config" flatten_help=#true // expand visible subcommands into this page // these are shown under -h cmd "config" before_help="shown before the command" diff --git a/go/argv/help.go b/go/argv/help.go index d5c0a5d9e..6b130ee4d 100644 --- a/go/argv/help.go +++ b/go/argv/help.go @@ -1,6 +1,9 @@ package argv -import "strings" +import ( + "sort" + "strings" +) // What a help page prints. // @@ -86,6 +89,8 @@ type Help struct { SubcommandHelpHeading string SubcommandValueName string NextLineHelp bool + FlattenHelp bool + SubcommandRequired bool // Examples are worked invocations, printed last. Examples []Example } @@ -119,6 +124,10 @@ const inlineLimit = 2 // Hidden entries are absent from the line as they are from the sections — help // describes what a user is invited to type. func UsageLine(path []string, cmd *Command, help HelpTable) string { + return usageLine(path, cmd, help, true) +} + +func usageLine(path []string, cmd *Command, help HelpTable, includeSubcommands bool) string { var out strings.Builder out.WriteString(strings.Join(path, " ")) @@ -177,7 +186,7 @@ func UsageLine(path []string, cmd *Command, help HelpTable) string { } } - if len(cmd.Subcommands) > 0 { + if includeSubcommands && len(cmd.Subcommands) > 0 { name := "SUBCOMMAND" if h := help.Lookup(cmd.Key); h != nil && h.SubcommandValueName != "" { name = h.SubcommandValueName @@ -187,6 +196,32 @@ func UsageLine(path []string, cmd *Command, help HelpTable) string { return out.String() } +func usageLines(path []string, cmd *Command, help HelpTable) []string { + h := help.Lookup(cmd.Key) + if h == nil || !h.FlattenHelp { + return []string{UsageLine(path, cmd, help)} + } + visible := make([]*Command, 0, len(cmd.Subcommands)) + for _, sub := range cmd.Subcommands { + if subHelp := help.Lookup(sub.Key); subHelp == nil || !subHelp.Hide { + visible = append(visible, sub) + } + } + if len(visible) == 0 { + return []string{UsageLine(path, cmd, help)} + } + sort.Slice(visible, func(i, j int) bool { return visible[i].Name < visible[j].Name }) + lines := make([]string, 0, len(visible)+1) + if !h.SubcommandRequired || cmd.ArgsConflictWithSubcommands { + lines = append(lines, usageLine(path, cmd, help, false)) + } + for _, sub := range visible { + subPath := append(append([]string{}, path...), sub.Name) + lines = append(lines, UsageLine(subPath, sub, help)) + } + return lines +} + // flagUsage is how one flag appears in the usage line: `-f --force`, plus its // value if it takes one. The line always offers every spelling, since nothing on // it is competing for a word. diff --git a/go/argv/page.go b/go/argv/page.go index 0725b9004..2b5216ea1 100644 --- a/go/argv/page.go +++ b/go/argv/page.go @@ -96,12 +96,20 @@ func ShortHelp(spec HelpSpec, path []string, chain []*Command, help HelpTable) s out.WriteString(about + "\n\n") } - out.WriteString("Usage: " + UsageLine(path, cmd, help) + "\n") + for i, line := range usageLines(path, cmd, help) { + if i == 0 { + out.WriteString("Usage: " + line + "\n") + } else { + out.WriteString(" " + line + "\n") + } + } // The path without the binary, which is what a listed subcommand shows: // usage-lib prints the whole path from the root rather than the child's own // name. - commandsSection(&out, path[min(1, len(path)):], cmd, help) + if meta == nil || !meta.FlattenHelp { + commandsSection(&out, path[min(1, len(path)):], cmd, help) + } args := visibleArgs(cmd, help, false) nextLineHelp := meta != nil && meta.NextLineHelp @@ -198,6 +206,9 @@ func ShortHelp(spec HelpSpec, path []string, chain []*Command, help HelpTable) s groupsSection(&out, "Global flags", len(inherited), func(int) string { return "" }, func(w *strings.Builder, i int) { entry(w, inherited[i]) }) + if meta != nil && meta.FlattenHelp { + flatCommandsShort(&out, path[min(1, len(path)):], cmd, help, nextLineHelp) + } examplesSection(&out, pageExamples(chain, help, meta)) @@ -277,6 +288,72 @@ func commandsSection(out *strings.Builder, path []string, cmd *Command, help Hel } } +func flatCommandsShort(out *strings.Builder, path []string, cmd *Command, help HelpTable, nextLine bool) { + visible := append([]*Command{}, cmd.Subcommands...) + sort.Slice(visible, func(i, j int) bool { return visible[i].Name < visible[j].Name }) + for _, sub := range visible { + h := help.Lookup(sub.Key) + if h != nil && h.Hide { + continue + } + subPath := append(append([]string{}, path...), sub.Name) + out.WriteString("\n" + strings.Join(subPath, " ") + ":\n") + if h != nil && strings.TrimSpace(h.Short) != "" { + out.WriteString(trimEnd(h.Short) + "\n") + } + + args := visibleArgs(sub, help, false) + flags := make([]*Flag, 0, len(sub.Flags)) + argCol := 0 + for _, a := range args { + argCol = max(argCol, width(argUsage(a, help.Lookup(a.Key)))) + } + flagCol := 0 + for _, f := range sub.Flags { + fh := help.Lookup(f.Key) + if f.Global || (fh != nil && (fh.Hide || fh.HideShortHelp)) { + continue + } + flags = append(flags, f) + flagCol = max(flagCol, width(columnUsage(f, allShown(f), help))) + } + for _, a := range args { + ah := help.Lookup(a.Key) + usage := argUsage(a, ah) + if text := helpText(ah); text != "" { + if nextLine { + out.WriteString(" " + usage + "\n") + writeIndented(out, text, 4) + } else { + out.WriteString(" " + pad(usage, argCol) + " " + text) + } + } else { + out.WriteString(" " + usage) + } + annotations(out, ah, true) + } + for _, f := range flags { + fh := help.Lookup(f.Key) + usage := columnUsage(f, allShown(f), help) + if text := helpText(fh); text != "" { + if nextLine { + out.WriteString(" " + usage + "\n") + writeIndented(out, text, 4) + } else { + out.WriteString(" " + pad(usage, flagCol) + " " + text) + } + } else { + out.WriteString(" " + usage) + } + annotations(out, fh, true) + } + if h != nil && h.FlattenHelp { + flatCommandsShort(out, subPath, sub, help, h.NextLineHelp) + } + out.WriteString("\n") + } +} + // groupsSection writes one section per heading, unheaded first, in the order the // headings first appear. func groupsSection(out *strings.Builder, defaultTitle string, n int, diff --git a/go/argv/page_long.go b/go/argv/page_long.go index dca9c57fe..100ede313 100644 --- a/go/argv/page_long.go +++ b/go/argv/page_long.go @@ -1,6 +1,9 @@ package argv -import "strings" +import ( + "sort" + "strings" +) // The page `--help` prints. // @@ -60,9 +63,17 @@ func LongHelp(spec HelpSpec, path []string, chain []*Command, help HelpTable) st out.WriteString(about + "\n\n") } - out.WriteString("Usage: " + UsageLine(path, cmd, help) + "\n") + for i, line := range usageLines(path, cmd, help) { + if i == 0 { + out.WriteString("Usage: " + line + "\n") + } else { + out.WriteString(" " + line + "\n") + } + } - longCommandsSection(&out, path[min(1, len(path)):], cmd, help) + if meta == nil || !meta.FlattenHelp { + longCommandsSection(&out, path[min(1, len(path)):], cmd, help) + } // One column width per section, over its visible entries — separately, so a // long flag does not push the arguments out. @@ -118,6 +129,9 @@ func LongHelp(spec HelpSpec, path []string, chain []*Command, help HelpTable) st groupsSection(&out, "Global flags", len(inherited), func(int) string { return "" }, func(w *strings.Builder, i int) { writeFlag(w, inherited[i]) }) + if meta != nil && meta.FlattenHelp { + flatCommandsLong(&out, path[min(1, len(path)):], cmd, help, nextLineHelp) + } if examples := pageExamples(chain, help, meta); len(examples) > 0 { out.WriteString("\nExamples:\n") @@ -192,6 +206,56 @@ func longCommandsSection(out *strings.Builder, path []string, cmd *Command, help out.WriteString(" help\n Print this message or the help of the given subcommand(s)\n") } +func flatCommandsLong(out *strings.Builder, path []string, cmd *Command, help HelpTable, nextLine bool) { + visible := append([]*Command{}, cmd.Subcommands...) + sort.Slice(visible, func(i, j int) bool { return visible[i].Name < visible[j].Name }) + for _, sub := range visible { + h := help.Lookup(sub.Key) + if h != nil && h.Hide { + continue + } + subPath := append(append([]string{}, path...), sub.Name) + out.WriteString("\n" + strings.Join(subPath, " ") + ":\n") + if about := firstOf(metaField(h, func(x *Help) string { return x.Long }), + metaField(h, func(x *Help) string { return x.Short })); strings.TrimSpace(about) != "" { + out.WriteString(trimEnd(about) + "\n") + } + + args := visibleArgs(sub, help, true) + flags := make([]*Flag, 0, len(sub.Flags)) + argCol := 0 + for _, a := range args { + argCol = max(argCol, width(argUsage(a, help.Lookup(a.Key)))) + } + flagCol := 0 + for _, f := range sub.Flags { + fh := help.Lookup(f.Key) + if f.Global || (fh != nil && (fh.Hide || fh.HideLongHelp)) { + continue + } + flags = append(flags, f) + flagCol = max(flagCol, width(columnUsage(f, allShown(f), help))) + } + for _, a := range args { + ah := help.Lookup(a.Key) + entry(out, argUsage(a, ah), firstOf(metaField(ah, func(x *Help) string { return x.Long }), + metaField(ah, func(x *Help) string { return x.Short })), argCol, nextLine) + longAnnotations(out, ah, true) + } + for _, f := range flags { + fh := help.Lookup(f.Key) + entry(out, columnUsage(f, allShown(f), help), firstOf( + metaField(fh, func(x *Help) string { return x.Long }), + metaField(fh, func(x *Help) string { return x.Short })), flagCol, nextLine) + longAnnotations(out, fh, true) + } + if h != nil && h.FlattenHelp { + flatCommandsLong(out, subPath, sub, help, h.NextLineHelp) + } + out.WriteString("\n") + } +} + // entry writes one flag or argument: its help in a column beside it, wrapped — or // indented underneath, where the text has line breaks of its own. func entry(out *strings.Builder, usage, help string, col int, nextLine bool) { diff --git a/go/argv/page_test.go b/go/argv/page_test.go index 058bb417b..f2d40d953 100644 --- a/go/argv/page_test.go +++ b/go/argv/page_test.go @@ -174,6 +174,47 @@ func TestNextLineHelp(t *testing.T) { } } +func TestFlattenHelp(t *testing.T) { + arg := &Arg{Name: "task", Key: 3, Required: true} + flag := &Flag{Name: "extraordinarily-long-flag", Key: 4, Longs: []string{"extraordinarily-long-flag"}} + deep := &Flag{Name: "deep", Key: 6, Longs: []string{"deep"}} + nested := &Command{Name: "nested", Key: 5, Flags: []*Flag{deep}} + sub := &Command{Name: "run", Key: 2, Args: []*Arg{arg}, Flags: []*Flag{flag}, Subcommands: []*Command{nested}} + root := &Command{Name: "ex", Key: 1, Subcommands: []*Command{sub}} + help := HelpTable{ + {Key: 1, FlattenHelp: true}, + {Key: 2, Short: "Run it", FlattenHelp: true, NextLineHelp: true}, + {Key: 3, Short: "Task name", Demanded: true}, + {Key: 4, Short: "Only show changes"}, + {Key: 5, Short: "Nested operation"}, + {Key: 6, Short: "Deep option"}, + } + + for _, page := range []string{ + ShortHelp(HelpSpec{Bin: "ex"}, []string{"ex"}, []*Command{root}, help), + LongHelp(HelpSpec{Bin: "ex"}, []string{"ex"}, []*Command{root}, help), + } { + for _, want := range []string{ + "Usage: ex\n ex run", + "\nrun:\nRun it", + "", + "--extraordinarily-long-flag", + "\nrun nested:\nNested operation", + "--deep\n Deep option", + } { + if !strings.Contains(page, want) { + t.Fatalf("missing %q in:\n%s", want, page) + } + } + if strings.Contains(page, "\nCommands:\n") { + t.Fatalf("flattened help still has a Commands section:\n%s", page) + } + if !strings.Contains(page, " Task name") { + t.Fatalf("a long flag stretched the argument column:\n%s", page) + } + } +} + // A description that ends in a break adds no blank line. // // clap's `long_about` often ends with one — a `///` block whose last line is diff --git a/go/internal/shadow/mise/tables.go b/go/internal/shadow/mise/tables.go index 1e5d38e5d..4a99433b8 100644 --- a/go/internal/shadow/mise/tables.go +++ b/go/internal/shadow/mise/tables.go @@ -4915,21 +4915,21 @@ var HelpText = argv.HelpTable{ {Key: CmdBootstrapApplySystemPlan, Hide: true}, {Key: CmdBootstrapInspectSystemFiles, Hide: true}, {Key: CmdBootstrapInspectFirewallPlan, Hide: true}, - {Key: CmdBootstrapAccounts, Short: "Manage Linux users and groups from `[bootstrap.users]` and `[bootstrap.groups]`"}, + {Key: CmdBootstrapAccounts, Short: "Manage Linux users and groups from `[bootstrap.users]` and `[bootstrap.groups]`", SubcommandRequired: true}, {Key: CmdBootstrapAccountsApply, Short: "Apply configured Linux users and groups"}, {Key: FlagBootstrapAccountsApplyDryRun, Short: "Print what would change without changing anything", Long: "Print what would change without changing anything"}, {Key: FlagBootstrapAccountsApplyYes, Short: "Skip the confirmation prompt", Long: "Skip the confirmation prompt"}, {Key: CmdBootstrapAccountsStatus, Short: "Show configured Linux user and group state"}, {Key: FlagBootstrapAccountsStatusJson, Short: "Output in JSON format", Long: "Output in JSON format"}, {Key: FlagBootstrapAccountsStatusMissing, Short: "Exit with code 1 when any account is not converged", Long: "Exit with code 1 when any account is not converged"}, - {Key: CmdBootstrapCompose, Short: "Manage Docker Compose projects from `[bootstrap.compose]`"}, + {Key: CmdBootstrapCompose, Short: "Manage Docker Compose projects from `[bootstrap.compose]`", SubcommandRequired: true}, {Key: CmdBootstrapComposeApply, Short: "Apply configured Docker Compose project state"}, {Key: FlagBootstrapComposeApplyDryRun, Short: "Print what would change without changing anything", Long: "Print what would change without changing anything"}, {Key: FlagBootstrapComposeApplyYes, Short: "Skip the confirmation prompt", Long: "Skip the confirmation prompt"}, {Key: CmdBootstrapComposeStatus, Short: "Show configured Docker Compose project state"}, {Key: FlagBootstrapComposeStatusJson, Short: "Output in JSON format", Long: "Output in JSON format"}, {Key: FlagBootstrapComposeStatusMissing, Short: "Exit with code 1 when any Compose project is not converged", Long: "Exit with code 1 when any Compose project is not converged"}, - {Key: CmdBootstrapDotfiles, Short: "Manage dotfiles from `[dotfiles]`"}, + {Key: CmdBootstrapDotfiles, Short: "Manage dotfiles from `[dotfiles]`", SubcommandRequired: true}, {Key: CmdBootstrapDotfilesAdd, Short: "Add or update dotfiles in `[dotfiles]`", Long: "Add or update dotfiles in `[dotfiles]`\n\nIf the target is already managed, this updates its source from the live\ntarget. Otherwise it creates a `[dotfiles]` entry and seeds the source\nunder `dotfiles.root` unless `--source` is provided.", AfterLongHelp: "Examples:\n\n $ mise bootstrap dotfiles add ~/.zshrc\n $ mise bootstrap dotfiles add --mode copy ~/.config/starship.toml\n $ mise bootstrap dotfiles add --source dotfiles/gitconfig ~/.gitconfig\n"}, {Key: FlagBootstrapDotfilesAddForce, Short: "Overwrite existing sources without prompting", Long: "Overwrite existing sources without prompting"}, {Key: FlagBootstrapDotfilesAddGlobal, Short: "Write to the global config", Long: "Write to the global config"}, @@ -4961,7 +4961,7 @@ var HelpText = argv.HelpTable{ {Key: FlagBootstrapDotfilesUnapplyDryRun, Short: "Print the actions that would run without writing anything", Long: "Print the actions that would run without writing anything"}, {Key: FlagBootstrapDotfilesUnapplyYes, Short: "Skip the confirmation prompt", Long: "Skip the confirmation prompt"}, {Key: ArgBootstrapDotfilesUnapplyTarget, Short: "Only unapply these targets", Long: "Only unapply these targets"}, - {Key: CmdBootstrapFiles, Short: "Manage privileged files and directories from `[bootstrap.files]` and `[bootstrap.directories]`"}, + {Key: CmdBootstrapFiles, Short: "Manage privileged files and directories from `[bootstrap.files]` and `[bootstrap.directories]`", SubcommandRequired: true}, {Key: CmdBootstrapFilesApply, Short: "Apply configured privileged files and directories"}, {Key: FlagBootstrapFilesApplyDryRun, Short: "Print what would change without changing anything", Long: "Print what would change without changing anything"}, {Key: FlagBootstrapFilesApplyYes, Short: "Skip the confirmation prompt", Long: "Skip the confirmation prompt"}, @@ -4970,65 +4970,65 @@ var HelpText = argv.HelpTable{ {Key: FlagBootstrapFilesStatusJson, Short: "Output in JSON format", Long: "Output in JSON format"}, {Key: FlagBootstrapFilesStatusMissing, Short: "Exit with code 1 when any resource is not converged", Long: "Exit with code 1 when any resource is not converged"}, {Key: FlagBootstrapFilesStatusPromptSecrets, Short: "Prompt securely for missing bootstrap secret inputs", Long: "Prompt securely for missing bootstrap secret inputs"}, - {Key: CmdBootstrapFirewall, Short: "Manage the Linux host firewall from `[bootstrap.linux.firewall]`"}, + {Key: CmdBootstrapFirewall, Short: "Manage the Linux host firewall from `[bootstrap.linux.firewall]`", SubcommandRequired: true}, {Key: CmdBootstrapFirewallApply, Short: "Apply the configured Linux host firewall"}, {Key: FlagBootstrapFirewallApplyDryRun, Short: "Print what would change without changing anything", Long: "Print what would change without changing anything"}, {Key: FlagBootstrapFirewallApplyYes, Short: "Skip the confirmation prompt", Long: "Skip the confirmation prompt"}, {Key: CmdBootstrapFirewallStatus, Short: "Show configured Linux host firewall state"}, {Key: FlagBootstrapFirewallStatusJson, Short: "Output in JSON format", Long: "Output in JSON format"}, {Key: FlagBootstrapFirewallStatusMissing, Short: "Exit with code 1 when the firewall is not converged", Long: "Exit with code 1 when the firewall is not converged"}, - {Key: CmdBootstrapLaunchd, Hide: true, Short: "Manage macOS LaunchAgents from `[bootstrap.macos.launchd.agents]`"}, + {Key: CmdBootstrapLaunchd, Hide: true, Short: "Manage macOS LaunchAgents from `[bootstrap.macos.launchd.agents]`", SubcommandRequired: true}, {Key: CmdBootstrapLaunchdApply}, {Key: FlagBootstrapLaunchdApplyDryRun, Short: "Print the commands that would run without running them", Long: "Print the commands that would run without running them"}, {Key: FlagBootstrapLaunchdApplyYes, Short: "Skip the confirmation prompt", Long: "Skip the confirmation prompt"}, {Key: CmdBootstrapLaunchdStatus}, {Key: FlagBootstrapLaunchdStatusJson, Short: "Output in JSON format", Long: "Output in JSON format"}, {Key: FlagBootstrapLaunchdStatusMissing, Short: "Exit with code 1 if any configured LaunchAgent is not in its desired state", Long: "Exit with code 1 if any configured LaunchAgent is not in its desired state"}, - {Key: CmdBootstrapLinux, Short: "Manage Linux bootstrap config from `[bootstrap.linux]`"}, - {Key: CmdBootstrapLinuxSystemdUnits, Short: "Manage systemd user services from `[bootstrap.linux.systemd.units]`"}, + {Key: CmdBootstrapLinux, Short: "Manage Linux bootstrap config from `[bootstrap.linux]`", SubcommandRequired: true}, + {Key: CmdBootstrapLinuxSystemdUnits, Short: "Manage systemd user services from `[bootstrap.linux.systemd.units]`", SubcommandRequired: true}, {Key: CmdBootstrapLinuxSystemdUnitsApply}, {Key: FlagBootstrapLinuxSystemdUnitsApplyDryRun, Short: "Print the commands that would run without running them", Long: "Print the commands that would run without running them"}, {Key: FlagBootstrapLinuxSystemdUnitsApplyYes, Short: "Skip the confirmation prompt", Long: "Skip the confirmation prompt"}, {Key: CmdBootstrapLinuxSystemdUnitsStatus}, {Key: FlagBootstrapLinuxSystemdUnitsStatusJson, Short: "Output in JSON format", Long: "Output in JSON format"}, {Key: FlagBootstrapLinuxSystemdUnitsStatusMissing, Short: "Exit with code 1 if any configured systemd user service is not in its desired state", Long: "Exit with code 1 if any configured systemd user service is not in its desired state"}, - {Key: CmdBootstrapMacos, Short: "Manage macOS bootstrap config from `[bootstrap.macos]`"}, - {Key: CmdBootstrapMacosDefaults, Short: "Manage macOS defaults from `[bootstrap.macos.defaults]`"}, + {Key: CmdBootstrapMacos, Short: "Manage macOS bootstrap config from `[bootstrap.macos]`", SubcommandRequired: true}, + {Key: CmdBootstrapMacosDefaults, Short: "Manage macOS defaults from `[bootstrap.macos.defaults]`", SubcommandRequired: true}, {Key: CmdBootstrapMacosDefaultsApply}, {Key: FlagBootstrapMacosDefaultsApplyDryRun, Short: "Print the commands that would run without running them", Long: "Print the commands that would run without running them"}, {Key: FlagBootstrapMacosDefaultsApplyYes, Short: "Skip the confirmation prompt", Long: "Skip the confirmation prompt"}, {Key: CmdBootstrapMacosDefaultsStatus}, {Key: FlagBootstrapMacosDefaultsStatusJson, Short: "Output in JSON format", Long: "Output in JSON format"}, {Key: FlagBootstrapMacosDefaultsStatusMissing, Short: "Exit with code 1 if any configured defaults are not in their desired state", Long: "Exit with code 1 if any configured defaults are not in their desired state"}, - {Key: CmdBootstrapMacosLaunchdAgents, Short: "Manage macOS LaunchAgents from `[bootstrap.macos.launchd.agents]`"}, + {Key: CmdBootstrapMacosLaunchdAgents, Short: "Manage macOS LaunchAgents from `[bootstrap.macos.launchd.agents]`", SubcommandRequired: true}, {Key: CmdBootstrapMacosLaunchdAgentsApply}, {Key: FlagBootstrapMacosLaunchdAgentsApplyDryRun, Short: "Print the commands that would run without running them", Long: "Print the commands that would run without running them"}, {Key: FlagBootstrapMacosLaunchdAgentsApplyYes, Short: "Skip the confirmation prompt", Long: "Skip the confirmation prompt"}, {Key: CmdBootstrapMacosLaunchdAgentsStatus}, {Key: FlagBootstrapMacosLaunchdAgentsStatusJson, Short: "Output in JSON format", Long: "Output in JSON format"}, {Key: FlagBootstrapMacosLaunchdAgentsStatusMissing, Short: "Exit with code 1 if any configured LaunchAgent is not in its desired state", Long: "Exit with code 1 if any configured LaunchAgent is not in its desired state"}, - {Key: CmdBootstrapMacosDefaults2, Hide: true, Short: "Manage macOS defaults from `[bootstrap.macos.defaults]`"}, + {Key: CmdBootstrapMacosDefaults2, Hide: true, Short: "Manage macOS defaults from `[bootstrap.macos.defaults]`", SubcommandRequired: true}, {Key: CmdBootstrapMacosDefaultsApply2}, {Key: FlagBootstrapMacosDefaultsApplyDryRun2, Short: "Print the commands that would run without running them", Long: "Print the commands that would run without running them"}, {Key: FlagBootstrapMacosDefaultsApplyYes2, Short: "Skip the confirmation prompt", Long: "Skip the confirmation prompt"}, {Key: CmdBootstrapMacosDefaultsStatus2}, {Key: FlagBootstrapMacosDefaultsStatusJson2, Short: "Output in JSON format", Long: "Output in JSON format"}, {Key: FlagBootstrapMacosDefaultsStatusMissing2, Short: "Exit with code 1 if any configured defaults are not in their desired state", Long: "Exit with code 1 if any configured defaults are not in their desired state"}, - {Key: CmdBootstrapMiseShellActivate, Short: "Manage mise shell activation from `[bootstrap.mise_shell_activate]`"}, + {Key: CmdBootstrapMiseShellActivate, Short: "Manage mise shell activation from `[bootstrap.mise_shell_activate]`", SubcommandRequired: true}, {Key: CmdBootstrapMiseShellActivateApply}, {Key: FlagBootstrapMiseShellActivateApplyDryRun, Short: "Print the actions that would run without writing anything", Long: "Print the actions that would run without writing anything"}, {Key: FlagBootstrapMiseShellActivateApplyYes, Short: "Skip the confirmation prompt", Long: "Skip the confirmation prompt"}, {Key: CmdBootstrapMiseShellActivateStatus}, {Key: FlagBootstrapMiseShellActivateStatusJson, Short: "Output in JSON format", Long: "Output in JSON format"}, {Key: FlagBootstrapMiseShellActivateStatusMissing, Short: "Exit with code 1 if any configured shell activation is not in its desired state", Long: "Exit with code 1 if any configured shell activation is not in its desired state"}, - {Key: CmdBootstrapPackages, Short: "Manage bootstrap system packages from `[bootstrap.packages]`"}, + {Key: CmdBootstrapPackages, Short: "Manage bootstrap system packages from `[bootstrap.packages]`", SubcommandRequired: true}, {Key: CmdBootstrapPackagesApply, Short: "Apply system packages from `[bootstrap.packages]`", Long: "Apply system packages from `[bootstrap.packages]`\n\nChecks which configured packages are missing and installs them with the\nsystem package manager. Built-in system managers may elevate with sudo when\nnot running as root (see `system_packages.sudo`); package plugins never do.\n\nPackages can also be given explicitly in `manager:package` form (e.g.\n`apk:zlib-dev`, `apt:curl`, `brew:jq`); they are installed whether or not they appear in\nthe config. Explicit packages and `--manager` scope the run to packages\nonly. `install` is accepted as an alias for this command.", VisibleAliases: []string{"i"}, AfterLongHelp: "Examples:\n\n $ mise bootstrap packages apply\n $ mise bootstrap packages apply apk:zlib-dev apt:curl brew:jq brew-cask:firefox flatpak:org.mozilla.firefox mas:497799835\n $ mise bootstrap packages apply --dry-run\n $ mise bootstrap packages apply --manager apt --yes\n"}, {Key: FlagBootstrapPackagesApplyManager, ValueName: "MANAGER", ValueDemanded: true, Short: "Only install packages for this built-in or plugin manager", Long: "Only install packages for this built-in or plugin manager"}, {Key: FlagBootstrapPackagesApplyDryRun, Short: "Print the commands that would run without running them", Long: "Print the commands that would run without running them"}, {Key: FlagBootstrapPackagesApplyYes, Short: "Skip the confirmation prompt", Long: "Skip the confirmation prompt"}, {Key: FlagBootstrapPackagesApplyUpdate, Short: "Refresh package manager metadata first (apk: `--update-cache`, apt: `apt-get update`)", Long: "Refresh package manager metadata first (apk: `--update-cache`, apt: `apt-get update`)"}, {Key: ArgBootstrapPackagesApplyPackage, Short: "Packages in `manager:package` form; defaults to everything configured in [bootstrap.packages]", Long: "Packages in `manager:package` form; defaults to everything configured in [bootstrap.packages]"}, - {Key: CmdBootstrapPackagesBrew, Short: "Manage Homebrew taps used by bootstrap packages", Long: "Manage Homebrew taps used by bootstrap packages\n\nThese commands edit `[bootstrap.brew.taps]` so tapped formulae and casks\ncan be fetched directly by mise without a Homebrew installation."}, + {Key: CmdBootstrapPackagesBrew, Short: "Manage Homebrew taps used by bootstrap packages", Long: "Manage Homebrew taps used by bootstrap packages\n\nThese commands edit `[bootstrap.brew.taps]` so tapped formulae and casks\ncan be fetched directly by mise without a Homebrew installation.", SubcommandRequired: true}, {Key: CmdBootstrapPackagesBrewTap, Short: "Add a Homebrew tap URL to [bootstrap.brew.taps]", AfterLongHelp: "Examples:\n\n $ mise bootstrap packages brew tap railwaycat/emacsmacport\n $ mise bootstrap packages brew tap acme/tools https://github.com/acme/homebrew-tools.git\n"}, {Key: FlagBootstrapPackagesBrewTapLocal, Short: "Write to the local config instead of the global config", Long: "Write to the local config instead of the global config"}, {Key: FlagBootstrapPackagesBrewTapDryRun, Short: "Print the config change without writing it", Long: "Print the config change without writing it"}, @@ -5070,7 +5070,7 @@ var HelpText = argv.HelpTable{ {Key: FlagBootstrapPlanJson, Short: "Output a stable machine-readable plan in JSON format", Long: "Output a stable machine-readable plan in JSON format"}, {Key: FlagBootstrapPlanDetailedExitcode, Short: "Exit 2 when the plan contains changes, 0 when unchanged, and 1 on errors", Long: "Exit 2 when the plan contains changes, 0 when unchanged, and 1 on errors"}, {Key: FlagBootstrapPlanPromptSecrets, Short: "Prompt securely for missing bootstrap secret inputs", Long: "Prompt securely for missing bootstrap secret inputs"}, - {Key: CmdBootstrapPlugins, Short: "Manage package manager plugins declared in `[bootstrap.plugins]`"}, + {Key: CmdBootstrapPlugins, Short: "Manage package manager plugins declared in `[bootstrap.plugins]`", SubcommandRequired: true}, {Key: CmdBootstrapPluginsApply}, {Key: FlagBootstrapPluginsApplyDryRun, Short: "Print what would happen without installing plugins", Long: "Print what would happen without installing plugins"}, {Key: CmdBootstrapPluginsStatus}, @@ -5098,7 +5098,7 @@ var HelpText = argv.HelpTable{ {Key: FlagBootstrapRemoteUpdate, Short: "Refresh package manager metadata and update configured repos remotely", Long: "Refresh package manager metadata and update configured repos remotely"}, {Key: FlagBootstrapRemoteYes, Short: "Skip remote confirmation prompts", Long: "Skip remote confirmation prompts"}, {Key: ArgBootstrapRemoteTarget, Short: "Inventory host names from `[bootstrap.remote.hosts]`", Long: "Inventory host names from `[bootstrap.remote.hosts]`"}, - {Key: CmdBootstrapRepos, Short: "Manage git repo checkouts from `[bootstrap.repos]`"}, + {Key: CmdBootstrapRepos, Short: "Manage git repo checkouts from `[bootstrap.repos]`", SubcommandRequired: true}, {Key: CmdBootstrapReposApply}, {Key: FlagBootstrapReposApplyDryRun, Short: "Print the commands that would run without running them", Long: "Print the commands that would run without running them"}, {Key: FlagBootstrapReposApplyYes, Short: "Skip the confirmation prompt", Long: "Skip the confirmation prompt"}, @@ -5114,11 +5114,11 @@ var HelpText = argv.HelpTable{ {Key: FlagBootstrapReposUpdateDryRun, Short: "Print the commands that would run without running them", Long: "Print the commands that would run without running them"}, {Key: FlagBootstrapReposUpdateYes, Short: "Skip the confirmation prompt", Long: "Skip the confirmation prompt"}, {Key: ArgBootstrapReposUpdatePath, Short: "Update only matching configured or expanded paths", Long: "Update only matching configured or expanded paths"}, - {Key: CmdBootstrapSecrets, Short: "Inspect bootstrap secret inputs without revealing their values"}, + {Key: CmdBootstrapSecrets, Short: "Inspect bootstrap secret inputs without revealing their values", SubcommandRequired: true}, {Key: CmdBootstrapSecretsStatus, Short: "Show whether declared bootstrap secret inputs are available"}, {Key: FlagBootstrapSecretsStatusJson, Short: "Output in JSON format", Long: "Output in JSON format"}, {Key: FlagBootstrapSecretsStatusMissing, Short: "Exit with code 1 if a declared secret input is unavailable", Long: "Exit with code 1 if a declared secret input is unavailable"}, - {Key: CmdBootstrapServices, Short: "Manage Linux system services from `[bootstrap.services]`"}, + {Key: CmdBootstrapServices, Short: "Manage Linux system services from `[bootstrap.services]`", SubcommandRequired: true}, {Key: CmdBootstrapServicesApply, Short: "Apply configured Linux system service state"}, {Key: FlagBootstrapServicesApplyDryRun, Short: "Print what would change without changing anything", Long: "Print what would change without changing anything"}, {Key: FlagBootstrapServicesApplyYes, Short: "Skip the confirmation prompt", Long: "Skip the confirmation prompt"}, @@ -5129,14 +5129,14 @@ var HelpText = argv.HelpTable{ {Key: FlagBootstrapStatusJson, Short: "Output in JSON format", Long: "Output in JSON format"}, {Key: FlagBootstrapStatusMissing, Short: "Exit with code 1 if any configured bootstrap state is not in its desired state", Long: "Exit with code 1 if any configured bootstrap state is not in its desired state"}, {Key: FlagBootstrapStatusPromptSecrets, Short: "Prompt securely for missing bootstrap secret inputs", Long: "Prompt securely for missing bootstrap secret inputs"}, - {Key: CmdBootstrapSystemd, Hide: true, Short: "Manage systemd user services from `[bootstrap.linux.systemd.units]`"}, + {Key: CmdBootstrapSystemd, Hide: true, Short: "Manage systemd user services from `[bootstrap.linux.systemd.units]`", SubcommandRequired: true}, {Key: CmdBootstrapSystemdApply}, {Key: FlagBootstrapSystemdApplyDryRun, Short: "Print the commands that would run without running them", Long: "Print the commands that would run without running them"}, {Key: FlagBootstrapSystemdApplyYes, Short: "Skip the confirmation prompt", Long: "Skip the confirmation prompt"}, {Key: CmdBootstrapSystemdStatus}, {Key: FlagBootstrapSystemdStatusJson, Short: "Output in JSON format", Long: "Output in JSON format"}, {Key: FlagBootstrapSystemdStatusMissing, Short: "Exit with code 1 if any configured systemd user service is not in its desired state", Long: "Exit with code 1 if any configured systemd user service is not in its desired state"}, - {Key: CmdBootstrapUser, Short: "Manage current-user bootstrap settings from `[bootstrap.user]`"}, + {Key: CmdBootstrapUser, Short: "Manage current-user bootstrap settings from `[bootstrap.user]`", SubcommandRequired: true}, {Key: CmdBootstrapUserApply}, {Key: FlagBootstrapUserApplyDryRun, Short: "Print the commands that would run without running them", Long: "Print the commands that would run without running them"}, {Key: FlagBootstrapUserApplyYes, Short: "Skip the confirmation prompt", Long: "Skip the confirmation prompt"}, @@ -5184,7 +5184,7 @@ var HelpText = argv.HelpTable{ {Key: CmdDirenvActivate, Hide: true, Short: "Output direnv function to use mise inside direnv", Long: "Output direnv function to use mise inside direnv\n\nSee https://mise.jdx.dev/direnv.html for more information\n\nBecause this generates the idiomatic files based on currently installed plugins,\nyou should run this command after installing new plugins. Otherwise\ndirenv may not know to update environment variables when idiomatic file versions change.", AfterLongHelp: "Examples:\n\n $ mise direnv activate > ~/.config/direnv/lib/use_mise.sh\n $ echo 'use mise' > .envrc\n $ direnv allow\n"}, {Key: CmdDirenvEnvrc, Hide: true, Short: "[internal] This is an internal command that writes an envrc file\nfor direnv to consume."}, {Key: CmdDirenvExec, Hide: true, Short: "[internal] This is an internal command that writes an envrc file\nfor direnv to consume."}, - {Key: CmdDotfiles, Hide: true, Short: "Manage dotfiles from `[dotfiles]` (deprecated)", Long: "Manage dotfiles from `[dotfiles]` (deprecated)\n\nUse `mise bootstrap dotfiles` instead."}, + {Key: CmdDotfiles, Hide: true, Short: "Manage dotfiles from `[dotfiles]` (deprecated)", Long: "Manage dotfiles from `[dotfiles]` (deprecated)\n\nUse `mise bootstrap dotfiles` instead.", SubcommandRequired: true}, {Key: CmdDotfilesAdd, Hide: true, Short: "Add or update dotfiles in `[dotfiles]`", Long: "Add or update dotfiles in `[dotfiles]`\n\nIf the target is already managed, this updates its source from the live\ntarget. Otherwise it creates a `[dotfiles]` entry and seeds the source\nunder `dotfiles.root` unless `--source` is provided.", AfterLongHelp: "Examples:\n\n $ mise bootstrap dotfiles add ~/.zshrc\n $ mise bootstrap dotfiles add --mode copy ~/.config/starship.toml\n $ mise bootstrap dotfiles add --source dotfiles/gitconfig ~/.gitconfig\n"}, {Key: FlagDotfilesAddForce, Short: "Overwrite existing sources without prompting", Long: "Overwrite existing sources without prompting"}, {Key: FlagDotfilesAddGlobal, Short: "Write to the global config", Long: "Write to the global config"}, @@ -5252,7 +5252,7 @@ var HelpText = argv.HelpTable{ {Key: FlagFmtAll, Short: "Format all files from the current directory", Long: "Format all files from the current directory"}, {Key: FlagFmtCheck, Short: "Check if the configs are formatted, no formatting is done", Long: "Check if the configs are formatted, no formatting is done"}, {Key: FlagFmtStdin, Short: "Read config from stdin and write its formatted version into stdout", Long: "Read config from stdin and write its formatted version into stdout"}, - {Key: CmdGenerate, Short: "Generate files for various tools/services", VisibleAliases: []string{"gen"}}, + {Key: CmdGenerate, Short: "Generate files for various tools/services", SubcommandRequired: true, VisibleAliases: []string{"gen"}}, {Key: CmdGenerateBootstrap, Short: "Generate a script to download+execute mise", Long: "Generate a script to download+execute mise\n\nThis is designed to be used in a project where contributors may not have mise installed.", AfterLongHelp: "Examples:\n\n $ mise generate bootstrap >./bin/mise\n $ chmod +x ./bin/mise\n $ ./bin/mise install – automatically downloads mise to .mise if not already installed\n"}, {Key: FlagGenerateBootstrapLocalize, Short: "Sandboxes mise internal directories like MISE_DATA_DIR and MISE_CACHE_DIR into a `.mise` directory in the project", Long: "Sandboxes mise internal directories like MISE_DATA_DIR and MISE_CACHE_DIR into a `.mise` directory in the project\n\nThis is necessary if users may use a different version of mise outside the project."}, {Key: FlagGenerateBootstrapVersion, ValueName: "VERSION", ValueDemanded: true, Short: "Specify mise version to fetch", Long: "Specify mise version to fetch"}, @@ -5299,7 +5299,7 @@ var HelpText = argv.HelpTable{ {Key: FlagGenerateToolStubUrl, ValueName: "URL", ValueDemanded: true, Short: "URL for downloading the tool", Long: "URL for downloading the tool\n\nExample: https://github.com/owner/repo/releases/download/v2.0.0/tool-linux-x64.tar.gz"}, {Key: FlagGenerateToolStubVersion, ValueName: "VERSION", ValueDemanded: true, Short: "Version of the tool", Long: "Version of the tool", Default: []string{"latest"}}, {Key: ArgGenerateToolStubOutput, Demanded: true, Short: "Output file path for the tool stub", Long: "Output file path for the tool stub"}, - {Key: CmdGithub, Hide: true, Short: "GitHub related commands"}, + {Key: CmdGithub, Hide: true, Short: "GitHub related commands", SubcommandRequired: true}, {Key: CmdGithubToken, Hide: true, Short: "Display the GitHub token mise will use for a given host", Long: "Display the GitHub token mise will use for a given host\n\nShows which token source mise would use, useful for debugging\nauthentication issues. The token is masked by default.", AfterLongHelp: "Examples:\n\n $ mise github token\n github.com: ghp_…xxxx (source: GITHUB_TOKEN)\n\n $ mise github token --unmask\n github.com: ghp_xxxxxxxxxxxx (source: GITHUB_TOKEN)\n\n $ mise github token github.mycompany.com\n github.mycompany.com: (none)\n"}, {Key: FlagGithubTokenOauth, Short: "Force native GitHub OAuth device flow instead of normal token resolution", Long: "Force native GitHub OAuth device flow instead of normal token resolution"}, {Key: FlagGithubTokenRaw, Short: "Print only the token value", Long: "Print only the token value"}, @@ -5396,7 +5396,7 @@ var HelpText = argv.HelpTable{ {Key: ArgLsRemoteToolVersion, Short: "Tool to get versions for", Long: "Tool to get versions for"}, {Key: ArgLsRemotePrefix, Short: "The version prefix to use when querying the latest version\nsame as the first argument after the \"@\"", Long: "The version prefix to use when querying the latest version\nsame as the first argument after the \"@\""}, {Key: CmdMcp, Short: "Run Model Context Protocol (MCP) server", Long: "Run Model Context Protocol (MCP) server\n\nThis command starts an MCP server that exposes mise functionality\nto AI assistants over stdin/stdout using JSON-RPC protocol.\n\nThe MCP server provides access to:\n- Installed and available tools\n- Task definitions and execution\n- Environment variables\n- Configuration information\n- Task execution via the run_task tool\n\nResources available:\n- mise://tools - List all tools (use ?include_inactive=true to include inactive tools)\n- mise://tasks - List all tasks with their configurations\n- mise://env - List all environment variables\n- mise://config - Show configuration files and project root\n\nTools available:\n- list_commands - Every mise command, with its declared effect on the world\n- install_tool - Install a tool with an optional version (not yet implemented)\n- run_task - Execute a mise task with optional arguments\n\nNote: This is primarily intended for integration with AI assistants like Claude,\nCursor, or other tools that support the Model Context Protocol.", AfterLongHelp: "Examples:\n\n # Start the MCP server (typically used by AI assistant tools)\n $ mise mcp\n\n # Example integration with Claude Desktop (add to claude_desktop_config.json):\n {\n \"mcpServers\": {\n \"mise\": {\n \"command\": \"mise\",\n \"args\": [\"mcp\"],\n \"env\": {}\n }\n }\n }\n\n # Interactive testing with JSON-RPC commands:\n $ echo '{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"initialize\",\"params\":{\"protocolVersion\":\"2024-11-05\",\"capabilities\":{},\"clientInfo\":{\"name\":\"test\",\"version\":\"1.0\"}}}' | mise mcp\n\n # Resources you can query:\n - mise://tools - List active tools\n - mise://tools?include_inactive=true - List all installed tools\n - mise://tasks - List all tasks\n - mise://env - List environment variables\n - mise://config - Show configuration info\n\n # Tools available:\n - list_commands - Every mise command and what running it does\n Example: {\"include_hidden\": false}\n - install_tool - Install a tool (not yet implemented)\n - run_task - Execute a mise task with optional arguments\n Example: {\"task\": \"build\", \"args\": [\"--verbose\"]}\n"}, - {Key: CmdOci, Short: "[experimental] Build OCI container images from a mise.toml", Long: "[experimental] Build OCI container images from a mise.toml\n\nEach tool becomes its own OCI layer, so bumping any single tool version\nonly invalidates one content-addressable blob — unlike a Dockerfile where\nchanging an early `RUN` invalidates every layer above it.\n\nThis command is experimental and requires `mise settings experimental=true`\n(or `MISE_EXPERIMENTAL=1`). Behavior, flags, and output layout may change\nin future releases."}, + {Key: CmdOci, Short: "[experimental] Build OCI container images from a mise.toml", Long: "[experimental] Build OCI container images from a mise.toml\n\nEach tool becomes its own OCI layer, so bumping any single tool version\nonly invalidates one content-addressable blob — unlike a Dockerfile where\nchanging an early `RUN` invalidates every layer above it.\n\nThis command is experimental and requires `mise settings experimental=true`\n(or `MISE_EXPERIMENTAL=1`). Behavior, flags, and output layout may change\nin future releases.", SubcommandRequired: true}, {Key: CmdOciBuild, Short: "[experimental] Build an OCI image from the current mise.toml", Long: "[experimental] Build an OCI image from the current mise.toml\n\nEach tool version becomes its own content-addressable OCI layer. Bumping a\ntool version only invalidates that tool's layer — other tools, the base\nimage, and config are reused unchanged. The output directory conforms to\nthe OCI image-layout spec and can be consumed by `skopeo`, `crane`, or\n`podman load`.\n\nRequires `mise settings experimental=true` (or `MISE_EXPERIMENTAL=1`).", AfterLongHelp: "Examples:\n\n Build with defaults (debian:bookworm-slim base):\n $ mise oci build\n\n Build with a specific base image and tag:\n $ mise oci build --from ubuntu:24.04 --tag myorg/dev:latest -o ./img\n\n Inspect the result with skopeo:\n $ skopeo inspect oci:./mise-oci\n\n Push to a registry:\n $ mise oci push --image-dir ./mise-oci ghcr.io/me/dev:latest\n\nNotes:\n\n - The image only contains tools from the project's mise config (and\n any configs at-or-below the project root). Tools from\n `~/.config/mise/config.toml` are not included; pass --include-global\n to package them too.\n - asdf and vfox plugins are not supported in v1; use a different backend\n (core, aqua, ubi, github, cargo, npm, go, pipx, spm, http) for each tool.\n - The host mise binary is embedded at /usr/local/bin/mise by default;\n build on the same OS/arch as your target image (or pass --no-mise).\n"}, {Key: FlagOciBuildCopy, Repeatable: true, ValueName: "HOST_PATH:IMAGE_PATH", ValueDemanded: true, Short: "Copy a host file, directory, or symlink into the image (repeatable, HOST:IMAGE)", Long: "Copy a host file, directory, or symlink into the image (repeatable, HOST:IMAGE)"}, {Key: FlagOciBuildOutput, ValueName: "OUTPUT", ValueDemanded: true, Short: "Output directory for the OCI image layout", Long: "Output directory for the OCI image layout", Default: []string{"./mise-oci"}}, @@ -5630,7 +5630,7 @@ var HelpText = argv.HelpTable{ {Key: CmdShellAliasUnset, Short: "Removes a shell alias", Long: "Removes a shell alias\n\nThis modifies the contents of ~/.config/mise/config.toml", VisibleAliases: []string{"rm", "remove", "delete", "del"}, AfterLongHelp: "Examples:\n\n $ mise shell-alias unset ll\n"}, {Key: ArgShellAliasUnsetShellAlias, Demanded: true, Short: "The alias to remove", Long: "The alias to remove"}, {Key: CmdSponsors, Short: "Show the companies sponsoring mise and the jdx.dev open source tools"}, - {Key: CmdSync, Short: "Synchronize tools from other version managers with mise"}, + {Key: CmdSync, Short: "Synchronize tools from other version managers with mise", SubcommandRequired: true}, {Key: CmdSyncNode, Short: "Symlinks all tool versions from an external tool into mise", Long: "Symlinks all tool versions from an external tool into mise\n\nFor example, use this to import all Homebrew node installs into mise\n\nThis won't overwrite any existing installs but will overwrite any existing symlinks", AfterLongHelp: "Examples:\n\n $ brew install node@18 node@20\n $ mise sync node --brew\n $ mise use -g node@18 - uses Homebrew-provided node\n"}, {Key: FlagSyncNodeBrew, Short: "Get tool versions from Homebrew", Long: "Get tool versions from Homebrew"}, {Key: FlagSyncNodeNodenv, Short: "Get tool versions from nodenv", Long: "Get tool versions from nodenv"}, @@ -5752,7 +5752,7 @@ var HelpText = argv.HelpTable{ {Key: FlagTestToolIncludeNonDefined, Short: "Also test tools not defined in registry/, guessing how to test it", Long: "Also test tools not defined in registry/, guessing how to test it"}, {Key: FlagTestToolRaw, Short: "Connect backend install command stdin/stdout/stderr directly to the terminal Implies --jobs=1", Long: "Connect backend install command stdin/stdout/stderr directly to the terminal Implies --jobs=1"}, {Key: ArgTestToolTools, Short: "Tool(s) to test", Long: "Tool(s) to test"}, - {Key: CmdToken, Short: "Display git provider tokens mise will use"}, + {Key: CmdToken, Short: "Display git provider tokens mise will use", SubcommandRequired: true}, {Key: CmdTokenForgejo, Short: "Forgejo token", AfterLongHelp: "Examples:\n\n $ mise token forgejo\n codeberg.org: a180…61f6 (source: FORGEJO_TOKEN)\n\n $ mise token forgejo --unmask\n codeberg.org: a18099ca69064be387fbe37b8ad1d333758361f6 (source: FORGEJO_TOKEN)\n\n $ mise token forgejo forgejo.mycompany.com\n forgejo.mycompany.com: (none)\n"}, {Key: FlagTokenForgejoUnmask, Short: "Show the full unmasked token", Long: "Show the full unmasked token"}, {Key: ArgTokenForgejoHost, Short: "Forgejo hostname", Long: "Forgejo hostname", Default: []string{"codeberg.org"}}, diff --git a/go/internal/spec/spec.go b/go/internal/spec/spec.go index d8544ee06..5b66fb073 100644 --- a/go/internal/spec/spec.go +++ b/go/internal/spec/spec.go @@ -107,7 +107,9 @@ type Cmd struct { AllowMissingPositional bool `json:"allow_missing_positional"` SubcommandHelpHeading string `json:"subcommand_help_heading"` SubcommandValueName string `json:"subcommand_value_name"` + SubcommandRequired bool `json:"subcommand_required"` NextLineHelp bool `json:"next_line_help"` + FlattenHelp bool `json:"flatten_help"` } // Subcommands is a command's children, in the order the spec declared them. @@ -657,6 +659,8 @@ func (b *builder) command(c *Cmd, inherited argv.UnknownFlags) *argv.Command { SubcommandHelpHeading: c.SubcommandHelpHeading, SubcommandValueName: c.SubcommandValueName, NextLineHelp: c.NextLineHelp, + FlattenHelp: c.FlattenHelp, + SubcommandRequired: c.SubcommandRequired, Examples: examples, }) diff --git a/lib/src/docs/cli/mod.rs b/lib/src/docs/cli/mod.rs index 92b317165..2c40d171d 100644 --- a/lib/src/docs/cli/mod.rs +++ b/lib/src/docs/cli/mod.rs @@ -328,6 +328,16 @@ fn without_hidden(cmd: &SpecCommand, long: bool) -> SpecCommand { } }); visible.subcommands.retain(|_, sub| !sub.hide); + // Ordinary help only lists immediate subcommands, so their fields are never + // rendered on this page. Walking and cloning the whole remaining tree here + // makes rendering every page quadratic on a fleet-sized CLI. Flattened help + // is the one mode that renders descendant fields and therefore needs the + // recursive filtering. + if visible.flatten_help { + for sub in visible.subcommands.values_mut() { + *sub = without_hidden(sub, long); + } + } visible } @@ -956,4 +966,49 @@ cmd "run" help="Run it" assert!(page.contains(" run\n Run it"), "{page}"); } } + + #[test] + fn flatten_help_expands_subcommands_instead_of_listing_them() { + let spec = crate::spec! { r#" +bin "testcli" +flatten_help #true +next_line_help #true +cmd "run" help="Run it" { + arg "" help="Task name" env="TASK" default="build" { + choices { + choice "build" + choice "test" + } + } + flag "--dry-run" help="Only show changes" + flatten_help #true + cmd "nested" help="Nested operation" { + flag "--deep" help="Deep option" + } +} + "# } + .unwrap(); + + for page in [ + render_help(&spec, &spec.cmd, false), + render_help(&spec, &spec.cmd, true), + ] { + assert!( + page.contains("Usage: testcli\n testcli run"), + "{page}" + ); + assert!(!page.contains("\nCommands:\n"), "{page}"); + assert!(page.contains("\nrun:\nRun it"), "{page}"); + assert!(page.contains("[task]"), "{page}"); + assert!(page.contains("--dry-run"), "{page}"); + assert!(page.contains("\nrun nested:\nNested operation"), "{page}"); + assert!(page.contains("--deep"), "{page}"); + assert!( + page.contains( + " [possible values: build, test]\n [env: TASK]\n (default: build)" + ), + "{page}" + ); + } + } } diff --git a/lib/src/docs/cli/templates/spec_template_long.tera b/lib/src/docs/cli/templates/spec_template_long.tera index a7e099af8..2f39574b5 100644 --- a/lib/src/docs/cli/templates/spec_template_long.tera +++ b/lib/src/docs/cli/templates/spec_template_long.tera @@ -23,9 +23,15 @@ {% endif -%} {%- endif -%} +{%- if cmd.flatten_help and cmd.flattened_usage %} +{%- for usage in cmd.flattened_usage %} +{% if loop.first %}Usage: {% else %} {% endif %}{{ (spec.bin ~ " " ~ usage) | trim }} +{%- endfor %} +{%- else -%} Usage: {{ (spec.bin ~ " " ~ cmd.usage) | trim }} +{%- endif %} -{%- if cmd.subcommands %} +{%- if cmd.subcommands and not cmd.flatten_help %} {{ cmd.subcommand_help_heading | default(value="Commands") }}: {%- for cmd in cmd.subcommands | values | sort(attribute="usage") %} @@ -156,6 +162,65 @@ Global flags: {%- endfor %} {%- endif %} +{%- if cmd.flatten_help %} +{%- for sub in cmd.flattened_subcommands %} + +{{ sub.full_cmd | join(sep=" ") }}: +{%- set about = sub.help_long | default(value=sub.help | default(value='')) %} +{%- if about %} +{{ about | trim }} +{%- endif %} +{%- for group in sub.arg_groups %} +{%- for arg in group.items %} +{%- if sub.flattened_next_line_help %} + {{ arg.usage | trim }} +{%- set help = arg.help_long | default(value=arg.help | default(value='')) %} +{%- if help %} + {{ help | indent(width=4) }} +{%- endif %} +{%- elif arg.help_rendered %} + {{ arg.usage | ljust(width=arg.usage_col_width) }} {{ arg.help_rendered }} +{%- else %} + {{ arg.usage | trim }} +{%- endif %} +{%- if not arg.hide_possible_values and arg.choices and arg.choices.choices %} + [possible values: {{ arg.choices.choices | join(sep=", ") }}] +{%- endif %} +{%- if not arg.hide_env and arg.env %} + [env: {{ arg.env }}] +{%- endif %} +{%- if not arg.hide_default_value and arg.default %} + (default: {{ arg.default | join(sep=", ") }}) +{%- endif %} +{%- endfor %} +{%- endfor %} +{%- for group in sub.flag_groups %} +{%- for flag in group.items %} +{%- if sub.flattened_next_line_help %} + {{ flag.display_usage }} +{%- set help = flag.help_long | default(value=flag.help | default(value='')) %} +{%- if help %} + {{ help | indent(width=4) }} +{%- endif %} +{%- elif flag.help_rendered %} + {{ flag.display_usage | ljust(width=flag.usage_col_width) }} {{ flag.help_rendered }} +{%- else %} + {{ flag.display_usage }} +{%- endif %} +{%- if not flag.hide_possible_values and flag.arg.choices and flag.arg.choices.choices %} + [possible values: {{ flag.arg.choices.choices | join(sep=", ") }}] +{%- endif %} +{%- if not flag.hide_env and flag.env %} + [env: {{ flag.env }}] +{%- endif %} +{%- if not flag.hide_default_value and flag.default %} + (default: {{ flag.default | join(sep=", ") }}) +{%- endif %} +{%- endfor %} +{%- endfor %} +{%- endfor %} +{%- endif %} + {%- if cmd.examples %} Examples: diff --git a/lib/src/docs/cli/templates/spec_template_short.tera b/lib/src/docs/cli/templates/spec_template_short.tera index 60fa4fa80..3c65396de 100644 --- a/lib/src/docs/cli/templates/spec_template_short.tera +++ b/lib/src/docs/cli/templates/spec_template_short.tera @@ -15,9 +15,15 @@ {% endif -%} {%- endif -%} +{%- if cmd.flatten_help and cmd.flattened_usage %} +{%- for usage in cmd.flattened_usage %} +{% if loop.first %}Usage: {% else %} {% endif %}{{ (spec.bin ~ " " ~ usage) | trim }} +{%- endfor %} +{%- else -%} Usage: {{ (spec.bin ~ " " ~ cmd.usage) | trim }} +{%- endif %} -{%- if cmd.subcommands %} +{%- if cmd.subcommands and not cmd.flatten_help %} {{ cmd.subcommand_help_heading | default(value="Commands") }}: {%- set next_line_help = cmd.next_line_help %} @@ -104,6 +110,58 @@ Global flags: {%- endfor %} {%- endif %} +{%- if cmd.flatten_help %} +{%- for sub in cmd.flattened_subcommands %} + +{{ sub.full_cmd | join(sep=" ") }}: +{%- if sub.help %} +{{ sub.help | trim }} +{%- endif %} +{%- for group in sub.arg_groups %} +{%- for arg in group.items %} + {% if arg.help %}{% if sub.flattened_next_line_help %}{{ arg.usage | trim }} + {{ arg.help | indent(width=4) }}{% else %}{{ arg.usage | trim | ljust(width=arg.usage_col_width) }} {{ arg.help }}{% endif %}{% else %}{{ arg.usage | trim }}{% endif %} +{%- if sub.flattened_next_line_help %} +{%- if not arg.hide_possible_values and arg.choices and arg.choices.choices %} + [possible values: {{ arg.choices.choices | join(sep=", ") }}]{%- endif %} +{%- if not arg.hide_possible_values and arg.choices and arg.choices.env %} + [choices env: {{ arg.choices.env }}]{%- endif %} +{%- if not arg.hide_env and arg.env %} + [env: {{ arg.env }}]{%- endif %} +{%- if not arg.hide_default_value and arg.default %} + (default: {{ arg.default | join(sep=", ") }}){%- endif %} +{%- else %} +{%- if not arg.hide_possible_values and arg.choices and arg.choices.choices %} [{{ arg.choices.choices | join(sep=", ") }}]{%- endif %} +{%- if not arg.hide_possible_values and arg.choices and arg.choices.env %} [choices env: {{ arg.choices.env }}]{%- endif %} +{%- if not arg.hide_env and arg.env %} [env: {{ arg.env }}]{%- endif %} +{%- if not arg.hide_default_value and arg.default %} (default: {{ arg.default | join(sep=", ") }}){%- endif %} +{%- endif %} +{%- endfor %} +{%- endfor %} +{%- for group in sub.flag_groups %} +{%- for flag in group.items %} + {% if flag.help %}{% if sub.flattened_next_line_help %}{{ flag.display_usage }} + {{ flag.help | indent(width=4) }}{% else %}{{ flag.display_usage | ljust(width=flag.usage_col_width) }} {{ flag.help }}{% endif %}{% else %}{{ flag.display_usage }}{% endif %} +{%- if sub.flattened_next_line_help %} +{%- if not flag.hide_possible_values and flag.arg.choices and flag.arg.choices.choices %} + [possible values: {{ flag.arg.choices.choices | join(sep=", ") }}]{%- endif %} +{%- if not flag.hide_possible_values and flag.arg.choices and flag.arg.choices.env %} + [choices env: {{ flag.arg.choices.env }}]{%- endif %} +{%- if not flag.hide_env and flag.env %} + [env: {{ flag.env }}]{%- endif %} +{%- if not flag.hide_default_value and flag.default %} + (default: {{ flag.default | join(sep=", ") }}){%- endif %} +{%- else %} +{%- if not flag.hide_possible_values and flag.arg.choices and flag.arg.choices.choices %} [{{ flag.arg.choices.choices | join(sep=", ") }}]{%- endif %} +{%- if not flag.hide_possible_values and flag.arg.choices and flag.arg.choices.env %} [choices env: {{ flag.arg.choices.env }}]{%- endif %} +{%- if not flag.hide_env and flag.env %} [env: {{ flag.env }}]{%- endif %} +{%- if not flag.hide_default_value and flag.default %} (default: {{ flag.default | join(sep=", ") }}){%- endif %} +{%- endif %} +{%- endfor %} +{%- endfor %} +{%- endfor %} +{%- endif %} + {%- if cmd.examples %} Examples: diff --git a/lib/src/docs/markdown/arg.rs b/lib/src/docs/markdown/arg.rs index a8bd6007c..049e4ef6e 100644 --- a/lib/src/docs/markdown/arg.rs +++ b/lib/src/docs/markdown/arg.rs @@ -6,9 +6,7 @@ impl MarkdownRenderer { pub fn render_arg(&self, arg: &crate::SpecArg) -> Result { let mut arg = SpecArg::from(arg); arg.render_md(self); - let mut ctx = self.clone(); - ctx.insert("arg", &arg); - ctx.render("arg_template.md.tera") + self.render_with("arg_template.md.tera", |ctx| ctx.insert("arg", &arg)) } } diff --git a/lib/src/docs/markdown/cmd.rs b/lib/src/docs/markdown/cmd.rs index df056f4cc..f52cd2985 100644 --- a/lib/src/docs/markdown/cmd.rs +++ b/lib/src/docs/markdown/cmd.rs @@ -6,9 +6,7 @@ impl MarkdownRenderer { pub fn render_cmd(&self, cmd: &crate::SpecCommand) -> Result { let mut cmd = SpecCommand::from(cmd); cmd.render_md(self); - let mut ctx = self.clone(); - ctx.insert("cmd", &cmd); - ctx.render("cmd_template.md.tera") + self.render_with("cmd_template.md.tera", |ctx| ctx.insert("cmd", &cmd)) } } diff --git a/lib/src/docs/markdown/config.rs b/lib/src/docs/markdown/config.rs index a3314316b..d20494b6b 100644 --- a/lib/src/docs/markdown/config.rs +++ b/lib/src/docs/markdown/config.rs @@ -17,9 +17,9 @@ impl MarkdownRenderer { return Ok(String::new()); } config.render_md(self); - let mut ctx = self.clone(); - ctx.insert("config", &config); - ctx.render("config_template.md.tera") + self.render_with("config_template.md.tera", |ctx| { + ctx.insert("config", &config) + }) } } diff --git a/lib/src/docs/markdown/flag.rs b/lib/src/docs/markdown/flag.rs index 58f76786d..c10d4e816 100644 --- a/lib/src/docs/markdown/flag.rs +++ b/lib/src/docs/markdown/flag.rs @@ -6,9 +6,7 @@ impl MarkdownRenderer { pub fn render_flag(&self, flag: &crate::SpecFlag) -> Result { let mut flag = SpecFlag::from(flag); flag.render_md(self); - let mut ctx = self.clone(); - ctx.insert("flag", &flag); - ctx.render("flag_template.md.tera") + self.render_with("flag_template.md.tera", |ctx| ctx.insert("flag", &flag)) } } diff --git a/lib/src/docs/markdown/renderer.rs b/lib/src/docs/markdown/renderer.rs index a6fa91e81..8e03fc89b 100644 --- a/lib/src/docs/markdown/renderer.rs +++ b/lib/src/docs/markdown/renderer.rs @@ -2,7 +2,6 @@ use crate::docs::markdown::tera::TERA; use crate::docs::models::Spec; use crate::error::UsageErr; use itertools::Itertools; -use serde::Serialize; fn escape_md(value: &str, html_encode: bool) -> String { let mut in_fenced_code_block = false; @@ -61,7 +60,6 @@ pub struct MarkdownRenderer { pub(crate) raw_config: crate::spec::config::SpecConfig, pub(crate) header_level: usize, pub(crate) multi: bool, - tera_ctx: tera::Context, url_prefix: Option, html_encode: bool, replace_pre_with_code_fences: bool, @@ -74,7 +72,6 @@ impl MarkdownRenderer { spec: spec.into(), header_level: 1, multi: false, - tera_ctx: tera::Context::new(), url_prefix: None, html_encode: true, replace_pre_with_code_fences: false, @@ -140,12 +137,8 @@ impl MarkdownRenderer { self } - pub(crate) fn insert>(&mut self, key: S, val: &T) { - self.tera_ctx.insert(key.into(), val); - } - fn tera_ctx(&self) -> tera::Context { - let mut ctx = self.tera_ctx.clone(); + let mut ctx = tera::Context::new(); ctx.insert("spec", &self.spec); ctx.insert("header_level", &self.header_level); ctx.insert("multi", &self.multi); @@ -154,7 +147,16 @@ impl MarkdownRenderer { ctx } - pub(crate) fn render(&self, template_name: &str) -> Result { + /// Render with values that belong only to this page. + /// + /// A page used to clone the whole renderer — including the complete command tree — merely + /// to insert one local into its stored context. Multi-page output paid that deep clone once + /// per command. The context already has to be materialized for Tera, so enrich that directly. + pub(crate) fn render_with( + &self, + template_name: &str, + enrich: impl FnOnce(&mut tera::Context), + ) -> Result { let mut tera = TERA.clone(); let html_encode = self.html_encode; @@ -170,7 +172,9 @@ impl MarkdownRenderer { }, ); - Ok(tera.render(template_name, &self.tera_ctx())?) + let mut ctx = self.tera_ctx(); + enrich(&mut ctx); + Ok(tera.render(template_name, &ctx)?) } pub(crate) fn replace_code_fences(&self, md: String) -> String { diff --git a/lib/src/docs/markdown/spec.rs b/lib/src/docs/markdown/spec.rs index 0405852e5..794a7897e 100644 --- a/lib/src/docs/markdown/spec.rs +++ b/lib/src/docs/markdown/spec.rs @@ -3,31 +3,32 @@ use crate::error::UsageErr; impl MarkdownRenderer { pub fn render_spec(&self) -> Result { - let mut ctx = self.clone(); - ctx.insert("all_commands", &self.spec.cmd.all_subcommands()); + let all_commands = self.spec.cmd.all_subcommands(); // From the raw block for the same reason `render_config` does: the copy on `self.spec` // was rendered by `new` before the builder options existed, and rendering happens once. let mut config = crate::docs::models::SpecConfig::from(&self.raw_config); config.render_md(self); - ctx.insert("config", &config); - ctx.render("spec_template.md.tera") + self.render_with("spec_template.md.tera", |ctx| { + ctx.insert("all_commands", &all_commands); + ctx.insert("config", &config); + }) } pub fn render_index(&self) -> Result { - let mut ctx = self.clone(); - ctx.multi = false; - ctx.insert("all_commands", &self.spec.cmd.all_subcommands()); + let all_commands = self.spec.cmd.all_subcommands(); // So the index can link the settings page it sits beside. Without this the page was // written and nothing pointed at it, which for a reader who starts at the index is // the same as not writing it. - ctx.insert( - "config", - &crate::docs::models::SpecConfig::from(&self.raw_config), - ); + let config = crate::docs::models::SpecConfig::from(&self.raw_config); // The name the page will actually be written under, so the link cannot point somewhere // else than the file — including when a `settings` command has taken `settings.md`. - ctx.insert("config_page", &self.config_page()); - ctx.render("index_template.md.tera") + self.render_with("index_template.md.tera", |ctx| { + // An index links separate pages even when the renderer's ordinary mode is single-file. + ctx.insert("multi", &false); + ctx.insert("all_commands", &all_commands); + ctx.insert("config", &config); + ctx.insert("config_page", &self.config_page()); + }) } } diff --git a/lib/src/docs/models.rs b/lib/src/docs/models.rs index 134a10611..04c9be455 100644 --- a/lib/src/docs/models.rs +++ b/lib/src/docs/models.rs @@ -48,6 +48,13 @@ pub struct SpecCommand { pub subcommand_required: bool, pub subcommand_help_heading: Option, pub next_line_help: bool, + pub flatten_help: bool, + pub args_conflicts_with_subcommands: bool, + pub flattened_usage: Vec, + /// Visible descendants rendered as sections when an ancestor flattens help. + pub flattened_subcommands: Vec, + /// The flattening parent's layout policy for this section. + pub flattened_next_line_help: bool, pub restart_token: Option, pub help: Option, pub help_long: Option, @@ -418,6 +425,23 @@ impl From<&crate::SpecCommand> for SpecCommand { use crate::docs::layout::{help_width, max_usage_width, render_help_text}; let terminal_width = help_width(cmd.term_width, cmd.max_term_width); + let flattened_usage = if cmd.flatten_help { + let mut lines = Vec::new(); + if !cmd.subcommand_required || cmd.args_conflicts_with_subcommands { + lines.push(cmd.usage_without_subcommands()); + } + let mut children: Vec<_> = cmd + .subcommands + .values() + .filter(|sub| !sub.hide) + .map(crate::SpecCommand::usage) + .collect(); + children.sort(); + lines.extend(children); + lines + } else { + Vec::new() + }; // Calculate layout for args let args_usage_col_width = max_usage_width(cmd.args.iter().map(|a| a.usage.as_str())); @@ -482,6 +506,7 @@ impl From<&crate::SpecCommand> for SpecCommand { subcommand_help_heading, subcommand_value_name: _, next_line_help, + flatten_help, // Consumed above while laying help out; templates need only the result. term_width: _, max_term_width: _, @@ -506,7 +531,7 @@ impl From<&crate::SpecCommand> for SpecCommand { dont_delimit_trailing_values: _, args_override_self: _, subcommand_negates_reqs: _, - args_conflicts_with_subcommands: _, + args_conflicts_with_subcommands, subcommand_precedence_over_arg: _, allow_missing_positional: _, // Rendered above, or deliberately absent from the docs model. @@ -522,13 +547,26 @@ impl From<&crate::SpecCommand> for SpecCommand { groups: _, } = cmd; + let subcommands: IndexMap<_, _> = subcommands + .iter() + .map(|(k, v)| (k.clone(), SpecCommand::from(v))) + .collect(); + let mut flattened_subcommands = Vec::new(); + if *flatten_help { + let mut visible: Vec<_> = subcommands.values().filter(|sub| !sub.hide).collect(); + visible.sort_by(|a, b| a.name.cmp(&b.name)); + for sub in visible { + let mut section = sub.clone(); + section.flattened_next_line_help = *next_line_help; + flattened_subcommands.push(section); + flattened_subcommands.extend(sub.flattened_subcommands.iter().cloned()); + } + } + Self { full_cmd: full_cmd.clone(), usage: usage.clone(), - subcommands: subcommands - .iter() - .map(|(k, v)| (k.clone(), SpecCommand::from(v))) - .collect(), + subcommands, flag_groups: group_by_heading(&flags, |f| f.help_heading.as_deref()), arg_groups: group_by_heading(&args, |a| a.help_heading.as_deref()), args, @@ -539,6 +577,11 @@ impl From<&crate::SpecCommand> for SpecCommand { subcommand_required: *subcommand_required, subcommand_help_heading: subcommand_help_heading.clone(), next_line_help: *next_line_help, + flatten_help: *flatten_help, + args_conflicts_with_subcommands: *args_conflicts_with_subcommands, + flattened_usage, + flattened_subcommands, + flattened_next_line_help: false, restart_token: restart_token.clone(), // The renderer owns the line break after a command description. Keeping one // embedded in the text creates an extra blank in next-line help. diff --git a/lib/src/go/mod.rs b/lib/src/go/mod.rs index 5e00510fb..ad5a83d05 100644 --- a/lib/src/go/mod.rs +++ b/lib/src/go/mod.rs @@ -990,6 +990,12 @@ fn command_help(e: &Emitted) -> String { if e.cmd.next_line_help { fields.push("NextLineHelp: true".to_string()); } + if e.cmd.flatten_help { + fields.push("FlattenHelp: true".to_string()); + } + if e.cmd.subcommand_required { + fields.push("SubcommandRequired: true".to_string()); + } // Visible only: the parse table merges hidden aliases in beside these, // because binding does not care which is which. A page does. let visible: Vec = e diff --git a/lib/src/spec/cmd.rs b/lib/src/spec/cmd.rs index b38f812fb..20d257cfb 100644 --- a/lib/src/spec/cmd.rs +++ b/lib/src/spec/cmd.rs @@ -103,6 +103,9 @@ pub struct SpecCommand { /// Put each argument, flag, and subcommand description on the following line. #[serde(skip_serializing_if = "is_false")] pub next_line_help: bool, + /// Expand each visible subcommand's summary and arguments into this command's help page. + #[serde(skip_serializing_if = "is_false")] + pub flatten_help: bool, /// Fixed help width. Zero disables wrapping. #[serde(skip_serializing_if = "Option::is_none")] pub term_width: Option, @@ -208,6 +211,7 @@ impl Default for SpecCommand { subcommand_help_heading: None, subcommand_value_name: None, next_line_help: false, + flatten_help: false, term_width: None, max_term_width: None, external_subcommand: false, @@ -326,6 +330,7 @@ impl SpecCommand { "subcommand_help_heading" => cmd.subcommand_help_heading = Some(v.ensure_string()?), "subcommand_value_name" => cmd.subcommand_value_name = Some(v.ensure_string()?), "next_line_help" => cmd.next_line_help = v.ensure_bool()?, + "flatten_help" => cmd.flatten_help = v.ensure_bool()?, "term_width" => cmd.term_width = Some(v.ensure_usize()?), "max_term_width" => cmd.max_term_width = Some(v.ensure_usize()?), "external_subcommand" => cmd.external_subcommand = v.ensure_bool()?, @@ -474,6 +479,9 @@ impl SpecCommand { "next_line_help" => { cmd.next_line_help = child.ensure_arg_len(1..=1)?.arg(0)?.ensure_bool()? } + "flatten_help" => { + cmd.flatten_help = child.ensure_arg_len(1..=1)?.arg(0)?.ensure_bool()? + } "term_width" => { cmd.term_width = Some(child.ensure_arg_len(1..=1)?.arg(0)?.ensure_usize()?) } @@ -549,6 +557,14 @@ impl SpecCommand { && self.subcommands.is_empty() } pub fn usage(&self) -> String { + self.usage_with_subcommands(true) + } + + pub(crate) fn usage_without_subcommands(&self) -> String { + self.usage_with_subcommands(false) + } + + fn usage_with_subcommands(&self, include_subcommands: bool) -> String { let mut usage = self.full_cmd.join(" "); let flags = self.flags.iter().filter(|f| !f.hide).collect_vec(); let args = self.args.iter().filter(|a| !a.hide).collect_vec(); @@ -585,7 +601,7 @@ impl SpecCommand { // if !self.mounts.is_empty() { // name = format!("{name} [mounts]"); // } - if !self.subcommands.is_empty() { + if include_subcommands && !self.subcommands.is_empty() { let name = self .subcommand_value_name .as_deref() @@ -626,6 +642,7 @@ impl SpecCommand { subcommand_help_heading, subcommand_value_name, next_line_help, + flatten_help, term_width, max_term_width, external_subcommand, @@ -715,6 +732,7 @@ impl SpecCommand { self.subcommand_value_name = subcommand_value_name; } self.next_line_help = next_line_help; + self.flatten_help = flatten_help; if term_width.is_some() { self.term_width = term_width; } @@ -834,6 +852,7 @@ impl From<&SpecCommand> for KdlNode { subcommand_help_heading, subcommand_value_name, next_line_help, + flatten_help, term_width, max_term_width, external_subcommand, @@ -894,6 +913,9 @@ impl From<&SpecCommand> for KdlNode { if *next_line_help { node.push(KdlEntry::new_prop("next_line_help", true)); } + if *flatten_help { + node.push(KdlEntry::new_prop("flatten_help", true)); + } if let Some(width) = term_width { node.push(KdlEntry::new_prop("term_width", *width as i128)); } @@ -1177,6 +1199,7 @@ impl From<&clap::Command> for SpecCommand { spec.subcommand_help_heading = cmd.get_subcommand_help_heading().map(str::to_string); spec.subcommand_value_name = cmd.get_subcommand_value_name().map(str::to_string); spec.next_line_help = cmd.is_next_line_help_set(); + spec.flatten_help = cmd.is_flatten_help_set(); spec.arg_required_else_help = cmd.is_arg_required_else_help_set(); spec.dont_delimit_trailing_values = cmd.is_dont_delimit_trailing_values_set(); spec.args_override_self = cmd.is_args_override_self(); diff --git a/lib/src/spec/mod.rs b/lib/src/spec/mod.rs index ea0673406..f69b2d8f9 100644 --- a/lib/src/spec/mod.rs +++ b/lib/src/spec/mod.rs @@ -331,6 +331,9 @@ impl Spec { "next_line_help" => { schema.cmd.next_line_help = node.arg(0)?.ensure_bool()?; } + "flatten_help" => { + schema.cmd.flatten_help = node.arg(0)?.ensure_bool()?; + } "term_width" => { schema.cmd.term_width = Some(node.arg(0)?.ensure_usize()?); } @@ -670,6 +673,11 @@ impl Display for Spec { node.push(true); nodes.push(node); } + if self.cmd.flatten_help { + let mut node = KdlNode::new("flatten_help"); + node.push(true); + nodes.push(node); + } if let Some(width) = self.cmd.term_width { let mut node = KdlNode::new("term_width"); node.push(width as i128); diff --git a/usage-rs/tests/facade.rs b/usage-rs/tests/facade.rs index e6dd563c1..b6ca98e26 100644 --- a/usage-rs/tests/facade.rs +++ b/usage-rs/tests/facade.rs @@ -164,6 +164,28 @@ struct NextLineHelp { mode: String, } +#[derive(Debug, Cli)] +#[usage(bin = "flat-help", flatten_help)] +#[allow(dead_code)] +struct FlatHelp { + #[usage(subcommand)] + command: FlatCommand, +} + +#[derive(Debug, Subcommands)] +#[allow(dead_code)] +enum FlatCommand { + /// Run a task. + Run(FlatRun), +} + +#[derive(Debug, Args)] +#[allow(dead_code)] +struct FlatRun { + /// Task name. + task: String, +} + #[derive(Cli)] #[command( bin = "presented", @@ -1213,6 +1235,22 @@ fn typed_next_line_help_reaches_help_and_the_portable_spec() { assert!(portable.cmd.next_line_help); } +#[test] +fn typed_flatten_help_reaches_help_and_the_portable_spec() { + let spec = FlatHelp::spec(); + assert!(spec.root.flatten_help); + let page = usage::argv::help::short_help(spec, &["flat-help"], &[spec.root]); + assert!(page.contains("Usage: flat-help run"), "{page}"); + assert!(!page.contains("\nCommands:\n"), "{page}"); + assert!(page.contains("\nrun:\nRun a task."), "{page}"); + assert!(page.contains(""), "{page}"); + + let kdl = FlatHelp::to_kdl(); + assert!(kdl.contains("flatten_help #true"), "{kdl}"); + let portable: usage_parser::Spec = kdl.parse().unwrap(); + assert!(portable.cmd.flatten_help); +} + #[test] fn emitted_parser_settings_are_portable_spec_metadata() { let Err(_) = StrictEx::parse_from(&[OsStr::new("--wat")]) else {