Add themes to help command when available #10318 (#10623)

# Description
The issue #10318 is resolved by introducing helper methods within the
existing `get_documentation` function in the nu-engine crate. Initially,
I considered using nu-color-config crate to convert HEX config color to
ANSI color and employing the following method
[https://github.com/nushell/nushell/blob/main/crates/nu-color-config/src/color_config.rs#L9C1-L20C2](https://github.com/nushell/nushell/blob/main/crates/nu-color-config/src/color_config.rs#L9C1-L20C2).
However, this approach was deemed impractical due to circular
dependencies. Consequently, in a manner akin to how we invoke the
`table` command from the nu-command crate in `get_documentation`
function to create a themed-colored table, we invoke the `ansi` command
from nu-command to obtain the ANSI theme color code.

# User-Facing Changes
Visual Changes Only: the help command now uses configured theme, else it
falls back on default hard coded values.


# Tests + Formatting
<!--
Don't forget to add tests that cover your changes.

Make sure you've run and fixed any issues with these commands:

- `cargo fmt --all -- --check` to check standard code formatting (`cargo
fmt --all` applies these changes)
- `cargo clippy --workspace -- -D warnings -D clippy::unwrap_used` to
check that you're using the standard code style
- `cargo test --workspace` to check that all tests pass (on Windows make
sure to [enable developer
mode](https://learn.microsoft.com/en-us/windows/apps/get-started/developer-mode-features-and-debugging))
- `cargo run -- -c "use std testing; testing run-tests --path
crates/nu-std"` to run the tests for the standard library

> **Note**
> from `nushell` you can also use the `toolkit` as follows
> ```bash
> use toolkit.nu # or use an `env_change` hook to activate it
automatically
> toolkit check pr
> ```
-->

# After Submitting
<!-- If your PR had any user-facing changes, update [the
documentation](https://github.com/nushell/nushell.github.io) after the
PR is merged, if necessary. This will help us keep the docs up to date.
-->
This commit is contained in:
Dany Pham 2023-10-10 08:40:05 -04:00 committed by GitHub
parent 8a77d1ed92
commit b634f1b010
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 167 additions and 39 deletions

View File

@ -57,7 +57,7 @@ impl NuHelpCompleter {
let _ = write!(long_desc, "Usage:\r\n > {}\r\n", sig.call_signature());
if !sig.named.is_empty() {
long_desc.push_str(&get_flags_section(sig, |v| {
long_desc.push_str(&get_flags_section(Some(&*self.0.clone()), sig, |v| {
v.into_string_parsable(", ", &self.0.config)
}))
}

View File

@ -1,7 +1,9 @@
use nu_protocol::ast::{Argument, Expr, Expression};
use nu_protocol::{
ast::Call,
engine::{EngineState, Stack},
record, Category, Example, IntoPipelineData, PipelineData, Signature, Span, SyntaxShape, Value,
record, Category, Example, IntoPipelineData, PipelineData, Signature, Span, SyntaxShape, Type,
Value,
};
use std::{collections::HashMap, fmt::Write};
@ -68,10 +70,15 @@ fn get_documentation(
) -> String {
// Create ansi colors
//todo make these configurable -- pull from enginestate.config
const G: &str = "\x1b[32m"; // green
const C: &str = "\x1b[36m"; // cyan
// was const BB: &str = "\x1b[1;34m"; // bold blue
const BB: &str = "\x1b[94m"; // light blue (nobold, should be bolding the *names*)
let help_section_name: String =
get_ansi_color_for_component_or_default(engine_state, "shape_string", "\x1b[32m"); // default: green
let help_subcolor_one: String =
get_ansi_color_for_component_or_default(engine_state, "shape_external", "\x1b[36m"); // default: cyan
// was const bb: &str = "\x1b[1;34m"; // bold blue
let help_subcolor_two: String =
get_ansi_color_for_component_or_default(engine_state, "shape_block", "\x1b[94m"); // default: light blue (nobold, should be bolding the *names*)
const RESET: &str = "\x1b[0m"; // reset
let cmd_name = &sig.name;
@ -97,32 +104,40 @@ fn get_documentation(
// Don't display removed/deprecated commands in the Subcommands list
&& !matches!(sig.category, Category::Removed)
{
subcommands.push(format!(" {C}{}{RESET} - {}", sig.name, sig.usage));
subcommands.push(format!(
" {help_subcolor_one}{}{RESET} - {}",
sig.name, sig.usage
));
}
}
}
if !sig.search_terms.is_empty() {
let text = format!(
"{G}Search terms{RESET}: {C}{}{}\n\n",
"{help_section_name}Search terms{RESET}: {help_subcolor_one}{}{}\n\n",
sig.search_terms.join(", "),
RESET
);
let _ = write!(long_desc, "{text}");
}
let text = format!("{}Usage{}:\n > {}\n", G, RESET, sig.call_signature());
let text = format!(
"{}Usage{}:\n > {}\n",
help_section_name,
RESET,
sig.call_signature()
);
let _ = write!(long_desc, "{text}");
if !subcommands.is_empty() {
let _ = write!(long_desc, "\n{G}Subcommands{RESET}:\n");
let _ = write!(long_desc, "\n{help_section_name}Subcommands{RESET}:\n");
subcommands.sort();
long_desc.push_str(&subcommands.join("\n"));
long_desc.push('\n');
}
if !sig.named.is_empty() {
long_desc.push_str(&get_flags_section(sig, |v| {
long_desc.push_str(&get_flags_section(Some(engine_state), sig, |v| {
nu_highlight_string(
&v.into_string_parsable(", ", &engine_state.config),
engine_state,
@ -135,12 +150,12 @@ fn get_documentation(
|| !sig.optional_positional.is_empty()
|| sig.rest_positional.is_some()
{
let _ = write!(long_desc, "\n{G}Parameters{RESET}:\n");
let _ = write!(long_desc, "\n{help_section_name}Parameters{RESET}:\n");
for positional in &sig.required_positional {
let text = match &positional.shape {
SyntaxShape::Keyword(kw, shape) => {
format!(
" {C}\"{}\" + {RESET}<{BB}{}{RESET}>: {}",
" {help_subcolor_one}\"{}\" + {RESET}<{help_subcolor_two}{}{RESET}>: {}",
String::from_utf8_lossy(kw),
document_shape(*shape.clone()),
positional.desc
@ -148,7 +163,7 @@ fn get_documentation(
}
_ => {
format!(
" {C}{}{RESET} <{BB}{}{RESET}>: {}",
" {help_subcolor_one}{}{RESET} <{help_subcolor_two}{}{RESET}>: {}",
positional.name,
document_shape(positional.shape.clone()),
positional.desc
@ -161,7 +176,7 @@ fn get_documentation(
let text = match &positional.shape {
SyntaxShape::Keyword(kw, shape) => {
format!(
" {C}\"{}\" + {RESET}<{BB}{}{RESET}>: {} (optional)",
" {help_subcolor_one}\"{}\" + {RESET}<{help_subcolor_two}{}{RESET}>: {} (optional)",
String::from_utf8_lossy(kw),
document_shape(*shape.clone()),
positional.desc
@ -182,7 +197,7 @@ fn get_documentation(
};
format!(
" {C}{}{RESET} <{BB}{}{RESET}>: {}{}",
" {help_subcolor_one}{}{RESET} <{help_subcolor_two}{}{RESET}>: {}{}",
positional.name,
document_shape(positional.shape.clone()),
positional.desc,
@ -195,7 +210,7 @@ fn get_documentation(
if let Some(rest_positional) = &sig.rest_positional {
let text = format!(
" ...{C}{}{RESET} <{BB}{}{RESET}>: {}",
" ...{help_subcolor_one}{}{RESET} <{help_subcolor_two}{}{RESET}>: {}",
rest_positional.name,
document_shape(rest_positional.shape.clone()),
rest_positional.desc
@ -234,7 +249,7 @@ fn get_documentation(
PipelineData::Value(Value::list(vals, span), None),
) {
if let Ok((str, ..)) = result.collect_string_strict(span) {
let _ = writeln!(long_desc, "\n{G}Input/output types{RESET}:");
let _ = writeln!(long_desc, "\n{help_section_name}Input/output types{RESET}:");
for line in str.lines() {
let _ = writeln!(long_desc, " {line}");
}
@ -244,7 +259,7 @@ fn get_documentation(
}
if !examples.is_empty() {
let _ = write!(long_desc, "\n{G}Examples{RESET}:");
let _ = write!(long_desc, "\n{help_section_name}Examples{RESET}:");
}
for example in examples {
@ -318,6 +333,93 @@ fn get_documentation(
}
}
fn get_ansi_color_for_component_or_default(
engine_state: &EngineState,
theme_component: &str,
default: &str,
) -> String {
if let Some(color) = &engine_state.get_config().color_config.get(theme_component) {
let mut caller_stack = Stack::new();
let span = Span::unknown();
let argument_opt = get_argument_for_color_value(engine_state, color, span);
// Call ansi command using argument
if let Some(argument) = argument_opt {
if let Some(decl_id) = engine_state.find_decl(b"ansi", &[]) {
if let Ok(result) = eval_call(
engine_state,
&mut caller_stack,
&Call {
decl_id,
head: span,
arguments: vec![argument],
redirect_stdout: true,
redirect_stderr: true,
parser_info: HashMap::new(),
},
PipelineData::Empty,
) {
if let Ok((str, ..)) = result.collect_string_strict(span) {
return str;
}
}
}
}
}
default.to_string()
}
fn get_argument_for_color_value(
engine_state: &EngineState,
color: &&Value,
span: Span,
) -> Option<Argument> {
match color {
Value::Record { val, .. } => {
let record_exp: Vec<(Expression, Expression)> = val
.into_iter()
.map(|(k, v)| {
(
Expression {
expr: Expr::String(k.clone()),
span,
ty: Type::String,
custom_completion: None,
},
Expression {
expr: Expr::String(
v.clone().into_string("", engine_state.get_config()),
),
span,
ty: Type::String,
custom_completion: None,
},
)
})
.collect();
Some(Argument::Positional(Expression {
span: Span::unknown(),
ty: Type::Record(vec![
("fg".to_string(), Type::String),
("attr".to_string(), Type::String),
]),
expr: Expr::Record(record_exp),
custom_completion: None,
}))
}
Value::String { val, .. } => Some(Argument::Positional(Expression {
span: Span::unknown(),
ty: Type::String,
expr: Expr::String(val.clone()),
custom_completion: None,
})),
_ => None,
}
}
// document shape helps showing more useful information
pub fn document_shape(shape: SyntaxShape) -> SyntaxShape {
match shape {
@ -327,6 +429,7 @@ pub fn document_shape(shape: SyntaxShape) -> SyntaxShape {
}
pub fn get_flags_section<F>(
engine_state_opt: Option<&EngineState>,
signature: &Signature,
mut value_formatter: F, // format default Value (because some calls cant access config or nu-highlight)
) -> String
@ -334,18 +437,38 @@ where
F: FnMut(&nu_protocol::Value) -> String,
{
//todo make these configurable -- pull from enginestate.config
const G: &str = "\x1b[32m"; // green
const C: &str = "\x1b[36m"; // cyan
// was const BB: &str = "\x1b[1;34m"; // bold blue
const BB: &str = "\x1b[94m"; // light blue (nobold, should be bolding the *names*)
let help_section_name: String;
let help_subcolor_one: String;
let help_subcolor_two: String;
// Sometimes we want to get the flags without engine_state
// For example, in nu-plugin. In that case, we fall back on default values
if let Some(engine_state) = engine_state_opt {
help_section_name =
get_ansi_color_for_component_or_default(engine_state, "shape_string", "\x1b[32m"); // default: green
help_subcolor_one =
get_ansi_color_for_component_or_default(engine_state, "shape_external", "\x1b[36m"); // default: cyan
// was const bb: &str = "\x1b[1;34m"; // bold blue
help_subcolor_two =
get_ansi_color_for_component_or_default(engine_state, "shape_block", "\x1b[94m");
// default: light blue (nobold, should be bolding the *names*)
} else {
help_section_name = "\x1b[32m".to_string();
help_subcolor_one = "\x1b[36m".to_string();
help_subcolor_two = "\x1b[94m".to_string();
}
const RESET: &str = "\x1b[0m"; // reset
const D: &str = "\x1b[39m"; // default
let mut long_desc = String::new();
let _ = write!(long_desc, "\n{G}Flags{RESET}:\n");
let _ = write!(long_desc, "\n{help_section_name}Flags{RESET}:\n");
for flag in &signature.named {
let default_str = if let Some(value) = &flag.default_value {
format!(" (default: {BB}{}{RESET})", &value_formatter(value))
format!(
" (default: {help_subcolor_two}{}{RESET})",
&value_formatter(value)
)
} else {
"".to_string()
};
@ -354,10 +477,10 @@ where
if let Some(short) = flag.short {
if flag.required {
format!(
" {C}-{}{}{RESET} (required parameter) {:?} - {}{}\n",
" {help_subcolor_one}-{}{}{RESET} (required parameter) {:?} - {}{}\n",
short,
if !flag.long.is_empty() {
format!("{D},{RESET} {C}--{}", flag.long)
format!("{D},{RESET} {help_subcolor_one}--{}", flag.long)
} else {
"".into()
},
@ -367,10 +490,10 @@ where
)
} else {
format!(
" {C}-{}{}{RESET} <{BB}{:?}{RESET}> - {}{}\n",
" {help_subcolor_one}-{}{}{RESET} <{help_subcolor_two}{:?}{RESET}> - {}{}\n",
short,
if !flag.long.is_empty() {
format!("{D},{RESET} {C}--{}", flag.long)
format!("{D},{RESET} {help_subcolor_one}--{}", flag.long)
} else {
"".into()
},
@ -381,22 +504,22 @@ where
}
} else if flag.required {
format!(
" {C}--{}{RESET} (required parameter) <{BB}{:?}{RESET}> - {}{}\n",
" {help_subcolor_one}--{}{RESET} (required parameter) <{help_subcolor_two}{:?}{RESET}> - {}{}\n",
flag.long, arg, flag.desc, default_str,
)
} else {
format!(
" {C}--{}{RESET} <{BB}{:?}{RESET}> - {}{}\n",
" {help_subcolor_one}--{}{RESET} <{help_subcolor_two}{:?}{RESET}> - {}{}\n",
flag.long, arg, flag.desc, default_str,
)
}
} else if let Some(short) = flag.short {
if flag.required {
format!(
" {C}-{}{}{RESET} (required parameter) - {}{}\n",
" {help_subcolor_one}-{}{}{RESET} (required parameter) - {}{}\n",
short,
if !flag.long.is_empty() {
format!("{D},{RESET} {C}--{}", flag.long)
format!("{D},{RESET} {help_subcolor_one}--{}", flag.long)
} else {
"".into()
},
@ -405,10 +528,10 @@ where
)
} else {
format!(
" {C}-{}{}{RESET} - {}{}\n",
" {help_subcolor_one}-{}{}{RESET} - {}{}\n",
short,
if !flag.long.is_empty() {
format!("{D},{RESET} {C}--{}", flag.long)
format!("{D},{RESET} {help_subcolor_one}--{}", flag.long)
} else {
"".into()
},
@ -418,11 +541,14 @@ where
}
} else if flag.required {
format!(
" {C}--{}{RESET} (required parameter) - {}{}\n",
" {help_subcolor_one}--{}{RESET} (required parameter) - {}{}\n",
flag.long, flag.desc, default_str,
)
} else {
format!(" {C}--{}{RESET} - {}\n", flag.long, flag.desc)
format!(
" {help_subcolor_one}--{}{RESET} - {}\n",
flag.long, flag.desc
)
};
long_desc.push_str(&msg);
}

View File

@ -385,7 +385,7 @@ fn print_help(plugin: &mut impl Plugin, encoder: impl PluginEncoder) {
}
})
.and_then(|_| {
let flags = get_flags_section(&signature.sig, |v| format!("{:#?}", v));
let flags = get_flags_section(None, &signature.sig, |v| format!("{:#?}", v));
write!(help, "{flags}")
})
.and_then(|_| writeln!(help, "\nParameters:"))

View File

@ -71,6 +71,8 @@ pub fn get_brief_subcommand_help(sigs: &[PluginSignature]) -> String {
let _ = writeln!(help, " {} - {}", x.1.sig.name, x.1.sig.usage);
}
help.push_str(&get_flags_section(&sigs[0].sig, |v| format!("{:#?}", v)));
help.push_str(&get_flags_section(None, &sigs[0].sig, |v| {
format!("{:#?}", v)
}));
help
}