forked from reubeno/brush
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcomplete.rs
More file actions
647 lines (563 loc) · 22.2 KB
/
Copy pathcomplete.rs
File metadata and controls
647 lines (563 loc) · 22.2 KB
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
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
use clap::Parser;
use std::collections::HashMap;
use std::fmt::Write as _;
use std::io::Write;
use brush_core::completion::{self, CompleteAction, CompleteOption, Spec};
use brush_core::{ExecutionExitCode, ExecutionResult, builtins, error, escape};
#[derive(Parser)]
struct CommonCompleteCommandArgs {
/// Options governing the behavior of completions.
#[arg(short = 'o')]
options: Vec<CompleteOption>,
/// Actions to apply to generate completions.
#[arg(short = 'A')]
actions: Vec<CompleteAction>,
/// File glob pattern to be expanded to generate completions.
#[arg(short = 'G', allow_hyphen_values = true, value_name = "GLOB")]
glob_pattern: Option<String>,
/// List of words that will be considered as completions.
#[arg(short = 'W', allow_hyphen_values = true)]
word_list: Option<String>,
/// Name of a shell function to invoke to generate completions.
#[arg(short = 'F', allow_hyphen_values = true, value_name = "FUNC_NAME")]
function_name: Option<String>,
/// Command to execute to generate completions.
#[arg(short = 'C', allow_hyphen_values = true)]
command: Option<String>,
/// Pattern used as filter for completions.
#[arg(short = 'X', allow_hyphen_values = true, value_name = "PATTERN")]
filter_pattern: Option<String>,
/// Prefix pattern used as filter for completions.
#[arg(short = 'P', allow_hyphen_values = true)]
prefix: Option<String>,
/// Suffix pattern used as filter for completions.
#[arg(short = 'S', allow_hyphen_values = true)]
suffix: Option<String>,
/// Complete with valid aliases.
#[arg(short = 'a')]
action_alias: bool,
/// Complete with names of shell builtins.
#[arg(short = 'b')]
action_builtin: bool,
/// Complete with names of executable commands.
#[arg(short = 'c')]
action_command: bool,
/// Complete with directory names.
#[arg(short = 'd')]
action_directory: bool,
/// Complete with names of exported shell variables.
#[arg(short = 'e')]
action_exported: bool,
/// Complete with filenames.
#[arg(short = 'f')]
action_file: bool,
/// Complete with valid user groups.
#[arg(short = 'g')]
action_group: bool,
/// Complete with job specs.
#[arg(short = 'j')]
action_job: bool,
/// Complete with keywords.
#[arg(short = 'k')]
action_keyword: bool,
/// Complete with names of system services.
#[arg(short = 's')]
action_service: bool,
/// Complete with valid usernames.
#[arg(short = 'u')]
action_user: bool,
/// Complete with names of shell variables.
#[arg(short = 'v')]
action_variable: bool,
}
impl CommonCompleteCommandArgs {
fn create_spec(&self, extglob_enabled: bool) -> completion::Spec {
let filter_pattern_excludes;
let filter_pattern = if let Some(filter_pattern) = self.filter_pattern.as_ref() {
// If the pattern starts with a '!' that's not the start of an extglob pattern,
// then we invert.
if let Some(remaining_pattern) = filter_pattern.strip_prefix('!') {
if !extglob_enabled || !remaining_pattern.starts_with('(') {
filter_pattern_excludes = false;
Some(remaining_pattern.to_owned())
} else {
filter_pattern_excludes = true;
Some(filter_pattern.to_owned())
}
} else {
filter_pattern_excludes = true;
Some(filter_pattern.clone())
}
} else {
filter_pattern_excludes = false;
None
};
let mut spec = completion::Spec {
options: completion::GenerationOptions::default(),
actions: self.resolve_actions(),
glob_pattern: self.glob_pattern.clone(),
word_list: self.word_list.clone(),
function_name: self.function_name.clone(),
command: self.command.clone(),
filter_pattern,
filter_pattern_excludes,
prefix: self.prefix.clone(),
suffix: self.suffix.clone(),
};
for option in &self.options {
match option {
CompleteOption::BashDefault => spec.options.bash_default = true,
CompleteOption::Default => spec.options.default = true,
CompleteOption::DirNames => spec.options.dir_names = true,
CompleteOption::FileNames => spec.options.file_names = true,
CompleteOption::NoQuote => spec.options.no_quote = true,
CompleteOption::NoSort => spec.options.no_sort = true,
CompleteOption::NoSpace => spec.options.no_space = true,
CompleteOption::PlusDirs => spec.options.plus_dirs = true,
}
}
spec
}
fn resolve_actions(&self) -> Vec<CompleteAction> {
let mut actions = self.actions.clone();
actions.extend(
[
(self.action_alias, CompleteAction::Alias),
(self.action_builtin, CompleteAction::Builtin),
(self.action_command, CompleteAction::Command),
(self.action_directory, CompleteAction::Directory),
(self.action_exported, CompleteAction::Export),
(self.action_file, CompleteAction::File),
(self.action_group, CompleteAction::Group),
(self.action_job, CompleteAction::Job),
(self.action_keyword, CompleteAction::Keyword),
(self.action_service, CompleteAction::Service),
(self.action_user, CompleteAction::User),
(self.action_variable, CompleteAction::Variable),
]
.into_iter()
.filter_map(|(enabled, action)| enabled.then_some(action)),
);
actions
}
}
/// Configure programmable command completion.
#[derive(Parser)]
pub(crate) struct CompleteCommand {
/// Display registered completion settings.
#[arg(short = 'p')]
print: bool,
/// Remove the completion settings associated with the given command.
#[arg(short = 'r')]
remove: bool,
/// Apply these settings to the default completion scenario.
#[arg(short = 'D')]
use_as_default: bool,
/// Apply these settings to completion of empty lines.
#[arg(short = 'E')]
use_for_empty_line: bool,
/// Apply these settings to completion of the initial word of the input line.
#[arg(short = 'I')]
use_for_initial_word: bool,
#[clap(flatten)]
common_args: CommonCompleteCommandArgs,
names: Vec<String>,
}
impl builtins::Command for CompleteCommand {
type Error = brush_core::Error;
async fn execute<SE: brush_core::ShellExtensions>(
&self,
mut context: brush_core::ExecutionContext<'_, SE>,
) -> Result<brush_core::ExecutionResult, Self::Error> {
let mut result = ExecutionResult::success();
// If -D, -E, or -I are specified, then any names provided are ignored.
if self.use_as_default
|| self.use_for_empty_line
|| self.use_for_initial_word
|| self.names.is_empty()
{
self.process_global(&mut context)?;
} else {
for name in &self.names {
if !self.try_process_for_command(&mut context, name.as_str())? {
result = ExecutionResult::general_error();
}
}
}
Ok(result)
}
}
impl CompleteCommand {
fn process_global(
&self,
context: &mut brush_core::ExecutionContext<'_, impl brush_core::ShellExtensions>,
) -> Result<(), brush_core::Error> {
// Read options before taking mutable borrow on completion_config
let extended_globbing = context.shell.options().extended_globbing;
// These are processed in an intentional order.
let special_option_name;
let target_spec = if self.use_as_default {
special_option_name = "-D";
Some(&mut context.shell.completion_config_mut().default)
} else if self.use_for_empty_line {
special_option_name = "-E";
Some(&mut context.shell.completion_config_mut().empty_line)
} else if self.use_for_initial_word {
special_option_name = "-I";
Some(&mut context.shell.completion_config_mut().initial_word)
} else {
special_option_name = "";
None
};
// Treat 'complete' with no options the same as 'complete -p'.
if self.print || (!self.remove && target_spec.is_none()) {
if let Some(target_spec) = target_spec {
if let Some(existing_spec) = target_spec {
let existing_spec = existing_spec.clone();
Self::display_spec(context, Some(special_option_name), None, &existing_spec)?;
} else {
return error::unimp("special spec not found");
}
} else {
for (command_name, spec) in context.shell.completion_config().iter() {
Self::display_spec(context, None, Some(command_name.as_str()), spec)?;
}
}
} else if self.remove {
if let Some(target_spec) = target_spec {
let mut new_spec = None;
std::mem::swap(&mut new_spec, target_spec);
} else {
context.shell.completion_config_mut().clear();
}
} else {
if let Some(target_spec) = target_spec {
let mut new_spec = Some(self.common_args.create_spec(extended_globbing));
std::mem::swap(&mut new_spec, target_spec);
} else {
return error::unimp("set unspecified spec");
}
}
Ok(())
}
fn try_display_spec_for_command(
context: &brush_core::ExecutionContext<'_, impl brush_core::ShellExtensions>,
name: &str,
) -> Result<bool, brush_core::Error> {
if let Some(spec) = context.shell.completion_config().get(name) {
Self::display_spec(context, None, Some(name), spec)?;
Ok(true)
} else {
writeln!(context.stderr(), "no completion found for command")?;
Ok(false)
}
}
#[expect(clippy::too_many_lines)]
fn display_spec(
context: &brush_core::ExecutionContext<'_, impl brush_core::ShellExtensions>,
special_name: Option<&str>,
command_name: Option<&str>,
spec: &Spec,
) -> Result<(), brush_core::Error> {
let mut s = String::from("complete");
if let Some(special_name) = special_name {
s.push(' ');
s.push_str(special_name);
}
for action in &spec.actions {
s.push(' ');
let action_str = match action {
CompleteAction::Alias => "-a",
CompleteAction::ArrayVar => "-A arrayvar",
CompleteAction::Binding => "-A binding",
CompleteAction::Builtin => "-b",
CompleteAction::Command => "-c",
CompleteAction::Directory => "-d",
CompleteAction::Disabled => "-A disabled",
CompleteAction::Enabled => "-A enabled",
CompleteAction::Export => "-e",
CompleteAction::File => "-f",
CompleteAction::Function => "-A function",
CompleteAction::Group => "-g",
CompleteAction::HelpTopic => "-A helptopic",
CompleteAction::HostName => "-A hostname",
CompleteAction::Job => "-j",
CompleteAction::Keyword => "-k",
CompleteAction::Running => "-A running",
CompleteAction::Service => "-s",
CompleteAction::SetOpt => "-A setopt",
CompleteAction::ShOpt => "-A shopt",
CompleteAction::Signal => "-A signal",
CompleteAction::Stopped => "-A stopped",
CompleteAction::User => "-u",
CompleteAction::Variable => "-v",
};
s.push_str(action_str);
}
if spec.options.bash_default {
s.push_str(" -o bashdefault");
}
if spec.options.default {
s.push_str(" -o default");
}
if spec.options.dir_names {
s.push_str(" -o dirnames");
}
if spec.options.file_names {
s.push_str(" -o filenames");
}
if spec.options.no_quote {
s.push_str(" -o noquote");
}
if spec.options.no_sort {
s.push_str(" -o nosort");
}
if spec.options.no_space {
s.push_str(" -o nospace");
}
if spec.options.plus_dirs {
s.push_str(" -o plusdirs");
}
if let Some(glob_pattern) = &spec.glob_pattern {
write!(
s,
" -G {}",
escape::force_quote(glob_pattern, escape::QuoteMode::SingleQuote)
)?;
}
if let Some(word_list) = &spec.word_list {
write!(
s,
" -W {}",
escape::force_quote(word_list, escape::QuoteMode::SingleQuote)
)?;
}
if let Some(function_name) = &spec.function_name {
write!(s, " -F {function_name}")?;
}
if let Some(command) = &spec.command {
write!(
s,
" -C {}",
escape::force_quote(command, escape::QuoteMode::SingleQuote)
)?;
}
if let Some(filter_pattern) = &spec.filter_pattern {
write!(
s,
" -X {}",
escape::force_quote(filter_pattern, escape::QuoteMode::SingleQuote)
)?;
}
if let Some(prefix) = &spec.prefix {
write!(
s,
" -P {}",
escape::force_quote(prefix, escape::QuoteMode::SingleQuote)
)?;
}
if let Some(suffix) = &spec.suffix {
write!(
s,
" -S {}",
escape::force_quote(suffix, escape::QuoteMode::SingleQuote)
)?;
}
if let Some(command_name) = command_name {
s.push(' ');
s.push_str(command_name);
}
writeln!(context.stdout(), "{s}")?;
Ok(())
}
fn try_process_for_command(
&self,
context: &mut brush_core::ExecutionContext<'_, impl brush_core::ShellExtensions>,
name: &str,
) -> Result<bool, brush_core::Error> {
if self.print {
return Self::try_display_spec_for_command(context, name);
} else if self.remove {
let mut result = context.shell.completion_config_mut().remove(name);
if !result {
if context.shell.options().interactive {
writeln!(context.stderr(), "complete: {name}: not found")?;
} else {
// For some reason, this is not supposed to be treated as a failure
// in non-interactive execution.
result = true;
}
}
return Ok(result);
}
let config = self
.common_args
.create_spec(context.shell.options().extended_globbing);
context.shell.completion_config_mut().set(name, config);
Ok(true)
}
}
/// Generate command completions.
#[derive(Parser)]
pub(crate) struct CompGenCommand {
#[clap(flatten)]
common_args: CommonCompleteCommandArgs,
// N.B. The word can only start with a hyphen if it's after a --.
word: Option<String>,
}
impl builtins::Command for CompGenCommand {
type Error = brush_core::Error;
async fn execute<SE: brush_core::ShellExtensions>(
&self,
context: brush_core::ExecutionContext<'_, SE>,
) -> Result<brush_core::ExecutionResult, Self::Error> {
let mut spec = self
.common_args
.create_spec(context.shell.options().extended_globbing);
spec.options.no_sort = true;
let token_to_complete = self.word.as_deref().unwrap_or_default();
// We unquote the token-to-be-completed before passing it to the completion system.
let unquoted_token = brush_parser::unquote_str(token_to_complete);
let completion_context = completion::Context {
token_to_complete: unquoted_token.as_str(),
preceding_token: None,
command_name: None,
token_index: 0,
tokens: &[&completion::CompletionToken {
text: token_to_complete,
start: 0,
}],
input_line: token_to_complete,
cursor_index: token_to_complete.len(),
trigger: completion::CompletionTrigger::Programmatic,
};
let result = spec
.get_completions(context.shell, &completion_context)
.await?;
match result {
completion::Answer::Candidates(candidates, _options) => {
// We are expected to return 1 if there are no candidates, even if no errors
// occurred along the way.
if candidates.is_empty() {
return Ok(ExecutionResult::general_error());
}
for candidate in candidates {
writeln!(context.stdout(), "{candidate}")?;
}
}
completion::Answer::RestartCompletionProcess => {
return error::unimp("restart completion");
}
}
Ok(ExecutionResult::success())
}
}
/// Set programmable command completion options.
#[derive(Parser)]
pub(crate) struct CompOptCommand {
/// Update the default completion settings.
#[arg(short = 'D')]
update_default: bool,
/// Update the completion settings for empty lines.
#[arg(short = 'E')]
update_empty: bool,
/// Update the completion settings for the initial word of the input line.
#[arg(short = 'I')]
update_initial_word: bool,
/// Enable the specified option for selected completion scenarios.
#[arg(short = 'o', value_name = "OPT")]
enabled_options: Vec<CompleteOption>,
#[arg(long = concat!("+o"), hide = true)]
disabled_options: Vec<CompleteOption>,
/// If specified, scopes updates to completions of the named commands.
names: Vec<String>,
}
impl builtins::Command for CompOptCommand {
type Error = brush_core::Error;
async fn execute<SE: brush_core::ShellExtensions>(
&self,
context: brush_core::ExecutionContext<'_, SE>,
) -> Result<brush_core::ExecutionResult, Self::Error> {
let mut options =
HashMap::with_capacity(self.disabled_options.len() + self.enabled_options.len());
for option in &self.disabled_options {
options.insert(option.clone(), false);
}
for option in &self.enabled_options {
options.insert(option.clone(), true);
}
if !self.names.is_empty() {
if self.update_default || self.update_empty || self.update_initial_word {
writeln!(
context.stderr(),
"compopt: cannot specify names with -D, -E, or -I"
)?;
return Ok(ExecutionExitCode::InvalidUsage.into());
}
for name in &self.names {
let spec = context.shell.completion_config_mut().get_or_add_mut(name);
Self::set_options_for_spec(spec, &options);
}
} else if self.update_default {
if let Some(spec) = &mut context.shell.completion_config_mut().default {
Self::set_options_for_spec(spec, &options);
} else {
let mut spec = Spec::default();
Self::set_options_for_spec(&mut spec, &options);
context.shell.completion_config_mut().default = Some(spec);
}
} else if self.update_empty {
if let Some(spec) = &mut context.shell.completion_config_mut().empty_line {
Self::set_options_for_spec(spec, &options);
} else {
let mut spec = Spec::default();
Self::set_options_for_spec(&mut spec, &options);
context.shell.completion_config_mut().empty_line = Some(spec);
}
} else if self.update_initial_word {
if let Some(spec) = &mut context.shell.completion_config_mut().initial_word {
Self::set_options_for_spec(spec, &options);
} else {
let mut spec = Spec::default();
Self::set_options_for_spec(&mut spec, &options);
context.shell.completion_config_mut().initial_word = Some(spec);
}
} else {
// If we got here, then we need to apply to any completion actively in-flight.
if let Some(in_flight_options) = context
.shell
.completion_config_mut()
.current_completion_options
.as_mut()
{
Self::set_options(in_flight_options, &options);
}
}
Ok(ExecutionResult::success())
}
}
impl CompOptCommand {
fn set_options_for_spec<'a, I>(spec: &mut Spec, options: I)
where
I: IntoIterator<Item = (&'a CompleteOption, &'a bool)>,
{
Self::set_options(&mut spec.options, options);
}
fn set_options<'a, I>(target_options: &mut completion::GenerationOptions, options: I)
where
I: IntoIterator<Item = (&'a CompleteOption, &'a bool)>,
{
for (option, value) in options {
match option {
CompleteOption::BashDefault => target_options.bash_default = *value,
CompleteOption::Default => target_options.default = *value,
CompleteOption::DirNames => target_options.dir_names = *value,
CompleteOption::FileNames => target_options.file_names = *value,
CompleteOption::NoQuote => target_options.no_quote = *value,
CompleteOption::NoSort => target_options.no_sort = *value,
CompleteOption::NoSpace => target_options.no_space = *value,
CompleteOption::PlusDirs => target_options.plus_dirs = *value,
}
}
}
}