forked from reubeno/brush
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathshell.rs
1118 lines (983 loc) · 37.9 KB
/
shell.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
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
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use std::borrow::Cow;
use std::collections::{HashMap, VecDeque};
use std::fmt::Write as _;
use std::io::{Read, Write};
use std::path::{Path, PathBuf};
use std::sync::Arc;
use crate::arithmetic::Evaluatable;
use crate::env::{EnvironmentLookup, EnvironmentScope, ShellEnvironment};
use crate::interp::{self, Execute, ExecutionParameters, ExecutionResult};
use crate::options::RuntimeOptions;
use crate::sys::fs::PathExt;
use crate::trace_categories;
use crate::variables::{self, ShellValue, ShellVariable};
use crate::{
builtins, commands, completion, env, error, expansion, functions, jobs, keywords, openfiles,
patterns, prompt, sys::users, traps,
};
/// Represents an instance of a shell.
pub struct Shell {
//
// Core state required by specification
/// Trap handler configuration for the shell.
pub traps: traps::TrapHandlerConfig,
/// Manages files opened and accessible via redirection operators.
pub open_files: openfiles::OpenFiles,
/// The current working directory.
pub working_dir: PathBuf,
/// The shell environment, containing shell variables.
pub env: ShellEnvironment,
/// Shell function definitions.
pub funcs: functions::FunctionEnv,
/// Runtime shell options.
pub options: RuntimeOptions,
/// State of managed jobs.
pub jobs: jobs::JobManager,
/// Shell aliases.
pub aliases: HashMap<String, String>,
//
// Additional state
/// The status of the last completed command.
pub last_exit_status: u8,
/// Clone depth from the original ancestor shell.
pub depth: usize,
/// Positional parameters ($1 and beyond)
pub positional_parameters: Vec<String>,
/// Shell name
pub shell_name: Option<String>,
/// Detailed display string for the shell
pub shell_product_display_str: Option<String>,
/// Script call stack.
pub script_call_stack: VecDeque<String>,
/// Function call stack.
pub function_call_stack: VecDeque<FunctionCall>,
/// Directory stack used by pushd et al.
pub directory_stack: Vec<PathBuf>,
/// Current line number being processed.
pub current_line_number: u32,
/// Completion configuration.
pub completion_config: completion::Config,
/// Shell built-in commands.
pub builtins: HashMap<String, builtins::Registration>,
}
impl Clone for Shell {
fn clone(&self) -> Self {
Self {
traps: self.traps.clone(),
open_files: self.open_files.clone(),
working_dir: self.working_dir.clone(),
env: self.env.clone(),
funcs: self.funcs.clone(),
options: self.options.clone(),
jobs: jobs::JobManager::new(),
aliases: self.aliases.clone(),
last_exit_status: self.last_exit_status,
positional_parameters: self.positional_parameters.clone(),
shell_name: self.shell_name.clone(),
shell_product_display_str: self.shell_product_display_str.clone(),
function_call_stack: self.function_call_stack.clone(),
script_call_stack: self.script_call_stack.clone(),
directory_stack: self.directory_stack.clone(),
current_line_number: self.current_line_number,
completion_config: self.completion_config.clone(),
builtins: self.builtins.clone(),
depth: self.depth + 1,
}
}
}
impl AsRef<Shell> for Shell {
fn as_ref(&self) -> &Shell {
self
}
}
impl AsMut<Shell> for Shell {
fn as_mut(&mut self) -> &mut Shell {
self
}
}
/// Options for creating a new shell.
#[derive(Debug, Default)]
pub struct CreateOptions {
/// Disabled shopt options.
pub disabled_shopt_options: Vec<String>,
/// Enabled shopt options.
pub enabled_shopt_options: Vec<String>,
/// Do not execute commands.
pub do_not_execute_commands: bool,
/// Whether the shell is interactive.
pub interactive: bool,
/// Whether the shell is a login shell.
pub login: bool,
/// Whether to skip using a readline-like interface for input.
pub no_editing: bool,
/// Whether to skip sourcing the system profile.
pub no_profile: bool,
/// Whether to skip sourcing the user's rc file.
pub no_rc: bool,
/// Whether the shell is in POSIX compliance mode.
pub posix: bool,
/// Whether to print commands and arguments as they are read.
pub print_commands_and_arguments: bool,
/// Whether commands are being read from stdin.
pub read_commands_from_stdin: bool,
/// The name of the shell.
pub shell_name: Option<String>,
/// Optionally provides a display string describing the version and variant of the shell.
pub shell_product_display_str: Option<String>,
/// Whether to run in maximal POSIX sh compatibility mode.
pub sh_mode: bool,
/// Whether to print verbose output.
pub verbose: bool,
}
/// Represents an active shell function call.
#[derive(Clone, Debug)]
pub struct FunctionCall {
/// The name of the function invoked.
function_name: String,
/// The definition of the invoked function.
function_definition: Arc<brush_parser::ast::FunctionDefinition>,
}
lazy_static::lazy_static! {
// NOTE: We have difficulty with xterm escape sequences going through rustyline;
// so we compile a regex that can be used to strip them out.
static ref PROMPT_XTERM_ESCAPE_SEQ_REGEX: fancy_regex::Regex = fancy_regex::Regex::new("\x1b][0-2];[^\x07]*\x07").unwrap();
}
impl Shell {
/// Returns a new shell instance created with the given options.
///
/// # Arguments
///
/// * `options` - The options to use when creating the shell.
pub async fn new(options: &CreateOptions) -> Result<Shell, error::Error> {
// Instantiate the shell with some defaults.
let mut shell = Shell {
traps: traps::TrapHandlerConfig::default(),
open_files: openfiles::OpenFiles::default(),
working_dir: std::env::current_dir()?,
env: Self::initialize_vars(options)?,
funcs: functions::FunctionEnv::default(),
options: RuntimeOptions::defaults_from(options),
jobs: jobs::JobManager::new(),
aliases: HashMap::default(),
last_exit_status: 0,
positional_parameters: vec![],
shell_name: options.shell_name.clone(),
shell_product_display_str: options.shell_product_display_str.clone(),
function_call_stack: VecDeque::new(),
script_call_stack: VecDeque::new(),
directory_stack: vec![],
current_line_number: 0,
completion_config: completion::Config::default(),
builtins: builtins::get_default_builtins(options),
depth: 0,
};
// TODO: Without this a script that sets extglob will fail because we
// parse the entire script with the same settings.
shell.options.extended_globbing = true;
// Load profiles/configuration.
shell.load_config(options).await?;
Ok(shell)
}
fn initialize_vars(options: &CreateOptions) -> Result<ShellEnvironment, error::Error> {
let mut env = ShellEnvironment::new();
// Seed parameters from environment.
for (k, v) in std::env::vars() {
let mut var = ShellVariable::new(ShellValue::String(v));
var.export();
env.set_global(k, var)?;
}
// Set some additional ones.
#[cfg(unix)]
{
let mut euid_var = ShellVariable::new(ShellValue::String(format!(
"{}",
uzers::get_effective_uid()
)));
euid_var.set_readonly();
env.set_global("EUID", euid_var)?;
}
let mut random_var = ShellVariable::new(ShellValue::Random);
random_var.hide_from_enumeration();
random_var.treat_as_integer();
env.set_global("RANDOM", random_var)?;
env.set_global("IFS", ShellVariable::new(" \t\n".into()))?;
env.set_global(
"COMP_WORDBREAKS",
ShellVariable::new(" \t\n\"\'><=;|&(:".into()),
)?;
let os_type = match std::env::consts::OS {
"linux" => "linux-gnu",
"windows" => "windows",
_ => "unknown",
};
env.set_global("OSTYPE", ShellVariable::new(os_type.into()))?;
// Set some defaults (if they're not already initialized).
if !env.is_set("HISTFILE") {
if let Some(home_dir) = Self::get_home_dir_with_env(&env) {
let histfile = home_dir.join(".brush_history");
env.set_global(
"HISTFILE",
ShellVariable::new(ShellValue::String(histfile.to_string_lossy().to_string())),
)?;
}
}
#[cfg(unix)]
if !env.is_set("PATH") {
env.set_global(
"PATH",
ShellVariable::new(
"/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin".into(),
),
)?;
}
if !options.sh_mode {
if let Some(shell_name) = &options.shell_name {
env.set_global("BASH", ShellVariable::new(shell_name.into()))?;
}
env.set_global(
"BASH_VERSINFO",
ShellVariable::new(ShellValue::indexed_array_from_slice(
["5", "1", "1", "1", "release", "unknown"].as_slice(),
)),
)?;
}
Ok(env)
}
async fn load_config(&mut self, options: &CreateOptions) -> Result<(), error::Error> {
let mut params = self.default_exec_params();
params.process_group_policy = interp::ProcessGroupPolicy::SameProcessGroup;
if options.login {
// --noprofile means skip this.
if options.no_profile {
return Ok(());
}
//
// Source /etc/profile if it exists.
//
// Next source the first of these that exists and is readable (if any):
// * ~/.bash_profile
// * ~/.bash_login
// * ~/.profile
//
self.source_if_exists(Path::new("/etc/profile"), ¶ms)
.await?;
if let Some(home_path) = self.get_home_dir() {
if options.sh_mode {
self.source_if_exists(home_path.join(".profile").as_path(), ¶ms)
.await?;
} else {
if !self
.source_if_exists(home_path.join(".bash_profile").as_path(), ¶ms)
.await?
{
if !self
.source_if_exists(home_path.join(".bash_login").as_path(), ¶ms)
.await?
{
self.source_if_exists(home_path.join(".profile").as_path(), ¶ms)
.await?;
}
}
}
}
} else {
if options.interactive {
// --norc means skip this. Also skip in sh mode.
if options.no_rc || options.sh_mode {
return Ok(());
}
//
// For non-login interactive shells, load in this order:
//
// /etc/bash.bashrc
// ~/.bashrc
//
self.source_if_exists(Path::new("/etc/bash.bashrc"), ¶ms)
.await?;
if let Some(home_path) = self.get_home_dir() {
self.source_if_exists(home_path.join(".bashrc").as_path(), ¶ms)
.await?;
self.source_if_exists(home_path.join(".brushrc").as_path(), ¶ms)
.await?;
}
} else {
let env_var_name = if options.sh_mode { "ENV" } else { "BASH_ENV" };
if self.env.is_set(env_var_name) {
//
// TODO: look at $ENV/BASH_ENV; source its expansion if that file exists
//
return error::unimp(
"load config from $ENV/BASH_ENV for non-interactive, non-login shell",
);
}
}
}
Ok(())
}
async fn source_if_exists(
&mut self,
path: &Path,
params: &ExecutionParameters,
) -> Result<bool, error::Error> {
if path.exists() {
let args: Vec<String> = vec![];
self.source(path, &args, params).await?;
Ok(true)
} else {
tracing::debug!("skipping non-existent file: {}", path.display());
Ok(false)
}
}
/// Source the given file as a shell script, returning the execution result.
///
/// # Arguments
///
/// * `path` - The path to the file to source.
/// * `args` - The arguments to pass to the script as positional parameters.
/// * `params` - Execution parameters.
pub async fn source<S: AsRef<str>>(
&mut self,
path: &Path,
args: &[S],
params: &ExecutionParameters,
) -> Result<ExecutionResult, error::Error> {
tracing::debug!("sourcing: {}", path.display());
let opened_file: openfiles::OpenFile = self
.open_file(path, params)
.map_err(|e| error::Error::FailedSourcingFile(path.to_owned(), e.into()))?;
if opened_file.is_dir() {
return Err(error::Error::FailedSourcingFile(
path.to_owned(),
error::Error::IsADirectory.into(),
));
}
let source_info = brush_parser::SourceInfo {
source: path.to_string_lossy().to_string(),
};
self.source_file(opened_file, &source_info, args, params)
.await
}
/// Source the given file as a shell script, returning the execution result.
///
/// # Arguments
///
/// * `file` - The file to source.
/// * `source_info` - Information about the source of the script.
/// * `args` - The arguments to pass to the script as positional parameters.
/// * `params` - Execution parameters.
async fn source_file<F: Read, S: AsRef<str>>(
&mut self,
file: F,
source_info: &brush_parser::SourceInfo,
args: &[S],
params: &ExecutionParameters,
) -> Result<ExecutionResult, error::Error> {
let mut reader = std::io::BufReader::new(file);
let mut parser =
brush_parser::Parser::new(&mut reader, &self.parser_options(), source_info);
tracing::debug!(target: trace_categories::PARSE, "Parsing sourced file: {}", source_info.source);
let parse_result = parser.parse(false);
let mut other_positional_parameters = args.iter().map(|s| s.as_ref().to_owned()).collect();
let mut other_shell_name = Some(source_info.source.clone());
// TODO: Find a cleaner way to change args.
std::mem::swap(&mut self.shell_name, &mut other_shell_name);
std::mem::swap(
&mut self.positional_parameters,
&mut other_positional_parameters,
);
self.script_call_stack
.push_front(source_info.source.clone());
self.update_bash_source_var()?;
let result = self
.run_parsed_result(parse_result, source_info, params)
.await;
self.script_call_stack.pop_front();
self.update_bash_source_var()?;
// Restore.
std::mem::swap(&mut self.shell_name, &mut other_shell_name);
std::mem::swap(
&mut self.positional_parameters,
&mut other_positional_parameters,
);
result
}
/// Invokes a function defined in this shell, returning the resulting exit status.
///
/// # Arguments
///
/// * `name` - The name of the function to invoke.
/// * `args` - The arguments to pass to the function.
pub async fn invoke_function(&mut self, name: &str, args: &[&str]) -> Result<u8, error::Error> {
// TODO: Figure out if *all* callers have the same process group policy.
let params = self.default_exec_params();
let command_name = String::from(name);
let func_registration = self
.funcs
.get(name)
.ok_or_else(|| error::Error::FunctionNotFound(name.to_owned()))?;
let func = func_registration.definition.clone();
let context = commands::ExecutionContext {
shell: self,
command_name,
params,
};
let command_args = args
.iter()
.map(|s| commands::CommandArg::String(String::from(*s)))
.collect::<Vec<_>>();
match commands::invoke_shell_function(func, context, &command_args).await? {
commands::CommandSpawnResult::SpawnedProcess(_) => {
error::unimp("child spawned from function invocation")
}
commands::CommandSpawnResult::ImmediateExit(code) => Ok(code),
commands::CommandSpawnResult::ExitShell(code) => Ok(code),
commands::CommandSpawnResult::ReturnFromFunctionOrScript(code) => Ok(code),
commands::CommandSpawnResult::BreakLoop(_)
| commands::CommandSpawnResult::ContinueLoop(_) => {
error::unimp("break or continue returned from function invocation")
}
}
}
/// Executes the given string as a shell program, returning the resulting exit status.
///
/// # Arguments
///
/// * `command` - The command to execute.
/// * `params` - Execution parameters.
pub async fn run_string(
&mut self,
command: String,
params: &ExecutionParameters,
) -> Result<ExecutionResult, error::Error> {
// TODO: Actually track line numbers; this is something of a hack, assuming each time
// this function is invoked we are on the next line of the input. For one thing,
// each string we run could be multiple lines.
self.current_line_number += 1;
let parse_result = self.parse_string(command);
let source_info = brush_parser::SourceInfo {
source: String::from("main"),
};
self.run_parsed_result(parse_result, &source_info, params)
.await
}
/// Parses the given string as a shell program, returning the resulting Abstract Syntax Tree
/// for the program.
///
/// # Arguments
///
/// * `s` - The string to parse as a program.
pub fn parse_string(
&self,
s: String,
) -> Result<brush_parser::ast::Program, brush_parser::ParseError> {
parse_string_impl(s, self.parser_options())
}
/// Applies basic shell expansion to the provided string.
///
/// # Arguments
///
/// * `s` - The string to expand.
pub async fn basic_expand_string<S: AsRef<str>>(
&mut self,
s: S,
) -> Result<String, error::Error> {
let result = expansion::basic_expand_str(self, s.as_ref()).await?;
Ok(result)
}
/// Applies full shell expansion and field splitting to the provided string; returns
/// a sequence of fields.
///
/// # Arguments
///
/// * `s` - The string to expand and split.
pub async fn full_expand_and_split_string<S: AsRef<str>>(
&mut self,
s: S,
) -> Result<Vec<String>, error::Error> {
let result = expansion::full_expand_and_split_str(self, s.as_ref()).await?;
Ok(result)
}
/// Returns the default execution parameters for this shell.
pub fn default_exec_params(&self) -> ExecutionParameters {
ExecutionParameters {
open_files: self.open_files.clone(),
..Default::default()
}
}
/// Executes the given script file, returning the resulting exit status.
///
/// # Arguments
///
/// * `script_path` - The path to the script file to execute.
/// * `args` - The arguments to pass to the script as positional parameters.
pub async fn run_script<S: AsRef<str>>(
&mut self,
script_path: &Path,
args: &[S],
) -> Result<ExecutionResult, error::Error> {
self.source(script_path, args, &self.default_exec_params())
.await
}
async fn run_parsed_result(
&mut self,
parse_result: Result<brush_parser::ast::Program, brush_parser::ParseError>,
source_info: &brush_parser::SourceInfo,
params: &ExecutionParameters,
) -> Result<ExecutionResult, error::Error> {
let mut error_prefix = String::new();
if !source_info.source.is_empty() {
error_prefix = format!("{}: ", source_info.source);
}
let result = match parse_result {
Ok(prog) => match self.run_program(prog, params).await {
Ok(result) => result,
Err(e) => {
tracing::error!("error: {:#}", e);
self.last_exit_status = 1;
ExecutionResult::new(1)
}
},
Err(brush_parser::ParseError::ParsingNearToken(token_near_error)) => {
let error_loc = &token_near_error.location().start;
tracing::error!(
"{}syntax error near token `{}' (line {} col {})",
error_prefix,
token_near_error.to_str(),
error_loc.line,
error_loc.column,
);
self.last_exit_status = 2;
ExecutionResult::new(2)
}
Err(brush_parser::ParseError::ParsingAtEndOfInput) => {
tracing::error!("{}syntax error at end of input", error_prefix);
self.last_exit_status = 2;
ExecutionResult::new(2)
}
Err(brush_parser::ParseError::Tokenizing { inner, position }) => {
let mut error_message = error_prefix.clone();
error_message.push_str(inner.to_string().as_str());
if let Some(position) = position {
write!(
error_message,
" (detected near line {} column {})",
position.line, position.column
)?;
}
tracing::error!("{}", error_message);
self.last_exit_status = 2;
ExecutionResult::new(2)
}
};
Ok(result)
}
/// Executes the given parsed shell program, returning the resulting exit status.
///
/// # Arguments
///
/// * `program` - The program to execute.
/// * `params` - Execution parameters.
pub async fn run_program(
&mut self,
program: brush_parser::ast::Program,
params: &ExecutionParameters,
) -> Result<ExecutionResult, error::Error> {
program.execute(self, params).await
}
fn default_prompt(&self) -> &'static str {
if self.options.sh_mode {
"$ "
} else {
"brush$ "
}
}
/// Composes the shell's prompt, applying all appropriate expansions.
pub async fn compose_prompt(&mut self) -> Result<String, error::Error> {
// Retrieve the spec.
let ps1 = self.parameter_or_default("PS1", self.default_prompt());
// Expand it.
let formatted_prompt = prompt::expand_prompt(self, ps1.as_ref())?;
// NOTE: We're having difficulty with xterm escape sequences going through rustyline;
// so we strip them here.
let formatted_prompt = PROMPT_XTERM_ESCAPE_SEQ_REGEX
.replace_all(formatted_prompt.as_str(), "")
.to_string();
// Now expand.
let formatted_prompt = expansion::basic_expand_str(self, &formatted_prompt).await?;
Ok(formatted_prompt)
}
/// Compose's the shell's alternate-side prompt, applying all appropriate expansions.
#[allow(clippy::unused_async)]
pub async fn compose_alt_side_prompt(&mut self) -> Result<String, error::Error> {
Ok(String::new())
}
/// Retrieve's the shell's continuation prompt.
pub fn continuation_prompt(&self) -> Result<String, error::Error> {
// TODO: Evaluate expansion?
Ok(self.parameter_or_default("PS2", "> "))
}
/// Returns the exit status of the last command executed in this shell.
pub fn last_result(&self) -> u8 {
self.last_exit_status
}
fn parameter_or_default(&self, name: &str, default: &str) -> String {
self.env.get(name).map_or_else(
|| default.to_owned(),
|(_, s)| s.value().to_cow_string().to_string(),
)
}
/// Returns a string representing the current `set`-style option flags set in the shell.
pub(crate) fn current_option_flags(&self) -> String {
let mut cs = vec![];
for (x, y) in crate::namedoptions::SET_OPTIONS.iter() {
if (y.getter)(&self.options) {
cs.push(*x);
}
}
// Sort the flags in a way that matches what bash does.
cs.sort_by(|a, b| {
if a == b {
std::cmp::Ordering::Equal
} else if *a == 's' {
std::cmp::Ordering::Greater
} else if *b == 's' {
std::cmp::Ordering::Less
} else if a.is_ascii_lowercase() && b.is_ascii_uppercase() {
std::cmp::Ordering::Less
} else if a.is_ascii_uppercase() && b.is_ascii_lowercase() {
std::cmp::Ordering::Greater
} else {
a.cmp(b)
}
});
cs.into_iter().collect()
}
/// Returns the options that should be used for parsing shell programs; reflects
/// the current configuration state of the shell and may change over time.
pub fn parser_options(&self) -> brush_parser::ParserOptions {
brush_parser::ParserOptions {
enable_extended_globbing: self.options.extended_globbing,
posix_mode: self.options.posix_mode,
sh_mode: self.options.sh_mode,
tilde_expansion: true,
}
}
/// Returns whether or not the shell is actively executing in a shell function.
pub(crate) fn in_function(&self) -> bool {
!self.function_call_stack.is_empty()
}
/// Updates the shell's internal tracking state to reflect that a new shell
/// function is being entered.
///
/// # Arguments
///
/// * `name` - The name of the function being entered.
/// * `function_def` - The definition of the function being entered.
pub(crate) fn enter_function(
&mut self,
name: &str,
function_def: &Arc<brush_parser::ast::FunctionDefinition>,
) -> Result<(), error::Error> {
self.function_call_stack.push_front(FunctionCall {
function_name: name.to_owned(),
function_definition: function_def.clone(),
});
self.env.push_scope(env::EnvironmentScope::Local);
self.update_funcname_var()?;
Ok(())
}
/// Updates the shell's internal tracking state to reflect that the shell
/// has exited the top-most function on its call stack.
pub(crate) fn leave_function(&mut self) -> Result<(), error::Error> {
self.env.pop_scope(env::EnvironmentScope::Local)?;
self.function_call_stack.pop_front();
self.update_funcname_var()?;
Ok(())
}
fn update_funcname_var(&mut self) -> Result<(), error::Error> {
//
// Fill out FUNCNAME[*]
//
let funcname_values = self
.function_call_stack
.iter()
.map(|s| (None, s.function_name.clone()))
.collect::<Vec<_>>();
self.env.update_or_add(
"FUNCNAME",
variables::ShellValueLiteral::Array(variables::ArrayLiteral(funcname_values)),
|_| Ok(()),
EnvironmentLookup::Anywhere,
EnvironmentScope::Global,
)?;
self.update_bash_source_var()
}
fn update_bash_source_var(&mut self) -> Result<(), error::Error> {
//
// Fill out BASH_SOURCE[*]
//
let source_values = if self.function_call_stack.is_empty() {
self.script_call_stack
.front()
.map_or_else(Vec::new, |s| vec![(None, s.to_owned())])
} else {
self.function_call_stack
.iter()
.map(|s| (None, s.function_definition.source.clone()))
.collect::<Vec<_>>()
};
self.env.update_or_add(
"BASH_SOURCE",
variables::ShellValueLiteral::Array(variables::ArrayLiteral(source_values)),
|_| Ok(()),
EnvironmentLookup::Anywhere,
EnvironmentScope::Global,
)?;
Ok(())
}
/// Returns the path to the history file used by the shell, if one is set.
pub fn get_history_file_path(&self) -> Option<PathBuf> {
self.env.get("HISTFILE").map(|(_, var)| {
let histfile_str: String = var.value().to_cow_string().to_string();
PathBuf::from(histfile_str)
})
}
/// Returns the number of the line being executed in the currently executing program.
pub(crate) fn get_current_input_line_number(&self) -> u32 {
self.current_line_number
}
/// Returns the current value of the IFS variable, or the default value if it is not set.
pub(crate) fn get_ifs(&self) -> Cow<'_, str> {
self.env.get("IFS").map_or_else(
|| Cow::Borrowed(" \t\n"),
|(_, v)| v.value().to_cow_string(),
)
}
/// Generates command completions for the shell.
///
/// # Arguments
///
/// * `input` - The input string to generate completions for.
/// * `position` - The position in the input string to generate completions at.
pub async fn get_completions(
&mut self,
input: &str,
position: usize,
) -> Result<completion::Completions, error::Error> {
let completion_config = self.completion_config.clone();
completion_config
.get_completions(self, input, position)
.await
}
/// Finds executables in the shell's current default PATH, matching the given glob pattern.
///
/// # Arguments
///
/// * `required_glob_pattern` - The glob pattern to match against.
#[allow(clippy::manual_flatten)]
pub fn find_executables_in_path(&self, required_glob_pattern: &str) -> Vec<PathBuf> {
let is_executable = |path: &Path| path.executable();
let mut executables = vec![];
for dir_str in self.env.get_str("PATH").unwrap_or_default().split(':') {
let pattern = std::format!("{dir_str}/{required_glob_pattern}");
// TODO: Pass through quoting.
if let Ok(entries) = patterns::Pattern::from(pattern).expand(
&self.working_dir,
self.options.extended_globbing,
Some(&is_executable),
) {
for entry in entries {
executables.push(PathBuf::from(entry));
}
}
}
executables
}
/// Gets the absolute form of the given path.
///
/// # Arguments
///
/// * `path` - The path to get the absolute form of.
pub fn get_absolute_path(&self, path: &Path) -> PathBuf {
if path.is_absolute() {
path.to_owned()
} else {
self.working_dir.join(path)
}
}
/// Opens the given file.
///
/// # Arguments
///
/// * `path` - The path to the file to open; may be relative to the shell's working directory.
/// * `params` - Execution parameters.
pub(crate) fn open_file(
&self,
path: &Path,
params: &ExecutionParameters,
) -> Result<openfiles::OpenFile, error::Error> {
let path_to_open = self.get_absolute_path(path);
// See if this is a reference to a file descriptor, in which case the actual
// /dev/fd* file path for this process may not match with what's in the execution
// parameters.
if let Some(parent) = path_to_open.parent() {
if parent == Path::new("/dev/fd") {
if let Some(filename) = path_to_open.file_name() {
if let Ok(fd_num) = filename.to_string_lossy().to_string().parse::<u32>() {
if let Some(open_file) = params.open_files.files.get(&fd_num) {
return open_file.try_dup();
}
}
}
}
}
Ok(std::fs::File::open(path_to_open)?.into())
}
/// Sets the shell's current working directory to the given path.
///
/// # Arguments
///
/// * `target_dir` - The path to set as the working directory.
pub fn set_working_dir(&mut self, target_dir: &Path) -> Result<(), error::Error> {
let abs_path = self.get_absolute_path(target_dir);
match std::fs::metadata(&abs_path) {
Ok(m) => {
if !m.is_dir() {
return Err(error::Error::NotADirectory(abs_path));
}
}
Err(e) => {
return Err(e.into());
}
}
// TODO: Don't canonicalize, just normalize.
let cleaned_path = abs_path.canonicalize()?;
let pwd = cleaned_path.to_string_lossy().to_string();
self.env.update_or_add(
"PWD",
variables::ShellValueLiteral::Scalar(pwd),
|var| {
var.export();
Ok(())
},
EnvironmentLookup::Anywhere,
EnvironmentScope::Global,
)?;
let oldpwd = std::mem::replace(&mut self.working_dir, cleaned_path);
self.env.update_or_add(
"OLDPWD",
variables::ShellValueLiteral::Scalar(oldpwd.to_string_lossy().to_string()),
|var| {
var.export();
Ok(())
},
EnvironmentLookup::Anywhere,
EnvironmentScope::Global,
)?;
Ok(())
}
/// Tilde-shortens the given string, replacing the user's home directory with a tilde.
///
/// # Arguments