forked from nushell/nushell
-
Notifications
You must be signed in to change notification settings - Fork 0
/
help_.rs
256 lines (229 loc) · 8.09 KB
/
help_.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
use crate::help::{help_aliases, help_commands, help_modules};
use fancy_regex::Regex;
use nu_ansi_term::Style;
use nu_engine::command_prelude::*;
use nu_protocol::span;
use nu_utils::IgnoreCaseExt;
#[derive(Clone)]
pub struct Help;
impl Command for Help {
fn name(&self) -> &str {
"help"
}
fn signature(&self) -> Signature {
Signature::build("help")
.input_output_types(vec![(Type::Nothing, Type::Any)])
.rest(
"rest",
SyntaxShape::String,
"The name of command, alias or module to get help on.",
)
.named(
"find",
SyntaxShape::String,
"string to find in command names, usage, and search terms",
Some('f'),
)
.category(Category::Core)
}
fn usage(&self) -> &str {
"Display help information about different parts of Nushell."
}
fn extra_usage(&self) -> &str {
r#"`help word` searches for "word" in commands, aliases and modules, in that order."#
}
fn run(
&self,
engine_state: &EngineState,
stack: &mut Stack,
call: &Call,
_input: PipelineData,
) -> Result<PipelineData, ShellError> {
let head = call.head;
let find: Option<Spanned<String>> = call.get_flag(engine_state, stack, "find")?;
let rest: Vec<Spanned<String>> = call.rest(engine_state, stack, 0)?;
if rest.is_empty() && find.is_none() {
let msg = r#"Welcome to Nushell.
Here are some tips to help you get started.
* help -h or help help - show available `help` subcommands and examples
* help commands - list all available commands
* help <name> - display help about a particular command, alias, or module
* help --find <text to search> - search through all help commands table
Nushell works on the idea of a "pipeline". Pipelines are commands connected with the '|' character.
Each stage in the pipeline works together to load, parse, and display information to you.
[Examples]
List the files in the current directory, sorted by size:
ls | sort-by size
Get information about the current system:
sys | get host
Get the processes on your system actively using CPU:
ps | where cpu > 0
You can also learn more at https://www.nushell.sh/book/"#;
Ok(Value::string(msg, head).into_pipeline_data())
} else if find.is_some() {
help_commands(engine_state, stack, call)
} else {
let result = help_aliases(engine_state, stack, call);
let result = if let Err(ShellError::AliasNotFound { .. }) = result {
help_commands(engine_state, stack, call)
} else {
result
};
let result = if let Err(ShellError::CommandNotFound { .. }) = result {
help_modules(engine_state, stack, call)
} else {
result
};
if let Err(ShellError::ModuleNotFoundAtRuntime {
mod_name: _,
span: _,
}) = result
{
let rest_spans: Vec<Span> = rest.iter().map(|arg| arg.span).collect();
Err(ShellError::NotFound {
span: span(&rest_spans),
})
} else {
result
}
}
}
fn examples(&self) -> Vec<Example> {
vec![
Example {
description: "show help for single command, alias, or module",
example: "help match",
result: None,
},
Example {
description: "show help for single sub-command, alias, or module",
example: "help str join",
result: None,
},
Example {
description: "search for string in command names, usage and search terms",
example: "help --find char",
result: None,
},
]
}
}
pub fn highlight_search_in_table(
table: Vec<Value>, // list of records
search_string: &str,
searched_cols: &[&str],
string_style: &Style,
highlight_style: &Style,
) -> Result<Vec<Value>, ShellError> {
let orig_search_string = search_string;
let search_string = search_string.to_folded_case();
let mut matches = vec![];
for record in table {
let span = record.span();
let (mut record, record_span) = if let Value::Record { val, .. } = record {
(val, span)
} else {
return Err(ShellError::NushellFailedSpanned {
msg: "Expected record".to_string(),
label: format!("got {}", record.get_type()),
span: record.span(),
});
};
let has_match = record.iter_mut().try_fold(
false,
|acc: bool, (col, val)| -> Result<bool, ShellError> {
if !searched_cols.contains(&col.as_str()) {
// don't search this column
return Ok(acc);
}
let span = val.span();
if let Value::String { val: s, .. } = val {
if s.to_folded_case().contains(&search_string) {
*val = Value::string(
highlight_search_string(
s,
orig_search_string,
string_style,
highlight_style,
)?,
span,
);
return Ok(true);
}
}
// column does not contain the searched string
// ignore non-string values
Ok(acc)
},
)?;
if has_match {
matches.push(Value::record(record, record_span));
}
}
Ok(matches)
}
// Highlight the search string using ANSI escape sequences and regular expressions.
pub fn highlight_search_string(
haystack: &str,
needle: &str,
string_style: &Style,
highlight_style: &Style,
) -> Result<String, ShellError> {
let regex_string = format!("(?i){needle}");
let regex = match Regex::new(®ex_string) {
Ok(regex) => regex,
Err(err) => {
return Err(ShellError::GenericError {
error: "Could not compile regex".into(),
msg: err.to_string(),
span: Some(Span::test_data()),
help: None,
inner: vec![],
});
}
};
// strip haystack to remove existing ansi style
let stripped_haystack = nu_utils::strip_ansi_likely(haystack);
let mut last_match_end = 0;
let mut highlighted = String::new();
for cap in regex.captures_iter(stripped_haystack.as_ref()) {
match cap {
Ok(capture) => {
let start = match capture.get(0) {
Some(acap) => acap.start(),
None => 0,
};
let end = match capture.get(0) {
Some(acap) => acap.end(),
None => 0,
};
highlighted.push_str(
&string_style
.paint(&stripped_haystack[last_match_end..start])
.to_string(),
);
highlighted.push_str(
&highlight_style
.paint(&stripped_haystack[start..end])
.to_string(),
);
last_match_end = end;
}
Err(e) => {
return Err(ShellError::GenericError {
error: "Error with regular expression capture".into(),
msg: e.to_string(),
span: None,
help: None,
inner: vec![],
});
}
}
}
highlighted.push_str(
&string_style
.paint(&stripped_haystack[last_match_end..])
.to_string(),
);
Ok(highlighted)
}