@@ -29,6 +29,195 @@ 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>, String) { |
| 112 | + let meta = *chain.last().expect("a page is always about some command"); |
| 113 | + let mut headings = vec!["Examples".to_string()]; |
| 114 | + if meta.subcommands.iter().any(|sub| !sub.hide) { |
| 115 | + headings.push( |
| 116 | + meta.subcommand_help_heading |
| 117 | + .unwrap_or("Commands") |
| 118 | + .to_string(), |
| 119 | + ); |
| 120 | + } |
| 121 | + |
| 122 | + let (own, inherited) = own_and_global(chain); |
| 123 | + let visible_arg = |arg: &&ArgMeta<'_>| { |
| 124 | + !arg.hide |
| 125 | + && if long { |
| 126 | + !arg.hide_long_help |
| 127 | + } else { |
| 128 | + !arg.hide_short_help |
| 129 | + } |
| 130 | + }; |
| 131 | + let args: Vec<_> = meta.args.iter().filter(visible_arg).collect(); |
| 132 | + if args.iter().any(|arg| arg.help_heading.is_none()) { |
| 133 | + headings.push("Arguments".to_string()); |
| 134 | + } |
| 135 | + headings.extend( |
| 136 | + args.iter() |
| 137 | + .filter_map(|arg| arg.help_heading) |
| 138 | + .map(str::to_string), |
| 139 | + ); |
| 140 | + |
| 141 | + let visible_flag = |flag: &&FlagMeta<'_>| { |
| 142 | + !flag.hide |
| 143 | + && if long { |
| 144 | + !flag.hide_long_help |
| 145 | + } else { |
| 146 | + !flag.hide_short_help |
| 147 | + } |
| 148 | + }; |
| 149 | + let own: Vec<_> = own.into_iter().filter(visible_flag).collect(); |
| 150 | + let inherited: Vec<_> = inherited |
| 151 | + .into_iter() |
| 152 | + .filter(|(flag, _)| { |
| 153 | + if long { |
| 154 | + !flag.hide_long_help |
| 155 | + } else { |
| 156 | + !flag.hide_short_help |
| 157 | + } |
| 158 | + }) |
| 159 | + .collect(); |
| 160 | + if own.iter().any(|flag| flag.help_heading.is_none()) { |
| 161 | + headings.push("Flags".to_string()); |
| 162 | + } |
| 163 | + headings.extend( |
| 164 | + own.iter() |
| 165 | + .filter_map(|flag| flag.help_heading) |
| 166 | + .map(str::to_string), |
| 167 | + ); |
| 168 | + if !inherited.is_empty() { |
| 169 | + headings.push("Global flags".to_string()); |
| 170 | + } |
| 171 | + |
| 172 | + let mut flag_usages: Vec<String> = own.iter().map(|flag| column_usage(flag)).collect(); |
| 173 | + flag_usages.extend(inherited.into_iter().map(|(_, usage)| usage)); |
| 174 | + flag_usages.sort_by_key(|usage| core::cmp::Reverse(usage.len())); |
| 175 | + |
| 176 | + let mut synopsis = String::new(); |
| 177 | + usage_section(&mut synopsis, spec, path, meta); |
| 178 | + (headings, flag_usages, synopsis.trim_end().to_string()) |
| 179 | +} |
| 180 | + |
| 181 | +fn styled_help( |
| 182 | + page: &str, |
| 183 | + style: Style, |
| 184 | + headings: &[String], |
| 185 | + flag_usages: &[String], |
| 186 | + synopsis: &str, |
| 187 | +) -> String { |
| 188 | + if !style.coloured { |
| 189 | + return page.to_string(); |
| 190 | + } |
| 191 | + let mut out = String::with_capacity(page.len()); |
| 192 | + for line in page.split_inclusive('\n') { |
| 193 | + let (body, newline) = line |
| 194 | + .strip_suffix('\n') |
| 195 | + .map_or((line, ""), |body| (body, "\n")); |
| 196 | + if body == synopsis && body.starts_with("Usage:") { |
| 197 | + let usage = body.strip_prefix("Usage:").unwrap_or_default(); |
| 198 | + out.push_str(&style.heading("Usage:")); |
| 199 | + out.push_str(&style.literal(usage)); |
| 200 | + } else if body |
| 201 | + .strip_suffix(':') |
| 202 | + .is_some_and(|heading| headings.iter().any(|known| known == heading)) |
| 203 | + { |
| 204 | + out.push_str(&style.heading(body)); |
| 205 | + } else { |
| 206 | + let styled = body.strip_prefix(" ").and_then(|entry| { |
| 207 | + flag_usages.iter().find_map(|usage| { |
| 208 | + entry |
| 209 | + .strip_prefix(usage) |
| 210 | + .filter(|rest| rest.is_empty() || rest.starts_with(char::is_whitespace)) |
| 211 | + .map(|rest| format!(" {}{rest}", styled_flag_usage(usage, style))) |
| 212 | + }) |
| 213 | + }); |
| 214 | + out.push_str(styled.as_deref().unwrap_or(body)); |
| 215 | + } |
| 216 | + out.push_str(newline); |
| 217 | + } |
| 218 | + out |
| 219 | +} |
| 220 | + |
32 | 221 | /// The `Usage:` line's body, without the `Usage: ` prefix. |
33 | 222 | /// |
34 | 223 | /// `path` is the command as invoked, starting with the binary: `["mise", "config", "ls"]`. |
@@ -1341,6 +1530,29 @@ pub fn render(spec: &Spec<'_>, cmd: &Command<'_>, long: bool) -> Option<String> |
1341 | 1530 | }) |
1342 | 1531 | } |
1343 | 1532 |
|
| 1533 | +/// Render a help page with an explicit colour policy. |
| 1534 | +pub fn render_styled( |
| 1535 | + spec: &Spec<'_>, |
| 1536 | + cmd: &Command<'_>, |
| 1537 | + long: bool, |
| 1538 | + style: Style, |
| 1539 | +) -> Option<String> { |
| 1540 | + let (path, chain) = find(spec, cmd)?; |
| 1541 | + let page = if long { |
| 1542 | + long_help(spec, &path, &chain) |
| 1543 | + } else { |
| 1544 | + short_help(spec, &path, &chain) |
| 1545 | + }; |
| 1546 | + let (headings, flag_usages, synopsis) = help_structure(spec, &path, &chain, long); |
| 1547 | + Some(styled_help( |
| 1548 | + &page, |
| 1549 | + style, |
| 1550 | + &headings, |
| 1551 | + &flag_usages, |
| 1552 | + &synopsis, |
| 1553 | + )) |
| 1554 | +} |
| 1555 | + |
1344 | 1556 | /// The route the words took to a command, for rendering its page unambiguously. |
1345 | 1557 | /// |
1346 | 1558 | /// Rebuilt by re-parsing, because [`Error::Help`](crate::Error::Help) carries the command and |
@@ -1408,7 +1620,10 @@ pub fn route_to<'t>( |
1408 | 1620 | /// The route tells them apart, and the parser has it — `Parser::command_path` is the sequence of |
1409 | 1621 | /// commands the words actually went through. Callers holding only a command keep [`render`] and |
1410 | 1622 | /// its answer; callers that parsed something should prefer this. |
1411 | | -pub fn render_at(spec: &Spec<'_>, route: &[&Command<'_>], long: bool) -> Option<String> { |
| 1623 | +fn route_context<'a>( |
| 1624 | + spec: &'a Spec<'a>, |
| 1625 | + route: &[&Command<'_>], |
| 1626 | +) -> Option<(Vec<&'a str>, Vec<&'a CommandMeta<'a>>)> { |
1412 | 1627 | let mut names = vec![spec.bin.unwrap_or(spec.name)]; |
1413 | 1628 | let mut chain = vec![spec.root]; |
1414 | 1629 | for cmd in route.iter().skip(1) { |
@@ -1422,9 +1637,82 @@ pub fn render_at(spec: &Spec<'_>, route: &[&Command<'_>], long: bool) -> Option< |
1422 | 1637 | names.push(next.cmd.name); |
1423 | 1638 | chain.push(next); |
1424 | 1639 | } |
| 1640 | + Some((names, chain)) |
| 1641 | +} |
| 1642 | + |
| 1643 | +pub fn render_at(spec: &Spec<'_>, route: &[&Command<'_>], long: bool) -> Option<String> { |
| 1644 | + let (names, chain) = route_context(spec, route)?; |
1425 | 1645 | Some(if long { |
1426 | 1646 | long_help(spec, &names, &chain) |
1427 | 1647 | } else { |
1428 | 1648 | short_help(spec, &names, &chain) |
1429 | 1649 | }) |
1430 | 1650 | } |
| 1651 | + |
| 1652 | +/// Render a route-specific help page with an explicit colour policy. |
| 1653 | +pub fn render_at_styled( |
| 1654 | + spec: &Spec<'_>, |
| 1655 | + route: &[&Command<'_>], |
| 1656 | + long: bool, |
| 1657 | + style: Style, |
| 1658 | +) -> Option<String> { |
| 1659 | + let (path, chain) = route_context(spec, route)?; |
| 1660 | + let page = if long { |
| 1661 | + long_help(spec, &path, &chain) |
| 1662 | + } else { |
| 1663 | + short_help(spec, &path, &chain) |
| 1664 | + }; |
| 1665 | + let (headings, flag_usages, synopsis) = help_structure(spec, &path, &chain, long); |
| 1666 | + Some(styled_help( |
| 1667 | + &page, |
| 1668 | + style, |
| 1669 | + &headings, |
| 1670 | + &flag_usages, |
| 1671 | + &synopsis, |
| 1672 | + )) |
| 1673 | +} |
| 1674 | + |
| 1675 | +#[cfg(test)] |
| 1676 | +mod style_tests { |
| 1677 | + use super::{styled_help, Style}; |
| 1678 | + |
| 1679 | + #[test] |
| 1680 | + fn coloured_help_styles_structure_without_changing_plain_text() { |
| 1681 | + let page = "A summary ending in:\nUsage: prose is not a synopsis\n\nUsage: ex [OPTIONS]\n\nOptions:\n -f, --force Force it\n [possible values: --auto]\n (default: -1)\n"; |
| 1682 | + let headings = vec!["Options".to_string()]; |
| 1683 | + let usages = vec!["-f, --force".to_string()]; |
| 1684 | + let synopsis = "Usage: ex [OPTIONS]"; |
| 1685 | + assert_eq!( |
| 1686 | + styled_help(page, Style::PLAIN, &headings, &usages, synopsis), |
| 1687 | + page |
| 1688 | + ); |
| 1689 | + |
| 1690 | + let coloured = styled_help(page, Style::COLOURED, &headings, &usages, synopsis); |
| 1691 | + assert!(coloured.contains("\u{1b}[1;4;32mUsage:\u{1b}[0m")); |
| 1692 | + assert!(coloured.contains("\u{1b}[1;4;32mOptions:\u{1b}[0m")); |
| 1693 | + assert!(coloured.contains("\u{1b}[36m-f\u{1b}[0m")); |
| 1694 | + assert!(coloured.contains("\u{1b}[36m--force\u{1b}[0m")); |
| 1695 | + assert!(coloured.contains("A summary ending in:\nUsage: prose is not a synopsis")); |
| 1696 | + assert!(coloured.contains("[possible values: --auto]")); |
| 1697 | + assert!(coloured.contains("(default: -1)")); |
| 1698 | + assert_eq!(strip_ansi(&coloured), page); |
| 1699 | + } |
| 1700 | + |
| 1701 | + fn strip_ansi(text: &str) -> String { |
| 1702 | + let mut out = String::new(); |
| 1703 | + let mut chars = text.chars().peekable(); |
| 1704 | + while let Some(ch) = chars.next() { |
| 1705 | + if ch == '\u{1b}' && chars.peek() == Some(&'[') { |
| 1706 | + chars.next(); |
| 1707 | + for code in chars.by_ref() { |
| 1708 | + if code == 'm' { |
| 1709 | + break; |
| 1710 | + } |
| 1711 | + } |
| 1712 | + } else { |
| 1713 | + out.push(ch); |
| 1714 | + } |
| 1715 | + } |
| 1716 | + out |
| 1717 | + } |
| 1718 | +} |