-
Notifications
You must be signed in to change notification settings - Fork 24
Expand file tree
/
Copy pathexecute.rs
More file actions
1201 lines (1137 loc) · 34.6 KB
/
execute.rs
File metadata and controls
1201 lines (1137 loc) · 34.6 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
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
// Copyright 2018-2025 the Deno authors. MIT license.
use std::collections::HashMap;
use std::ffi::OsStr;
use std::ffi::OsString;
use std::path::Path;
use std::path::PathBuf;
use std::rc::Rc;
use std::string::FromUtf8Error;
use futures::FutureExt;
use futures::future;
use futures::future::LocalBoxFuture;
use thiserror::Error;
use tokio::task::JoinHandle;
use crate::parser::Command;
use crate::parser::CommandInner;
use crate::parser::IoFile;
use crate::parser::PipeSequence;
use crate::parser::PipeSequenceOperator;
use crate::parser::Pipeline;
use crate::parser::PipelineInner;
use crate::parser::Redirect;
use crate::parser::RedirectFd;
use crate::parser::RedirectOp;
use crate::parser::RedirectOpInput;
use crate::parser::RedirectOpOutput;
use crate::parser::Sequence;
use crate::parser::SequentialList;
use crate::parser::SimpleCommand;
use crate::parser::Word;
use crate::parser::WordPart;
use crate::shell::commands::ShellCommand;
use crate::shell::commands::ShellCommandContext;
use crate::shell::types::EnvChange;
use crate::shell::types::ExecuteResult;
use crate::shell::types::FutureExecuteResult;
use crate::shell::types::KillSignal;
use crate::shell::types::ProcessSignaler;
use crate::shell::types::ShellPipeReader;
use crate::shell::types::ShellPipeWriter;
use crate::shell::types::ShellState;
use crate::shell::types::SignalKind;
use crate::shell::types::pipe;
use super::command::UnresolvedCommandName;
use super::command::execute_unresolved_command_name;
use super::types::TreeExitCodeCell;
/// Executes a `SequentialList` of commands in a deno_task_shell environment.
///
/// This function accepts a list of commands, a map of environment variables, the current working directory,
/// and a map of custom shell commands. It sets up the shell state and then calls `execute_with_pipes`
/// with the standard input, output, and error streams.
///
/// # Arguments
/// * `list` - A `SequentialList` of commands to execute.
/// * `env_vars` - A map of environment variables which are set in the shell.
/// * `cwd` - The current working directory.
/// * `custom_commands` - A map of custom shell commands and there ShellCommand implementation.
/// * `kill_signal` - Use to send signals to spawned executables.
///
/// # Returns
/// The exit code of the command execution.
pub async fn execute(
list: SequentialList,
env_vars: HashMap<OsString, OsString>,
cwd: PathBuf,
custom_commands: HashMap<String, Rc<dyn ShellCommand>>,
kill_signal: KillSignal,
) -> i32 {
let state = ShellState::new(env_vars, cwd, custom_commands, kill_signal);
execute_with_pipes(
list,
state,
ShellPipeReader::stdin(),
ShellPipeWriter::stdout(),
ShellPipeWriter::stderr(),
)
.await
}
/// Executes a command list and returns the ProcessSignaler for monitoring child processes.
///
/// This is useful when you need to track spawned child PIDs for signal forwarding.
/// The returned `ProcessSignaler` can be used to:
/// - Get the current foreground process PID via `current_pid()`
/// - Subscribe to process spawn notifications via `subscribe()`
///
/// # Example
///
/// ```ignore
/// use deno_task_shell::{execute_with_signaler, KillSignal, SignalKind};
///
/// let kill_signal = KillSignal::default();
/// let (signaler, execute_future) = execute_with_signaler(
/// list,
/// env_vars,
/// cwd,
/// custom_commands,
/// kill_signal.clone(),
/// );
///
/// // Check the current child process
/// if let Some(child_pid) = signaler.current_pid() {
/// // Decide whether to forward signals based on process group
/// let child_pgid = unsafe { libc::getpgid(child_pid as i32) };
/// let our_pgid = unsafe { libc::getpgid(0) };
///
/// if child_pgid != our_pgid {
/// kill_signal.send(SignalKind::SIGINT);
/// }
/// }
///
/// let exit_code = execute_future.await;
/// ```
pub fn execute_with_signaler(
list: SequentialList,
env_vars: HashMap<OsString, OsString>,
cwd: PathBuf,
custom_commands: HashMap<String, Rc<dyn ShellCommand>>,
kill_signal: KillSignal,
) -> (ProcessSignaler, impl std::future::Future<Output = i32>) {
let signaler = ProcessSignaler::new();
let state = ShellState::new_with_process_signaler(
env_vars,
cwd,
custom_commands,
kill_signal,
signaler.clone(),
);
let future = async move {
execute_with_pipes(
list,
state,
ShellPipeReader::stdin(),
ShellPipeWriter::stdout(),
ShellPipeWriter::stderr(),
)
.await
};
(signaler, future)
}
/// Executes a `SequentialList` of commands with specified input and output pipes.
///
/// This function accepts a list of commands, a shell state, and pipes for standard input, output, and error.
/// This function allows the user to retrive the data outputted by the execution and act on it using code.
/// This is made public for the use-case of running tests with shell execution in application depending on the library.
///
/// # Arguments
///
/// * `list` - A `SequentialList` of commands to execute.
/// * `state` - The current state of the shell, including environment variables and the current directory.
/// * `stdin` - A reader for the standard input stream.
/// * `stdout` - A writer for the standard output stream.
/// * `stderr` - A writer for the standard error stream.
///
/// # Returns
///
/// The exit code of the command execution.
pub async fn execute_with_pipes(
list: SequentialList,
state: ShellState,
stdin: ShellPipeReader,
stdout: ShellPipeWriter,
stderr: ShellPipeWriter,
) -> i32 {
// spawn a sequential list and pipe its output to the environment
let result = execute_sequential_list(
list,
state,
stdin,
stdout,
stderr,
AsyncCommandBehavior::Wait,
)
.await;
match result {
ExecuteResult::Exit(code, _) => code,
ExecuteResult::Continue(exit_code, _, _) => exit_code,
}
}
#[derive(Debug, PartialEq)]
enum AsyncCommandBehavior {
Wait,
Yield,
}
fn execute_sequential_list(
list: SequentialList,
mut state: ShellState,
stdin: ShellPipeReader,
stdout: ShellPipeWriter,
stderr: ShellPipeWriter,
async_command_behavior: AsyncCommandBehavior,
) -> FutureExecuteResult {
async move {
let mut final_exit_code = 0;
let mut final_changes = Vec::new();
let mut async_handles = Vec::new();
let mut was_exit = false;
for item in list.items {
if item.is_async {
let state = state.clone();
let stdin = stdin.clone();
let stdout = stdout.clone();
let stderr = stderr.clone();
async_handles.push(tokio::task::spawn_local(async move {
let main_signal = state.kill_signal().clone();
let tree_exit_code_cell = state.tree_exit_code_cell().clone();
let result =
execute_sequence(item.sequence, state, stdin, stdout, stderr).await;
let (exit_code, handles) = result.into_exit_code_and_handles();
wait_handles(exit_code, handles, &main_signal, &tree_exit_code_cell)
.await
}));
} else {
let result = execute_sequence(
item.sequence,
state.clone(),
stdin.clone(),
stdout.clone(),
stderr.clone(),
)
.await;
match result {
ExecuteResult::Exit(exit_code, handles) => {
async_handles.extend(handles);
final_exit_code = exit_code;
was_exit = true;
break;
}
ExecuteResult::Continue(exit_code, changes, handles) => {
state.apply_changes(&changes);
state.apply_env_var(
OsStr::new("?"),
OsStr::new(&exit_code.to_string()),
);
final_changes.extend(changes);
async_handles.extend(handles);
// use the final sequential item's exit code
final_exit_code = exit_code;
}
}
}
}
// wait for async commands to complete
if async_command_behavior == AsyncCommandBehavior::Wait {
final_exit_code = wait_handles(
final_exit_code,
std::mem::take(&mut async_handles),
state.kill_signal(),
state.tree_exit_code_cell(),
)
.await;
}
if was_exit {
ExecuteResult::Exit(final_exit_code, async_handles)
} else {
ExecuteResult::Continue(final_exit_code, final_changes, async_handles)
}
}
.boxed_local()
}
async fn wait_handles(
mut exit_code: i32,
mut handles: Vec<JoinHandle<i32>>,
kill_signal: &KillSignal,
tree_exit_code_cell: &TreeExitCodeCell,
) -> i32 {
if exit_code != 0 {
// this section failed, so set it as the exit code
tree_exit_code_cell.try_set(exit_code);
kill_signal.send(SignalKind::SIGTERM);
}
// prefer surfacing the tree exit code because it's the main reason for the failure
exit_code = tree_exit_code_cell.get().unwrap_or(exit_code);
while !handles.is_empty() {
let (result, _, remaining) = futures::future::select_all(handles).await;
// prefer the first non-zero exit code
let new_exit_code = result.unwrap();
if exit_code == 0 && new_exit_code != 0 {
exit_code = new_exit_code;
}
handles = remaining;
}
exit_code
}
fn execute_sequence(
sequence: Sequence,
mut state: ShellState,
stdin: ShellPipeReader,
stdout: ShellPipeWriter,
mut stderr: ShellPipeWriter,
) -> FutureExecuteResult {
// requires boxed async because of recursive async
async move {
match sequence {
Sequence::ShellVar(var) => ExecuteResult::Continue(
0,
vec![EnvChange::SetShellVar(
var.name.into(),
match evaluate_word(var.value, &state, stdin, stderr.clone()).await {
Ok(value) => value,
Err(err) => {
return err.into_exit_code(&mut stderr);
}
},
)],
Vec::new(),
),
Sequence::BooleanList(list) => {
let mut changes = vec![];
let first_result = execute_sequence(
list.current,
state.clone(),
stdin.clone(),
stdout.clone(),
stderr.clone(),
)
.await;
let (exit_code, mut async_handles) = match first_result {
ExecuteResult::Exit(_, _) => return first_result,
ExecuteResult::Continue(exit_code, sub_changes, async_handles) => {
state.apply_env_var(
OsStr::new("?"),
OsStr::new(&exit_code.to_string()),
);
state.apply_changes(&sub_changes);
changes.extend(sub_changes);
(exit_code, async_handles)
}
};
let next = if list.op.moves_next_for_exit_code(exit_code) {
Some(list.next)
} else {
let mut next = list.next;
loop {
// boolean lists always move right on the tree
match next {
Sequence::BooleanList(list) => {
if list.op.moves_next_for_exit_code(exit_code) {
break Some(list.next);
}
next = list.next;
}
_ => break None,
}
}
};
if let Some(next) = next {
let next_result =
execute_sequence(next, state, stdin, stdout, stderr).await;
match next_result {
ExecuteResult::Exit(code, sub_handles) => {
async_handles.extend(sub_handles);
ExecuteResult::Exit(code, async_handles)
}
ExecuteResult::Continue(exit_code, sub_changes, sub_handles) => {
changes.extend(sub_changes);
async_handles.extend(sub_handles);
ExecuteResult::Continue(exit_code, changes, async_handles)
}
}
} else {
ExecuteResult::Continue(exit_code, changes, async_handles)
}
}
Sequence::Pipeline(pipeline) => {
execute_pipeline(pipeline, state, stdin, stdout, stderr).await
}
}
}
.boxed_local()
}
async fn execute_pipeline(
pipeline: Pipeline,
state: ShellState,
stdin: ShellPipeReader,
stdout: ShellPipeWriter,
stderr: ShellPipeWriter,
) -> ExecuteResult {
let result =
execute_pipeline_inner(pipeline.inner, state, stdin, stdout, stderr).await;
if pipeline.negated {
match result {
ExecuteResult::Exit(code, handles) => ExecuteResult::Exit(code, handles),
ExecuteResult::Continue(code, changes, handles) => {
let new_code = if code == 0 { 1 } else { 0 };
ExecuteResult::Continue(new_code, changes, handles)
}
}
} else {
result
}
}
async fn execute_pipeline_inner(
pipeline: PipelineInner,
state: ShellState,
stdin: ShellPipeReader,
stdout: ShellPipeWriter,
stderr: ShellPipeWriter,
) -> ExecuteResult {
match pipeline {
PipelineInner::Command(command) => {
execute_command(command, state, stdin, stdout, stderr).await
}
PipelineInner::PipeSequence(pipe_sequence) => {
execute_pipe_sequence(*pipe_sequence, state, stdin, stdout, stderr).await
}
}
}
#[derive(Debug)]
enum RedirectPipe {
Input(ShellPipeReader),
Output(ShellPipeWriter),
}
async fn resolve_redirect_pipe(
redirect: &Redirect,
state: &ShellState,
stdin: &ShellPipeReader,
stdout: &ShellPipeWriter,
stderr: &mut ShellPipeWriter,
) -> Result<RedirectPipe, ExecuteResult> {
match redirect.io_file.clone() {
IoFile::Word(word) => {
resolve_redirect_word_pipe(word, &redirect.op, state, stdin, stderr).await
}
IoFile::Fd(fd) => match &redirect.op {
RedirectOp::Input(RedirectOpInput::Redirect) => {
let _ = stderr.write_line(
"deno_task_shell: input redirecting file descriptors is not implemented",
);
Err(ExecuteResult::from_exit_code(1))
}
RedirectOp::Output(_op) => match fd {
1 => Ok(RedirectPipe::Output(stdout.clone())),
2 => Ok(RedirectPipe::Output(stderr.clone())),
_ => {
let _ = stderr.write_line(
"deno_task_shell: output redirecting file descriptors beyond stdout and stderr is not implemented",
);
Err(ExecuteResult::from_exit_code(1))
}
},
},
}
}
async fn resolve_redirect_word_pipe(
word: Word,
redirect_op: &RedirectOp,
state: &ShellState,
stdin: &ShellPipeReader,
stderr: &mut ShellPipeWriter,
) -> Result<RedirectPipe, ExecuteResult> {
fn handle_std_result(
output_path: &Path,
std_file_result: std::io::Result<std::fs::File>,
stderr: &mut ShellPipeWriter,
) -> Result<std::fs::File, ExecuteResult> {
match std_file_result {
Ok(std_file) => Ok(std_file),
Err(err) => {
let _ = stderr.write_line(&format!(
"error opening file for redirect ({}). {:#}",
output_path.display(),
err
));
Err(ExecuteResult::from_exit_code(1))
}
}
}
let words = evaluate_word_parts(
word.into_parts(),
state,
stdin.clone(),
stderr.clone(),
)
.await;
let words = match words {
Ok(word) => word,
Err(err) => {
return Err(err.into_exit_code(stderr));
}
};
// edge case that's not supported
if words.is_empty() {
let _ = stderr.write_line("redirect path must be 1 argument, but found 0");
return Err(ExecuteResult::from_exit_code(1));
} else if words.len() > 1 {
let _ = stderr.write_line(&format!(
concat!(
"redirect path must be 1 argument, but found {0} ({1}). ",
"Did you mean to quote it (ex. \"{1}\")?"
),
words.len(),
os_string_join(&words, " ").to_string_lossy()
));
return Err(ExecuteResult::from_exit_code(1));
}
let output_path = &words[0];
match &redirect_op {
RedirectOp::Input(RedirectOpInput::Redirect) => {
let output_path = state.cwd().join(output_path);
let std_file_result =
std::fs::OpenOptions::new().read(true).open(&output_path);
handle_std_result(&output_path, std_file_result, stderr).map(|std_file| {
RedirectPipe::Input(ShellPipeReader::from_std(std_file))
})
}
RedirectOp::Output(op) => {
// cross platform suppress output
if output_path == "/dev/null" {
return Ok(RedirectPipe::Output(ShellPipeWriter::null()));
}
let output_path = state.cwd().join(output_path);
let is_append = *op == RedirectOpOutput::Append;
let std_file_result = std::fs::OpenOptions::new()
.write(true)
.create(true)
.append(is_append)
.truncate(!is_append)
.open(&output_path);
handle_std_result(&output_path, std_file_result, stderr).map(|std_file| {
RedirectPipe::Output(ShellPipeWriter::from_std(std_file))
})
}
}
}
async fn execute_command(
command: Command,
state: ShellState,
stdin: ShellPipeReader,
stdout: ShellPipeWriter,
mut stderr: ShellPipeWriter,
) -> ExecuteResult {
let (stdin, stdout, stderr) = if let Some(redirect) = &command.redirect {
let pipe = match resolve_redirect_pipe(
redirect,
&state,
&stdin,
&stdout,
&mut stderr,
)
.await
{
Ok(value) => value,
Err(value) => return value,
};
match pipe {
RedirectPipe::Input(pipe) => match redirect.maybe_fd {
Some(_) => {
let _ = stderr.write_line(
"input redirects with file descriptors are not supported",
);
return ExecuteResult::from_exit_code(1);
}
None => (pipe, stdout, stderr),
},
RedirectPipe::Output(pipe) => match redirect.maybe_fd {
Some(RedirectFd::Fd(2)) => (stdin, stdout, pipe),
Some(RedirectFd::Fd(1)) | None => (stdin, pipe, stderr),
Some(RedirectFd::Fd(_)) => {
let _ = stderr.write_line(
"only redirecting to stdout (1) and stderr (2) is supported",
);
return ExecuteResult::from_exit_code(1);
}
Some(RedirectFd::StdoutStderr) => (stdin, pipe.clone(), pipe),
},
}
} else {
(stdin, stdout, stderr)
};
match command.inner {
CommandInner::Simple(command) => {
execute_simple_command(command, state, stdin, stdout, stderr).await
}
CommandInner::Subshell(list) => {
execute_subshell(list, state, stdin, stdout, stderr).await
}
}
}
async fn execute_pipe_sequence(
pipe_sequence: PipeSequence,
state: ShellState,
stdin: ShellPipeReader,
stdout: ShellPipeWriter,
stderr: ShellPipeWriter,
) -> ExecuteResult {
let mut wait_tasks = vec![];
let mut last_output = Some(stdin);
let mut next_inner: Option<PipelineInner> = Some(pipe_sequence.into());
while let Some(sequence) = next_inner.take() {
let (output_reader, output_writer) = pipe();
let (stderr, command) = match sequence {
PipelineInner::PipeSequence(pipe_sequence) => {
next_inner = Some(pipe_sequence.next);
(
match pipe_sequence.op {
PipeSequenceOperator::Stdout => stderr.clone(),
PipeSequenceOperator::StdoutStderr => output_writer.clone(),
},
pipe_sequence.current,
)
}
PipelineInner::Command(command) => (stderr.clone(), command),
};
wait_tasks.push(execute_command(
command,
state.clone(),
last_output.take().unwrap(),
output_writer.clone(),
stderr.clone(),
));
last_output = Some(output_reader);
}
let output_handle = tokio::task::spawn_blocking(|| {
last_output.unwrap().pipe_to_sender(stdout).unwrap();
});
let mut results = futures::future::join_all(wait_tasks).await;
output_handle.await.unwrap();
let last_result = results.pop().unwrap();
let all_handles = results.into_iter().flat_map(|r| r.into_handles());
match last_result {
ExecuteResult::Exit(code, mut handles) => {
handles.extend(all_handles);
ExecuteResult::Continue(code, Vec::new(), handles)
}
ExecuteResult::Continue(code, _, mut handles) => {
handles.extend(all_handles);
ExecuteResult::Continue(code, Vec::new(), handles)
}
}
}
async fn execute_subshell(
list: Box<SequentialList>,
state: ShellState,
stdin: ShellPipeReader,
stdout: ShellPipeWriter,
stderr: ShellPipeWriter,
) -> ExecuteResult {
let result = execute_sequential_list(
*list,
state,
stdin,
stdout,
stderr,
// yield async commands to the parent
AsyncCommandBehavior::Yield,
)
.await;
match result {
ExecuteResult::Exit(code, handles) => {
// sub shells do not cause an exit
ExecuteResult::Continue(code, Vec::new(), handles)
}
ExecuteResult::Continue(code, _env_changes, handles) => {
// env changes are not propagated
ExecuteResult::Continue(code, Vec::new(), handles)
}
}
}
async fn execute_simple_command(
command: SimpleCommand,
state: ShellState,
stdin: ShellPipeReader,
stdout: ShellPipeWriter,
mut stderr: ShellPipeWriter,
) -> ExecuteResult {
let args =
evaluate_args(command.args, &state, stdin.clone(), stderr.clone()).await;
let args = match args {
Ok(args) => args,
Err(err) => {
return err.into_exit_code(&mut stderr);
}
};
let mut state = state.clone();
for env_var in command.env_vars {
let value =
evaluate_word(env_var.value, &state, stdin.clone(), stderr.clone()).await;
let value = match value {
Ok(value) => value,
Err(err) => {
return err.into_exit_code(&mut stderr);
}
};
state.apply_env_var(OsStr::new(&env_var.name), OsStr::new(&value));
}
execute_command_args(args, state, stdin, stdout, stderr).await
}
fn execute_command_args(
mut args: Vec<OsString>,
state: ShellState,
stdin: ShellPipeReader,
stdout: ShellPipeWriter,
mut stderr: ShellPipeWriter,
) -> FutureExecuteResult {
let command_name = if args.is_empty() {
OsString::new()
} else {
args.remove(0)
};
if let Some(exit_code) = state.kill_signal().aborted_code() {
Box::pin(future::ready(ExecuteResult::from_exit_code(exit_code)))
} else if let Some(stripped_name) =
command_name.to_string_lossy().strip_prefix('!')
{
let _ = stderr.write_line(
&format!(concat!(
"History expansion is not supported:\n",
" {}\n",
" ~\n\n",
"Perhaps you meant to add a space after the exclamation point to negate the command?\n",
" ! {}",
), command_name.to_string_lossy(), stripped_name)
);
Box::pin(future::ready(ExecuteResult::from_exit_code(1)))
} else {
let command_context = ShellCommandContext {
args,
state,
stdin,
stdout,
stderr,
execute_command_args: Box::new(move |context| {
execute_command_args(
context.args,
context.state,
context.stdin,
context.stdout,
context.stderr,
)
}),
};
match command_context.state.resolve_custom_command(&command_name) {
Some(command) => command.execute(command_context),
None => execute_unresolved_command_name(
UnresolvedCommandName {
name: command_name,
base_dir: command_context.state.cwd().to_path_buf(),
},
command_context,
),
}
}
}
pub async fn evaluate_args(
args: Vec<Word>,
state: &ShellState,
stdin: ShellPipeReader,
stderr: ShellPipeWriter,
) -> Result<Vec<OsString>, EvaluateWordTextError> {
let mut result = Vec::new();
for arg in args {
let parts = evaluate_word_parts(
arg.into_parts(),
state,
stdin.clone(),
stderr.clone(),
)
.await?;
result.extend(parts);
}
Ok(result)
}
async fn evaluate_word(
word: Word,
state: &ShellState,
stdin: ShellPipeReader,
stderr: ShellPipeWriter,
) -> Result<OsString, EvaluateWordTextError> {
let word_parts =
evaluate_word_parts(word.into_parts(), state, stdin, stderr).await?;
Ok(os_string_join(&word_parts, " "))
}
#[derive(Debug, Error)]
pub enum EvaluateWordTextError {
#[error("glob: no matches found '{}'. {}", pattern, err)]
InvalidPattern {
pattern: String,
err: glob::PatternError,
},
#[error("glob: no matches found '{}'. Pattern part was not valid utf-8", part.to_string_lossy())]
NotUtf8Pattern { part: OsString },
#[error("glob: no matches found '{}'", pattern)]
NoFilesMatched { pattern: String },
#[error("invalid utf-8: {}", err)]
InvalidUtf8 {
#[from]
err: FromUtf8Error,
},
#[error("failed resolving home directory for tilde expansion")]
NoHomeDirectory,
}
impl EvaluateWordTextError {
pub fn into_exit_code(self, stderr: &mut ShellPipeWriter) -> ExecuteResult {
let _ = stderr.write_line(&self.to_string());
ExecuteResult::from_exit_code(1)
}
}
fn evaluate_word_parts(
parts: Vec<WordPart>,
state: &ShellState,
stdin: ShellPipeReader,
stderr: ShellPipeWriter,
) -> LocalBoxFuture<'_, Result<Vec<OsString>, EvaluateWordTextError>> {
#[derive(Debug)]
enum TextPart {
Quoted(OsString),
Text(OsString),
}
impl TextPart {
pub fn as_str(&self) -> &OsStr {
match self {
TextPart::Quoted(text) => text,
TextPart::Text(text) => text,
}
}
}
fn text_parts_to_string(parts: Vec<TextPart>) -> OsString {
let mut result =
OsString::with_capacity(parts.iter().map(|p| p.as_str().len()).sum());
for part in parts {
result.push(part.as_str());
}
result
}
fn evaluate_word_text(
state: &ShellState,
text_parts: Vec<TextPart>,
is_quoted: bool,
) -> Result<Vec<OsString>, EvaluateWordTextError> {
if !is_quoted
&& text_parts
.iter()
.filter_map(|p| match p {
TextPart::Quoted(_) => None,
TextPart::Text(text) => text.to_str(),
})
.any(|text| text.chars().any(|c| matches!(c, '?' | '*' | '[')))
{
let mut current_text = String::new();
for text_part in text_parts {
match text_part {
TextPart::Quoted(text) => {
if let Some(text) = text.to_str() {
for c in text.chars() {
match c {
'?' | '*' | '[' | ']' => {
// escape because it was quoted
current_text.push('[');
current_text.push(c);
current_text.push(']');
}
_ => current_text.push(c),
}
}
} else {
return Err(EvaluateWordTextError::NotUtf8Pattern { part: text });
}
}
TextPart::Text(text) => {
if let Some(text) = text.to_str() {
current_text.push_str(text);
} else {
return Err(EvaluateWordTextError::NotUtf8Pattern { part: text });
}
}
}
}
let is_absolute = Path::new(¤t_text).is_absolute();
let cwd = state.cwd();
let pattern = if is_absolute {
current_text
} else {
format!("{}/{}", cwd.display(), current_text)
};
let result = glob::glob_with(
&pattern,
glob::MatchOptions {
// false because it should work the same way on case insensitive file systems
case_sensitive: false,
// true because it copies what sh does
require_literal_separator: true,
// true because it copies with sh does—these files are considered "hidden"
require_literal_leading_dot: true,
},
);
match result {
Ok(paths) => {
let paths =
paths.into_iter().filter_map(|p| p.ok()).collect::<Vec<_>>();
if paths.is_empty() {
Err(EvaluateWordTextError::NoFilesMatched { pattern })
} else {
let paths = if is_absolute {
paths
.into_iter()
.map(|p| p.into_os_string())
.collect::<Vec<_>>()
} else {
paths
.into_iter()
.map(|p| {
let path = p.strip_prefix(cwd).unwrap();
path.to_path_buf().into_os_string()
})
.collect::<Vec<_>>()
};
Ok(paths)
}
}
Err(err) => Err(EvaluateWordTextError::InvalidPattern { pattern, err }),
}
} else {
Ok(vec![text_parts_to_string(text_parts)])
}
}
fn evaluate_word_parts_inner(
parts: Vec<WordPart>,
is_quoted: bool,
state: &ShellState,
stdin: ShellPipeReader,
stderr: ShellPipeWriter,
) -> LocalBoxFuture<'_, Result<Vec<OsString>, EvaluateWordTextError>> {
// recursive async, so requires boxing
async move {
let mut result = Vec::new();
let mut current_text = Vec::new();
for part in parts {
let evaluation_result_text = match part {
WordPart::Text(text) => {
current_text.push(TextPart::Text(text.into()));
None
}
WordPart::Variable(name) => state.get_var(OsStr::new(&name)).cloned(),
WordPart::Tilde => Some(
sys_traits::impls::real_home_dir_with_env(state)
.map(|s| s.into_os_string())
.ok_or(EvaluateWordTextError::NoHomeDirectory)?,
),
WordPart::Command(list) => Some(
evaluate_command_substitution(
list,
// contain cancellation to the command substitution
&state.with_child_signal(),
stdin.clone(),
stderr.clone(),
)
.await?,
),
WordPart::Quoted(parts) => {
let parts = evaluate_word_parts_inner(
parts,
true,
state,
stdin.clone(),
stderr.clone(),
)
.await?;
let text = os_string_join(&parts, " ");
current_text.push(TextPart::Quoted(text));
continue;
}