@@ -29,6 +29,201 @@ use crate::DoubleDash; |
29 | 29 | /// `[FLAGS]` or `[ARGS]…` and the sections below carry the detail. |
30 | 30 | const INLINE_LIMIT: usize = 2; |
31 | 31 |
|
| 32 | +/// Whether help output is coloured. |
| 33 | +/// |
| 34 | +/// Plain rendering remains available for generated documents and snapshots; |
| 35 | +/// process-facing help uses [`Style::auto`]. |
| 36 | +#[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 37 | +pub struct Style { |
| 38 | + coloured: bool, |
| 39 | +} |
| 40 | + |
| 41 | +impl Style { |
| 42 | + /// Plain text, suitable for a pipe or a generated artifact. |
| 43 | + pub const PLAIN: Style = Style { coloured: false }; |
| 44 | + /// ANSI-coloured text, regardless of the output destination. |
| 45 | + pub const COLOURED: Style = Style { coloured: true }; |
| 46 | + |
| 47 | + /// Colour when stdout is a terminal and the environment permits it. |
| 48 | + pub fn auto() -> Style { |
| 49 | + use std::io::IsTerminal as _; |
| 50 | + let forced = std::env::var_os("CLICOLOR_FORCE").is_some_and(|v| v != "0"); |
| 51 | + let refused = std::env::var_os("NO_COLOR").is_some_and(|v| !v.is_empty()); |
| 52 | + if refused { |
| 53 | + Style::PLAIN |
| 54 | + } else if forced || std::io::stdout().is_terminal() { |
| 55 | + Style::COLOURED |
| 56 | + } else { |
| 57 | + Style::PLAIN |
| 58 | + } |
| 59 | + } |
| 60 | + |
| 61 | + fn wrap(self, code: &str, text: &str) -> String { |
| 62 | + if self.coloured { |
| 63 | + format!("\u{1b}[{code}m{text}\u{1b}[0m") |
| 64 | + } else { |
| 65 | + text.to_string() |
| 66 | + } |
| 67 | + } |
| 68 | + |
| 69 | + fn heading(self, text: &str) -> String { |
| 70 | + self.wrap("1;4;32", text) |
| 71 | + } |
| 72 | + |
| 73 | + fn literal(self, text: &str) -> String { |
| 74 | + self.wrap("36", text) |
| 75 | + } |
| 76 | +} |
| 77 | + |
| 78 | +fn styled_flag_usage(usage: &str, style: Style) -> String { |
| 79 | + let mut out = String::with_capacity(usage.len()); |
| 80 | + let mut rest = usage; |
| 81 | + while let Some(start) = rest.find('-') { |
| 82 | + let previous_allows = start == 0 |
| 83 | + || rest[..start] |
| 84 | + .chars() |
| 85 | + .next_back() |
| 86 | + .is_some_and(|c| c.is_whitespace() || matches!(c, ',' | ':' | '[' | '<')); |
| 87 | + if !previous_allows { |
| 88 | + out.push_str(&rest[..=start]); |
| 89 | + rest = &rest[start + 1..]; |
| 90 | + continue; |
| 91 | + } |
| 92 | + let end = rest[start..] |
| 93 | + .char_indices() |
| 94 | + .skip(1) |
| 95 | + .find_map(|(i, c)| (c.is_whitespace() || matches!(c, ',' | ']' | '>')).then_some(i)) |
| 96 | + .unwrap_or(rest.len() - start) |
| 97 | + + start; |
| 98 | + out.push_str(&rest[..start]); |
| 99 | + out.push_str(&style.literal(&rest[start..end])); |
| 100 | + rest = &rest[end..]; |
| 101 | + } |
| 102 | + out.push_str(rest); |
| 103 | + out |
| 104 | +} |
| 105 | + |
| 106 | +fn help_structure( |
| 107 | + spec: &Spec<'_>, |
| 108 | + path: &[&str], |
| 109 | + chain: &[&CommandMeta<'_>], |
| 110 | + long: bool, |
| 111 | +) -> (Vec<String>, Vec<String>, Vec<String>) { |
| 112 | + let meta = *chain.last().expect("a page is always about some command"); |
| 113 | + let mut headings = Vec::new(); |
| 114 | + if !page_examples(spec, meta).is_empty() { |
| 115 | + headings.push("Examples".to_string()); |
| 116 | + } |
| 117 | + if meta.subcommands.iter().any(|sub| !sub.hide) { |
| 118 | + headings.push( |
| 119 | + meta.subcommand_help_heading |
| 120 | + .unwrap_or("Commands") |
| 121 | + .to_string(), |
| 122 | + ); |
| 123 | + } |
| 124 | + |
| 125 | + let (own, inherited) = own_and_global(chain); |
| 126 | + let visible_arg = |arg: &&ArgMeta<'_>| { |
| 127 | + !arg.hide |
| 128 | + && if long { |
| 129 | + !arg.hide_long_help |
| 130 | + } else { |
| 131 | + !arg.hide_short_help |
| 132 | + } |
| 133 | + }; |
| 134 | + let args: Vec<_> = meta.args.iter().filter(visible_arg).collect(); |
| 135 | + if args.iter().any(|arg| arg.help_heading.is_none()) { |
| 136 | + headings.push("Arguments".to_string()); |
| 137 | + } |
| 138 | + headings.extend( |
| 139 | + args.iter() |
| 140 | + .filter_map(|arg| arg.help_heading) |
| 141 | + .map(str::to_string), |
| 142 | + ); |
| 143 | + |
| 144 | + let visible_flag = |flag: &&FlagMeta<'_>| { |
| 145 | + !flag.hide |
| 146 | + && if long { |
| 147 | + !flag.hide_long_help |
| 148 | + } else { |
| 149 | + !flag.hide_short_help |
| 150 | + } |
| 151 | + }; |
| 152 | + let own: Vec<_> = own.into_iter().filter(visible_flag).collect(); |
| 153 | + let inherited: Vec<_> = inherited |
| 154 | + .into_iter() |
| 155 | + .filter(|(flag, _)| { |
| 156 | + if long { |
| 157 | + !flag.hide_long_help |
| 158 | + } else { |
| 159 | + !flag.hide_short_help |
| 160 | + } |
| 161 | + }) |
| 162 | + .collect(); |
| 163 | + if own.iter().any(|flag| flag.help_heading.is_none()) { |
| 164 | + headings.push("Flags".to_string()); |
| 165 | + } |
| 166 | + headings.extend( |
| 167 | + own.iter() |
| 168 | + .filter_map(|flag| flag.help_heading) |
| 169 | + .map(str::to_string), |
| 170 | + ); |
| 171 | + if !inherited.is_empty() { |
| 172 | + headings.push("Global flags".to_string()); |
| 173 | + } |
| 174 | + |
| 175 | + let mut flag_usages: Vec<String> = own.iter().map(|flag| column_usage(flag)).collect(); |
| 176 | + flag_usages.extend(inherited.into_iter().map(|(_, usage)| usage)); |
| 177 | + flag_usages.sort_by_key(|usage| core::cmp::Reverse(usage.len())); |
| 178 | + |
| 179 | + let mut synopsis = String::new(); |
| 180 | + usage_section(&mut synopsis, spec, path, meta); |
| 181 | + let synopsis = synopsis.lines().map(str::to_string).collect(); |
| 182 | + (headings, flag_usages, synopsis) |
| 183 | +} |
| 184 | + |
| 185 | +fn styled_help( |
| 186 | + page: &str, |
| 187 | + style: Style, |
| 188 | + headings: &[String], |
| 189 | + flag_usages: &[String], |
| 190 | + synopsis: &[String], |
| 191 | +) -> String { |
| 192 | + if !style.coloured { |
| 193 | + return page.to_string(); |
| 194 | + } |
| 195 | + let mut out = String::with_capacity(page.len()); |
| 196 | + for line in page.split_inclusive('\n') { |
| 197 | + let (body, newline) = line |
| 198 | + .strip_suffix('\n') |
| 199 | + .map_or((line, ""), |body| (body, "\n")); |
| 200 | + if synopsis.iter().any(|known| known == body) && body.starts_with("Usage:") { |
| 201 | + let usage = body.strip_prefix("Usage:").unwrap_or_default(); |
| 202 | + out.push_str(&style.heading("Usage:")); |
| 203 | + out.push_str(&style.literal(usage)); |
| 204 | + } else if synopsis.iter().any(|known| known == body) { |
| 205 | + out.push_str(&style.literal(body)); |
| 206 | + } else if body |
| 207 | + .strip_suffix(':') |
| 208 | + .is_some_and(|heading| headings.iter().any(|known| known == heading)) |
| 209 | + { |
| 210 | + out.push_str(&style.heading(body)); |
| 211 | + } else { |
| 212 | + let styled = body.strip_prefix(" ").and_then(|entry| { |
| 213 | + flag_usages.iter().find_map(|usage| { |
| 214 | + entry |
| 215 | + .strip_prefix(usage) |
| 216 | + .filter(|rest| rest.is_empty() || rest.starts_with(char::is_whitespace)) |
| 217 | + .map(|rest| format!(" {}{rest}", styled_flag_usage(usage, style))) |
| 218 | + }) |
| 219 | + }); |
| 220 | + out.push_str(styled.as_deref().unwrap_or(body)); |
| 221 | + } |
| 222 | + out.push_str(newline); |
| 223 | + } |
| 224 | + out |
| 225 | +} |
| 226 | + |
32 | 227 | /// The `Usage:` line's body, without the `Usage: ` prefix. |
33 | 228 | /// |
34 | 229 | /// `path` is the command as invoked, starting with the binary: `["mise", "config", "ls"]`. |
@@ -1341,6 +1536,29 @@ pub fn render(spec: &Spec<'_>, cmd: &Command<'_>, long: bool) -> Option<String> |
1341 | 1536 | }) |
1342 | 1537 | } |
1343 | 1538 |
|
| 1539 | +/// Render a help page with an explicit colour policy. |
| 1540 | +pub fn render_styled( |
| 1541 | + spec: &Spec<'_>, |
| 1542 | + cmd: &Command<'_>, |
| 1543 | + long: bool, |
| 1544 | + style: Style, |
| 1545 | +) -> Option<String> { |
| 1546 | + let (path, chain) = find(spec, cmd)?; |
| 1547 | + let page = if long { |
| 1548 | + long_help(spec, &path, &chain) |
| 1549 | + } else { |
| 1550 | + short_help(spec, &path, &chain) |
| 1551 | + }; |
| 1552 | + let (headings, flag_usages, synopsis) = help_structure(spec, &path, &chain, long); |
| 1553 | + Some(styled_help( |
| 1554 | + &page, |
| 1555 | + style, |
| 1556 | + &headings, |
| 1557 | + &flag_usages, |
| 1558 | + &synopsis, |
| 1559 | + )) |
| 1560 | +} |
| 1561 | + |
1344 | 1562 | /// The route the words took to a command, for rendering its page unambiguously. |
1345 | 1563 | /// |
1346 | 1564 | /// Rebuilt by re-parsing, because [`Error::Help`](crate::Error::Help) carries the command and |
@@ -1408,7 +1626,10 @@ pub fn route_to<'t>( |
1408 | 1626 | /// The route tells them apart, and the parser has it — `Parser::command_path` is the sequence of |
1409 | 1627 | /// commands the words actually went through. Callers holding only a command keep [`render`] and |
1410 | 1628 | /// its answer; callers that parsed something should prefer this. |
1411 | | -pub fn render_at(spec: &Spec<'_>, route: &[&Command<'_>], long: bool) -> Option<String> { |
| 1629 | +fn route_context<'a>( |
| 1630 | + spec: &'a Spec<'a>, |
| 1631 | + route: &[&Command<'_>], |
| 1632 | +) -> Option<(Vec<&'a str>, Vec<&'a CommandMeta<'a>>)> { |
1412 | 1633 | let mut names = vec![spec.bin.unwrap_or(spec.name)]; |
1413 | 1634 | let mut chain = vec![spec.root]; |
1414 | 1635 | for cmd in route.iter().skip(1) { |
@@ -1422,9 +1643,87 @@ pub fn render_at(spec: &Spec<'_>, route: &[&Command<'_>], long: bool) -> Option< |
1422 | 1643 | names.push(next.cmd.name); |
1423 | 1644 | chain.push(next); |
1424 | 1645 | } |
| 1646 | + Some((names, chain)) |
| 1647 | +} |
| 1648 | + |
| 1649 | +pub fn render_at(spec: &Spec<'_>, route: &[&Command<'_>], long: bool) -> Option<String> { |
| 1650 | + let (names, chain) = route_context(spec, route)?; |
1425 | 1651 | Some(if long { |
1426 | 1652 | long_help(spec, &names, &chain) |
1427 | 1653 | } else { |
1428 | 1654 | short_help(spec, &names, &chain) |
1429 | 1655 | }) |
1430 | 1656 | } |
| 1657 | + |
| 1658 | +/// Render a route-specific help page with an explicit colour policy. |
| 1659 | +pub fn render_at_styled( |
| 1660 | + spec: &Spec<'_>, |
| 1661 | + route: &[&Command<'_>], |
| 1662 | + long: bool, |
| 1663 | + style: Style, |
| 1664 | +) -> Option<String> { |
| 1665 | + let (path, chain) = route_context(spec, route)?; |
| 1666 | + let page = if long { |
| 1667 | + long_help(spec, &path, &chain) |
| 1668 | + } else { |
| 1669 | + short_help(spec, &path, &chain) |
| 1670 | + }; |
| 1671 | + let (headings, flag_usages, synopsis) = help_structure(spec, &path, &chain, long); |
| 1672 | + Some(styled_help( |
| 1673 | + &page, |
| 1674 | + style, |
| 1675 | + &headings, |
| 1676 | + &flag_usages, |
| 1677 | + &synopsis, |
| 1678 | + )) |
| 1679 | +} |
| 1680 | + |
| 1681 | +#[cfg(test)] |
| 1682 | +mod style_tests { |
| 1683 | + use super::{styled_help, Style}; |
| 1684 | + |
| 1685 | + #[test] |
| 1686 | + fn coloured_help_styles_structure_without_changing_plain_text() { |
| 1687 | + let page = "A summary ending in:\nUsage: prose is not a synopsis\nExamples:\n\nUsage: ex [OPTIONS]\n ex --all\n\nOptions:\n -f, --force Force it\n [possible values: --auto]\n (default: -1)\n"; |
| 1688 | + let headings = vec!["Options".to_string()]; |
| 1689 | + let usages = vec!["-f, --force".to_string()]; |
| 1690 | + let synopsis = vec![ |
| 1691 | + "Usage: ex [OPTIONS]".to_string(), |
| 1692 | + " ex --all".to_string(), |
| 1693 | + ]; |
| 1694 | + assert_eq!( |
| 1695 | + styled_help(page, Style::PLAIN, &headings, &usages, &synopsis), |
| 1696 | + page |
| 1697 | + ); |
| 1698 | + |
| 1699 | + let coloured = styled_help(page, Style::COLOURED, &headings, &usages, &synopsis); |
| 1700 | + assert!(coloured.contains("\u{1b}[1;4;32mUsage:\u{1b}[0m")); |
| 1701 | + assert!(coloured.contains("\u{1b}[1;4;32mOptions:\u{1b}[0m")); |
| 1702 | + assert!(coloured.contains("\u{1b}[36m-f\u{1b}[0m")); |
| 1703 | + assert!(coloured.contains("\u{1b}[36m--force\u{1b}[0m")); |
| 1704 | + assert!(coloured.contains("A summary ending in:\nUsage: prose is not a synopsis")); |
| 1705 | + assert!(coloured.contains("Usage: prose is not a synopsis\nExamples:")); |
| 1706 | + assert!(coloured.contains("\u{1b}[36m ex --all\u{1b}[0m")); |
| 1707 | + assert!(coloured.contains("[possible values: --auto]")); |
| 1708 | + assert!(coloured.contains("(default: -1)")); |
| 1709 | + assert_eq!(strip_ansi(&coloured), page); |
| 1710 | + } |
| 1711 | + |
| 1712 | + fn strip_ansi(text: &str) -> String { |
| 1713 | + let mut out = String::new(); |
| 1714 | + let mut chars = text.chars().peekable(); |
| 1715 | + while let Some(ch) = chars.next() { |
| 1716 | + if ch == '\u{1b}' && chars.peek() == Some(&'[') { |
| 1717 | + chars.next(); |
| 1718 | + for code in chars.by_ref() { |
| 1719 | + if code == 'm' { |
| 1720 | + break; |
| 1721 | + } |
| 1722 | + } |
| 1723 | + } else { |
| 1724 | + out.push(ch); |
| 1725 | + } |
| 1726 | + } |
| 1727 | + out |
| 1728 | + } |
| 1729 | +} |