Skip to main content

nu_command/help/
help_commands.rs

1use crate::filters::find_internal;
2use nu_engine::{command_prelude::*, get_full_help};
3use nu_protocol::DeclId;
4
5#[derive(Clone)]
6pub struct HelpCommands;
7
8impl Command for HelpCommands {
9    fn name(&self) -> &str {
10        "help commands"
11    }
12
13    fn description(&self) -> &str {
14        "Show help on nushell commands."
15    }
16
17    fn signature(&self) -> Signature {
18        Signature::build("help commands")
19            .category(Category::Core)
20            .rest(
21                "rest",
22                SyntaxShape::String,
23                "The name of command to get help on.",
24            )
25            .named(
26                "find",
27                SyntaxShape::String,
28                "String to find in command names, descriptions, and search terms.",
29                Some('f'),
30            )
31            .input_output_types(vec![(Type::Nothing, Type::table())])
32            .allow_variants_without_examples(true)
33    }
34
35    fn run(
36        &self,
37        engine_state: &EngineState,
38        stack: &mut Stack,
39        call: &Call,
40        _input: PipelineData,
41    ) -> Result<PipelineData, ShellError> {
42        help_commands(engine_state, stack, call)
43    }
44}
45
46pub fn help_commands(
47    engine_state: &EngineState,
48    stack: &mut Stack,
49    call: &Call,
50) -> Result<PipelineData, ShellError> {
51    let head = call.head;
52    let find: Option<Spanned<String>> = call.get_flag(engine_state, stack, "find")?;
53    let rest: Vec<Spanned<String>> = call.rest(engine_state, stack, 0)?;
54
55    if let Some(f) = find {
56        let all_cmds_vec = build_help_commands(engine_state, head);
57        return find_internal(
58            all_cmds_vec,
59            engine_state,
60            stack,
61            &f.item,
62            &["name", "description", "search_terms"],
63            true,
64        );
65    }
66
67    if rest.is_empty() {
68        Ok(build_help_commands(engine_state, head))
69    } else {
70        let mut name = String::new();
71
72        for r in &rest {
73            if !name.is_empty() {
74                name.push(' ');
75            }
76            name.push_str(&r.item);
77        }
78
79        // Try to find the command, resolving aliases if necessary
80        let decl_id = find_decl_with_alias_resolution(engine_state, name.as_bytes());
81
82        if let Some(decl) = decl_id {
83            let cmd = engine_state.get_decl(decl);
84
85            // Get the canonical signature for this declaration so we can detect when the
86            // user asked for a module-qualified name (e.g. `clip prefix`) and adjust the
87            // Usage line in the generated help text accordingly.
88            let sig = engine_state.get_signature(cmd).update_from_command(cmd);
89
90            let mut help_text = get_full_help(cmd, engine_state, stack);
91
92            // If the requested name differs from the signature's base name (module-qualified
93            // request), replace the first occurrence of the usage call name so help shows
94            // the qualified form the user asked for.
95            if name != sig.name {
96                let search = format!("> {}", sig.name);
97                let replace = format!("> {}", name);
98                help_text = help_text.replacen(&search, &replace, 1);
99            }
100
101            Ok(Value::string(help_text, call.head).into_pipeline_data())
102        } else {
103            Err(ShellError::CommandNotFound {
104                span: Span::merge_many(rest.iter().map(|s| s.span)),
105            })
106        }
107    }
108}
109
110fn find_decl_with_alias_resolution(engine_state: &EngineState, name: &[u8]) -> Option<DeclId> {
111    let name_str = String::from_utf8_lossy(name);
112    let parts: Vec<&str> = name_str.split_whitespace().collect();
113
114    if parts.is_empty() {
115        return None;
116    }
117
118    if let Some(decl_id) = engine_state.find_decl(name, &[]) {
119        return Some(decl_id);
120    }
121
122    if let Some(first_decl_id) = engine_state.find_decl(parts[0].as_bytes(), &[]) {
123        let first_decl = engine_state.get_decl(first_decl_id);
124
125        // If it's an alias, try to resolve with remaining parts
126        if let Some(alias) = first_decl.as_alias()
127            && let nu_protocol::ast::Expression {
128                expr: nu_protocol::ast::Expr::Call(call),
129                ..
130            } = &alias.wrapped_call
131        {
132            let aliased_decl = engine_state.get_decl(call.decl_id);
133            let aliased_name = aliased_decl.name();
134
135            // If we have more parts, try to find "aliased_name + remaining parts"
136            if parts.len() > 1 {
137                let full_name = format!("{} {}", aliased_name, parts[1..].join(" "));
138                return find_decl_with_alias_resolution(engine_state, full_name.as_bytes());
139            } else {
140                // Just the alias, return the aliased command
141                return Some(call.decl_id);
142            }
143        }
144    }
145
146    None
147}
148
149fn build_help_commands(engine_state: &EngineState, span: Span) -> PipelineData {
150    let commands = engine_state.get_decls_sorted(false);
151    let mut found_cmds_vec = Vec::new();
152
153    for (decl_name_bytes, decl_id) in commands {
154        let decl = engine_state.get_decl(decl_id);
155        let sig = decl.signature().update_from_command(decl);
156
157        // Use the overlay-visible name (decl_name_bytes) as the help `name` so module-qualified
158        // names (e.g. "clip prefix") are shown instead of the bare signature name.
159        let key = String::from_utf8_lossy(&decl_name_bytes).to_string();
160        let description = sig.description;
161        let search_terms = sig.search_terms;
162
163        let command_type = decl.command_type().to_string();
164
165        // Build table of parameters
166        let param_table = {
167            let mut vals = vec![];
168
169            for required_param in &sig.required_positional {
170                vals.push(Value::record(
171                    record! {
172                        "name" => Value::string(&required_param.name, span),
173                        "type" => Value::string(required_param.shape.to_string(), span),
174                        "required" => Value::bool(true, span),
175                        "description" => Value::string(&required_param.desc, span),
176                    },
177                    span,
178                ));
179            }
180
181            for optional_param in &sig.optional_positional {
182                vals.push(Value::record(
183                    record! {
184                        "name" => Value::string(&optional_param.name, span),
185                        "type" => Value::string(optional_param.shape.to_string(), span),
186                        "required" => Value::bool(false, span),
187                        "description" => Value::string(&optional_param.desc, span),
188                    },
189                    span,
190                ));
191            }
192
193            if let Some(rest_positional) = &sig.rest_positional {
194                vals.push(Value::record(
195                    record! {
196                        "name" => Value::string(format!("...{}", rest_positional.name), span),
197                        "type" => Value::string(rest_positional.shape.to_string(), span),
198                        "required" => Value::bool(false, span),
199                        "description" => Value::string(&rest_positional.desc, span),
200                    },
201                    span,
202                ));
203            }
204
205            for named_param in &sig.named {
206                let name = if let Some(short) = named_param.short {
207                    if named_param.long.is_empty() {
208                        format!("-{short}")
209                    } else {
210                        format!("--{}(-{})", named_param.long, short)
211                    }
212                } else {
213                    format!("--{}", named_param.long)
214                };
215
216                let typ = if let Some(arg) = &named_param.arg {
217                    arg.to_string()
218                } else {
219                    "switch".to_string()
220                };
221
222                vals.push(Value::record(
223                    record! {
224                        "name" => Value::string(name, span),
225                        "type" => Value::string(typ, span),
226                        "required" => Value::bool(named_param.required, span),
227                        "description" => Value::string(&named_param.desc, span),
228                    },
229                    span,
230                ));
231            }
232
233            Value::list(vals, span)
234        };
235
236        // Build the signature input/output table
237        let input_output_table = {
238            let mut vals = vec![];
239
240            for (input_type, output_type) in sig.input_output_types {
241                vals.push(Value::record(
242                    record! {
243                        "input" => Value::string(input_type.to_string(), span),
244                        "output" => Value::string(output_type.to_string(), span),
245                    },
246                    span,
247                ));
248            }
249
250            Value::list(vals, span)
251        };
252
253        let record = record! {
254            "name" => Value::string(key, span),
255            "category" => Value::string(sig.category.to_string(), span),
256            "command_type" => Value::string(command_type, span),
257            "description" => Value::string(description, span),
258            "params" => param_table,
259            "input_output" => input_output_table,
260            "search_terms" => Value::string(search_terms.join(", "), span),
261            "is_const" => Value::bool(decl.is_const(), span),
262        };
263
264        found_cmds_vec.push(Value::record(record, span));
265    }
266
267    Value::list(found_cmds_vec, span).into_pipeline_data()
268}
269
270#[cfg(test)]
271mod test {
272    #[test]
273    fn test_examples() {
274        use super::HelpCommands;
275        use crate::test_examples;
276        test_examples(HelpCommands {})
277    }
278}