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@c042f23

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • PLAN.md
  • argv/src
    • diagnostic.rs
    • 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/diagnostic.rs‎

Copy file name to clipboardExpand all lines: argv/src/diagnostic.rs
+12-1Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -556,7 +556,12 @@ pub fn render(
556556
// clap prints the command's help page here, including the available subcommands,
557557
// while keeping exit 2; an error plus only `<SUBCOMMAND>` tells the reader what is
558558
// missing and withholds the list they need to fix it.
559-
if let Some(help) = crate::help::render_at(spec, &taken, false) {
559+
let help_style = if style == Style::COLOURED {
560+
crate::help::Style::COLOURED
561+
} else {
562+
crate::help::Style::PLAIN
563+
};
564+
if let Some(help) = crate::help::render_at_styled(spec, &taken, false, help_style) {
560565
return help;
561566
}
562567
with_usage = true;
@@ -923,6 +928,12 @@ mod tests {
923928
assert!(message.contains("use"), "{message}");
924929
assert!(message.contains("user"), "{message}");
925930
assert!(!message.contains("requires a subcommand"), "{message}");
931+
932+
let coloured = render(&SPEC, &[], &Error::MissingSubcommand, Style::COLOURED);
933+
assert!(
934+
coloured.contains("\u{1b}[1;4;32mCommands:\u{1b}[0m"),
935+
"{coloured}"
936+
);
926937
}
927938

928939
#[test]
Collapse file

‎argv/src/help.rs‎

Copy file name to clipboardExpand all lines: argv/src/help.rs
+300-1Lines changed: 300 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,201 @@ 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>, 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+
32227
/// The `Usage:` line's body, without the `Usage: ` prefix.
33228
///
34229
/// `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>
13411536
})
13421537
}
13431538

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+
13441562
/// The route the words took to a command, for rendering its page unambiguously.
13451563
///
13461564
/// Rebuilt by re-parsing, because [`Error::Help`](crate::Error::Help) carries the command and
@@ -1408,7 +1626,10 @@ pub fn route_to<'t>(
14081626
/// The route tells them apart, and the parser has it — `Parser::command_path` is the sequence of
14091627
/// commands the words actually went through. Callers holding only a command keep [`render`] and
14101628
/// 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>>)> {
14121633
let mut names = vec![spec.bin.unwrap_or(spec.name)];
14131634
let mut chain = vec![spec.root];
14141635
for cmd in route.iter().skip(1) {
@@ -1422,9 +1643,87 @@ pub fn render_at(spec: &Spec<'_>, route: &[&Command<'_>], long: bool) -> Option<
14221643
names.push(next.cmd.name);
14231644
chain.push(next);
14241645
}
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)?;
14251651
Some(if long {
14261652
long_help(spec, &names, &chain)
14271653
} else {
14281654
short_help(spec, &names, &chain)
14291655
})
14301656
}
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+
}
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 {

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.