GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — feat(docs): color process-facing help · jdx/usage@d8e93ee

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • PLAN.md
  • argv/src
    • help.rs
  • derive/src
    • codegen.rs
  • docs/rust
    • clap-compatibility.md
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎PLAN.md‎

Copy file name to clipboardExpand all lines: PLAN.md
+4-2Lines changed: 4 additions & 2 deletions
  • Display the source diff
  • Display the rich diff
Original file line numberDiff line numberDiff line change
@@ -524,8 +524,10 @@ Groups are the opposite case: `Command::get_groups`, `ArgGroup::get_args` and
524524

525525
**Help output**
526526

527-
- [ ] **Colour.** Errors are styled (`argv/src/diagnostic.rs`); help is not. clap
528-
colours headings and flag names by default and exposes `Command::styles`.
527+
- [x] **Colour.** Process-facing help colours headings, usage literals, and flag
528+
names automatically, honoring `NO_COLOR` and `CLICOLOR_FORCE`; explicit
529+
plain/coloured rendering stays available for tests and generated artifacts.
530+
clap's arbitrary `Command::styles` palette is intentionally not reproduced.
529531
- [ ] **`term_width` / `max_term_width`** — we wrap to `COLUMNS` and take no
530532
instruction about it.
531533
- [x] **The granular hides** — `hide_default_value`, `hide_env`, `hide_env_values`,
Collapse file

‎argv/src/help.rs‎

Copy file name to clipboardExpand all lines: argv/src/help.rs
+289-1Lines changed: 289 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,195 @@ use crate::DoubleDash;
2929
/// `[FLAGS]` or `[ARGS]…` and the sections below carry the detail.
3030
const INLINE_LIMIT: usize = 2;
3131

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+
32221
/// The `Usage:` line's body, without the `Usage: ` prefix.
33222
///
34223
/// `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>
13411530
})
13421531
}
13431532

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+
13441556
/// The route the words took to a command, for rendering its page unambiguously.
13451557
///
13461558
/// Rebuilt by re-parsing, because [`Error::Help`](crate::Error::Help) carries the command and
@@ -1408,7 +1620,10 @@ pub fn route_to<'t>(
14081620
/// The route tells them apart, and the parser has it — `Parser::command_path` is the sequence of
14091621
/// commands the words actually went through. Callers holding only a command keep [`render`] and
14101622
/// 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>>)> {
14121627
let mut names = vec![spec.bin.unwrap_or(spec.name)];
14131628
let mut chain = vec![spec.root];
14141629
for cmd in route.iter().skip(1) {
@@ -1422,9 +1637,82 @@ pub fn render_at(spec: &Spec<'_>, route: &[&Command<'_>], long: bool) -> Option<
14221637
names.push(next.cmd.name);
14231638
chain.push(next);
14241639
}
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)?;
14251645
Some(if long {
14261646
long_help(spec, &names, &chain)
14271647
} else {
14281648
short_help(spec, &names, &chain)
14291649
})
14301650
}
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+
}
Collapse file

‎derive/src/codegen.rs‎

Copy file name to clipboardExpand all lines: derive/src/codegen.rs
+12-2Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -771,10 +771,20 @@ pub fn emit(cli: &Cli) -> TokenStream {
771771
cmd,
772772
) {
773773
::std::option::Option::Some(route) => {
774-
usage_argv::help::render_at(__usage_spec, &route, long)
774+
usage_argv::help::render_at_styled(
775+
__usage_spec,
776+
&route,
777+
long,
778+
usage_argv::help::Style::auto(),
779+
)
775780
}
776781
::std::option::Option::None => {
777-
usage_argv::help::render(__usage_spec, cmd, long)
782+
usage_argv::help::render_styled(
783+
__usage_spec,
784+
cmd,
785+
long,
786+
usage_argv::help::Style::auto(),
787+
)
778788
}
779789
};
780790
match __usage_page {
Collapse file

‎docs/rust/clap-compatibility.md‎

Copy file name to clipboardExpand all lines: docs/rust/clap-compatibility.md
+1-1Lines changed: 1 addition & 1 deletion
  • Display the source diff
  • Display the rich diff
Original file line numberDiff line numberDiff line change
@@ -117,7 +117,7 @@ the Rust declaration, not only from generated KDL, wherever the bridge column sa
117117
| `rename_all`, `rename_all_env` | yes | n/a | yes | yes | yes | n/a | Full clap casing vocabulary; bare `env` uses the environment casing policy. |
118118
| `help_template`, `next_line_help`, `flatten_help` | no | n/a | no | no | no | no | No equivalent yet. |
119119
| `term_width`, `max_term_width` | no | n/a | no | no | no | no | Help wraps using `COLUMNS`. |
120-
| help styles and color | n/a | n/a | n/a | n/a | lossy | no | Diagnostics are styled; help is not. |
120+
| 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. |
121121
| 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. |
122122
| `--version` / `-V`, dynamic version | yes | yes | yes | yes | yes | yes | Literal and runtime versions propagate through nested commands. |
123123
| completion generation | yes | yes | yes | yes | lossy | yes | Bash, fish, Nushell, PowerShell, and zsh plus runtime overlays are supported; Elvish is not. |

0 commit comments

Comments
0 (0)
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.