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
use nu_cmd_base::hook::eval_hook;
use nu_engine::{command_prelude::*, env_to_strings, get_eval_expression};
use nu_protocol::{ast::Expr, did_you_mean, IoStream, ListStream, NuGlob, RawStream};
use nu_system::ForegroundChild;
use nu_utils::IgnoreCaseExt;
use os_pipe::PipeReader;
use pathdiff::diff_paths;
use std::{
collections::HashMap,
io::{BufRead, BufReader, Read, Write},
path::{Path, PathBuf},
process::{Command as CommandSys, Stdio},
sync::{mpsc, Arc},
thread,
};
#[derive(Clone)]
pub struct External;
impl Command for External {
fn name(&self) -> &str {
"run-external"
}
fn usage(&self) -> &str {
"Runs external command."
}
fn signature(&self) -> nu_protocol::Signature {
Signature::build(self.name())
.input_output_types(vec![(Type::Any, Type::Any)])
.switch("redirect-stdout", "redirect stdout to the pipeline", None)
.switch("redirect-stderr", "redirect stderr to the pipeline", None)
.switch(
"redirect-combine",
"redirect both stdout and stderr combined to the pipeline (collected in stdout)",
None,
)
.switch("trim-end-newline", "trimming end newlines", None)
.required("command", SyntaxShape::String, "External command to run.")
.rest("args", SyntaxShape::Any, "Arguments for external command.")
.category(Category::System)
}
fn run(
&self,
engine_state: &EngineState,
stack: &mut Stack,
call: &Call,
input: PipelineData,
) -> Result<PipelineData, ShellError> {
let redirect_stdout = call.has_flag(engine_state, stack, "redirect-stdout")?;
let redirect_stderr = call.has_flag(engine_state, stack, "redirect-stderr")?;
let redirect_combine = call.has_flag(engine_state, stack, "redirect-combine")?;
let trim_end_newline = call.has_flag(engine_state, stack, "trim-end-newline")?;
if redirect_combine && (redirect_stdout || redirect_stderr) {
return Err(ShellError::ExternalCommand {
label: "Cannot use --redirect-combine with --redirect-stdout or --redirect-stderr"
.into(),
help: "use either --redirect-combine or redirect a single output stream".into(),
span: call.head,
});
}
if trim_end_newline {
nu_protocol::report_error_new(
engine_state,
&ShellError::GenericError {
error: "Deprecated flag".into(),
msg: "`--trim-end-newline` is deprecated".into(),
span: Some(call.arguments_span()),
help: Some(
"trailing new lines are now removed by default when collecting into a value"
.into(),
),
inner: vec![],
},
);
}
if redirect_combine {
nu_protocol::report_error_new(
engine_state,
&ShellError::GenericError {
error: "Deprecated flag".into(),
msg: "`--redirect-combine` is deprecated".into(),
span: Some(call.arguments_span()),
help: Some("use the `o+e>|` pipe redirection instead".into()),
inner: vec![],
},
);
} else if redirect_stdout {
nu_protocol::report_error_new(
engine_state,
&ShellError::GenericError {
error: "Deprecated flag".into(),
msg: "`--redirect-stdout` is deprecated".into(),
span: Some(call.arguments_span()),
help: Some(
"`run-external` will now always redirect stdout if there is a pipe `|` afterwards"
.into(),
),
inner: vec![],
},
);
} else if redirect_stderr {
nu_protocol::report_error_new(
engine_state,
&ShellError::GenericError {
error: "Deprecated flag".into(),
msg: "`--redirect-stderr` is deprecated".into(),
span: Some(call.arguments_span()),
help: Some("use the `e>|` stderr pipe redirection instead".into()),
inner: vec![],
},
);
}
let command = create_external_command(engine_state, stack, call)?;
command.run_with_input(engine_state, stack, input, false)
}
fn examples(&self) -> Vec<Example> {
vec![
Example {
description: "Run an external command",
example: r#"run-external "echo" "-n" "hello""#,
result: None,
},
Example {
description: "Redirect stdout from an external command into the pipeline",
example: r#"run-external "echo" "-n" "hello" | split chars"#,
result: None,
},
Example {
description: "Redirect stderr from an external command into the pipeline",
example: r#"run-external "nu" "-c" "print -e hello" e>| split chars"#,
result: None,
},
]
}
}
/// Creates ExternalCommand from a call
pub fn create_external_command(
engine_state: &EngineState,
stack: &mut Stack,
call: &Call,
) -> Result<ExternalCommand, ShellError> {
let name: Spanned<String> = call.req(engine_state, stack, 0)?;
// Translate environment variables from Values to Strings
let env_vars_str = env_to_strings(engine_state, stack)?;
fn value_as_spanned(value: Value) -> Result<Spanned<String>, ShellError> {
let span = value.span();
value
.coerce_string()
.map(|item| Spanned { item, span })
.map_err(|_| ShellError::ExternalCommand {
label: format!("Cannot convert {} to a string", value.get_type()),
help: "All arguments to an external command need to be string-compatible".into(),
span,
})
}
let eval_expression = get_eval_expression(engine_state);
let mut spanned_args = vec![];
let mut arg_keep_raw = vec![];
for (arg, spread) in call.rest_iter(1) {
match eval_expression(engine_state, stack, arg)? {
Value::List { vals, .. } => {
if spread {
// turn all the strings in the array into params.
// Example: one_arg may be something like ["ls" "-a"]
// convert it to "ls" "-a"
for v in vals {
spanned_args.push(value_as_spanned(v)?);
// for arguments in list, it's always treated as a whole arguments
arg_keep_raw.push(true);
}
} else {
return Err(ShellError::CannotPassListToExternal {
arg: String::from_utf8_lossy(engine_state.get_span_contents(arg.span))
.into(),
span: arg.span,
});
}
}
val => {
if spread {
return Err(ShellError::CannotSpreadAsList { span: arg.span });
} else {
spanned_args.push(value_as_spanned(val)?);
match arg.expr {
// refer to `parse_dollar_expr` function
// the expression type of $variable_name, $"($variable_name)"
// will be Expr::StringInterpolation, Expr::FullCellPath
Expr::StringInterpolation(_) | Expr::FullCellPath(_) => {
arg_keep_raw.push(true)
}
_ => arg_keep_raw.push(false),
}
}
}
}
}
Ok(ExternalCommand {
name,
args: spanned_args,
arg_keep_raw,
out: stack.stdout().clone(),
err: stack.stderr().clone(),
env_vars: env_vars_str,
})
}
#[derive(Clone)]
pub struct ExternalCommand {
pub name: Spanned<String>,
pub args: Vec<Spanned<String>>,
pub arg_keep_raw: Vec<bool>,
pub out: IoStream,
pub err: IoStream,
pub env_vars: HashMap<String, String>,
}
impl ExternalCommand {
pub fn run_with_input(
&self,
engine_state: &EngineState,
stack: &mut Stack,
input: PipelineData,
reconfirm_command_name: bool,
) -> Result<PipelineData, ShellError> {
let head = self.name.span;
let ctrlc = engine_state.ctrlc.clone();
#[allow(unused_mut)]
let (cmd, mut reader) = self.create_process(&input, false, head)?;
#[cfg(all(not(unix), not(windows)))] // are there any systems like this?
let child = ForegroundChild::spawn(cmd);
#[cfg(windows)]
let child = match ForegroundChild::spawn(cmd) {
Ok(child) => Ok(child),
Err(err) => {
// Running external commands on Windows has 2 points of complication:
// 1. Some common Windows commands are actually built in to cmd.exe, not executables in their own right.
// 2. We need to let users run batch scripts etc. (.bat, .cmd) without typing their extension
// To support these situations, we have a fallback path that gets run if a command
// fails to be run as a normal executable:
// 1. "shell out" to cmd.exe if the command is a known cmd.exe internal command
// 2. Otherwise, use `which-rs` to look for batch files etc. then run those in cmd.exe
// set the default value, maybe we'll override it later
let mut child = Err(err);
// This has the full list of cmd.exe "internal" commands: https://ss64.com/nt/syntax-internal.html
// I (Reilly) went through the full list and whittled it down to ones that are potentially useful:
const CMD_INTERNAL_COMMANDS: [&str; 9] = [
"ASSOC", "CLS", "ECHO", "FTYPE", "MKLINK", "PAUSE", "START", "VER", "VOL",
];
let command_name = &self.name.item;
let looks_like_cmd_internal = CMD_INTERNAL_COMMANDS
.iter()
.any(|&cmd| command_name.eq_ignore_ascii_case(cmd));
if looks_like_cmd_internal {
let (cmd, new_reader) = self.create_process(&input, true, head)?;
reader = new_reader;
child = ForegroundChild::spawn(cmd);
} else {
#[cfg(feature = "which-support")]
{
// maybe it's a batch file (foo.cmd) and the user typed `foo`. Try to find it with `which-rs`
// TODO: clean this up with an if-let chain once those are stable
if let Ok(path) =
nu_engine::env::path_str(engine_state, stack, self.name.span)
{
if let Some(cwd) = self.env_vars.get("PWD") {
// append cwd to PATH so `which-rs` looks in the cwd too.
// this approximates what cmd.exe does.
let path_with_cwd = format!("{};{}", cwd, path);
if let Ok(which_path) =
which::which_in(&self.name.item, Some(path_with_cwd), cwd)
{
if let Some(file_name) = which_path.file_name() {
if !file_name.to_string_lossy().eq_ignore_case(command_name)
{
// which-rs found an executable file with a slightly different name
// than the one the user tried. Let's try running it
let mut new_command = self.clone();
new_command.name = Spanned {
item: file_name.to_string_lossy().to_string(),
span: self.name.span,
};
let (cmd, new_reader) =
new_command.create_process(&input, true, head)?;
reader = new_reader;
child = ForegroundChild::spawn(cmd);
}
}
}
}
}
}
}
child
}
};
#[cfg(unix)]
let child = ForegroundChild::spawn(
cmd,
engine_state.is_interactive,
&engine_state.pipeline_externals_state,
);
match child {
Err(err) => {
match err.kind() {
// If file not found, try suggesting alternative commands to the user
std::io::ErrorKind::NotFound => {
// recommend a replacement if the user tried a removed command
let command_name_lower = self.name.item.to_lowercase();
let removed_from_nu = crate::removed_commands();
if removed_from_nu.contains_key(&command_name_lower) {
let replacement = match removed_from_nu.get(&command_name_lower) {
Some(s) => s.clone(),
None => "".to_string(),
};
return Err(ShellError::RemovedCommand {
removed: command_name_lower,
replacement,
span: self.name.span,
});
}
let suggestion = suggest_command(&self.name.item, engine_state);
let label = match suggestion {
Some(s) => {
if reconfirm_command_name {
format!(
"'{}' was not found; did you mean '{s}'?",
self.name.item
)
} else {
let cmd_name = &self.name.item;
let maybe_module = engine_state
.which_module_has_decl(cmd_name.as_bytes(), &[]);
if let Some(module_name) = maybe_module {
let module_name = String::from_utf8_lossy(module_name);
let new_name = &[module_name.as_ref(), cmd_name].join(" ");
if engine_state
.find_decl(new_name.as_bytes(), &[])
.is_some()
{
format!("command '{cmd_name}' was not found but it was imported from module '{module_name}'; try using `{new_name}`")
} else {
format!("command '{cmd_name}' was not found but it exists in module '{module_name}'; try importing it with `use`")
}
} else {
// If command and suggestion are the same, display not found
if cmd_name == &s {
format!("'{cmd_name}' was not found")
} else {
format!("did you mean '{s}'?")
}
}
}
}
None => {
if reconfirm_command_name {
format!("executable '{}' was not found", self.name.item)
} else {
"executable was not found".into()
}
}
};
let mut err_str = err.to_string();
if engine_state.is_interactive {
let mut engine_state = engine_state.clone();
if let Some(hook) = engine_state.config.hooks.command_not_found.clone()
{
let canary = "ENTERED_COMMAND_NOT_FOUND";
let stack = &mut stack.start_capture();
if stack.has_env_var(&engine_state, canary) {
return Err(ShellError::ExternalCommand {
label: "command_not_found handler could not be run".into(),
help: "make sure the command_not_found closure itself does not use unknown commands".to_string(),
span: self.name.span,
});
}
stack.add_env_var(
canary.to_string(),
Value::bool(true, Span::unknown()),
);
match eval_hook(
&mut engine_state,
stack,
None,
vec![(
"cmd_name".into(),
Value::string(self.name.item.to_string(), self.name.span),
)],
&hook,
"command_not_found",
) {
Ok(PipelineData::Value(Value::String { val, .. }, ..)) => {
err_str = format!("{}\n{}", err_str, val);
}
Err(err) => {
stack.remove_env_var(&engine_state, canary);
return Err(err);
}
_ => {}
}
stack.remove_env_var(&engine_state, canary);
}
}
Err(ShellError::ExternalCommand {
label,
help: err_str,
span: self.name.span,
})
}
// otherwise, a default error message
_ => Err(ShellError::ExternalCommand {
label: "can't run executable".into(),
help: err.to_string(),
span: self.name.span,
}),
}
}
Ok(mut child) => {
if !input.is_nothing() {
let mut engine_state = engine_state.clone();
let mut stack = stack.clone();
// Turn off color as we pass data through
Arc::make_mut(&mut engine_state.config).use_ansi_coloring = false;
// Pipe input into the external command's stdin
if let Some(mut stdin_write) = child.as_mut().stdin.take() {
thread::Builder::new()
.name("external stdin worker".to_string())
.spawn(move || {
let input = match input {
input @ PipelineData::Value(Value::Binary { .. }, ..) => {
Ok(input)
}
input => {
let stack = &mut stack.start_capture();
// Attempt to render the input as a table before piping it to the external.
// This is important for pagers like `less`;
// they need to get Nu data rendered for display to users.
//
// TODO: should we do something different for list<string> inputs?
// Users often expect those to be piped to *nix tools as raw strings separated by newlines
crate::Table.run(
&engine_state,
stack,
&Call::new(head),
input,
)
}
};
if let Ok(input) = input {
for value in input.into_iter() {
let buf = match value {
Value::String { val, .. } => val.into_bytes(),
Value::Binary { val, .. } => val,
_ => return Err(()),
};
if stdin_write.write(&buf).is_err() {
return Ok(());
}
}
}
Ok(())
})
.map_err(|e| e.into_spanned(head))?;
}
}
#[cfg(unix)]
let commandname = self.name.item.clone();
let span = self.name.span;
let (exit_code_tx, exit_code_rx) = mpsc::channel();
let (stdout, stderr) = if let Some(combined) = reader {
(
Some(RawStream::new(
Box::new(ByteLines::new(combined)),
ctrlc.clone(),
head,
None,
)),
None,
)
} else {
let stdout = child.as_mut().stdout.take().map(|out| {
RawStream::new(Box::new(ByteLines::new(out)), ctrlc.clone(), head, None)
});
let stderr = child.as_mut().stderr.take().map(|err| {
RawStream::new(Box::new(ByteLines::new(err)), ctrlc.clone(), head, None)
});
if matches!(self.err, IoStream::Pipe) {
(stderr, stdout)
} else {
(stdout, stderr)
}
};
// Create a thread to wait for an exit code.
thread::Builder::new()
.name("exit code waiter".into())
.spawn(move || match child.as_mut().wait() {
Err(err) => Err(ShellError::ExternalCommand {
label: "External command exited with error".into(),
help: err.to_string(),
span,
}),
Ok(x) => {
#[cfg(unix)]
{
use nix::sys::signal::Signal;
use nu_ansi_term::{Color, Style};
use std::os::unix::process::ExitStatusExt;
if x.core_dumped() {
let cause = x
.signal()
.and_then(|sig| {
Signal::try_from(sig).ok().map(Signal::as_str)
})
.unwrap_or("Something went wrong");
let style = Style::new().bold().on(Color::Red);
let message = format!(
"{cause}: child process '{commandname}' core dumped"
);
eprintln!("{}", style.paint(&message));
let _ = exit_code_tx.send(Value::error(
ShellError::ExternalCommand {
label: "core dumped".into(),
help: message,
span: head,
},
head,
));
return Ok(());
}
}
if let Some(code) = x.code() {
let _ = exit_code_tx.send(Value::int(code as i64, head));
} else if x.success() {
let _ = exit_code_tx.send(Value::int(0, head));
} else {
let _ = exit_code_tx.send(Value::int(-1, head));
}
Ok(())
}
})
.map_err(|e| e.into_spanned(head))?;
let exit_code_receiver = ValueReceiver::new(exit_code_rx);
Ok(PipelineData::ExternalStream {
stdout,
stderr,
exit_code: Some(ListStream::from_stream(
Box::new(exit_code_receiver),
ctrlc.clone(),
)),
span: head,
metadata: None,
trim_end_newline: true,
})
}
}
}
pub fn create_process(
&self,
input: &PipelineData,
use_cmd: bool,
span: Span,
) -> Result<(CommandSys, Option<PipeReader>), ShellError> {
let mut process = if let Some(d) = self.env_vars.get("PWD") {
let mut process = if use_cmd {
self.spawn_cmd_command(d)
} else {
self.create_command(d)?
};
// do not try to set current directory if cwd does not exist
if Path::new(&d).exists() {
process.current_dir(d);
}
process
} else {
return Err(ShellError::GenericError{
error: "Current directory not found".into(),
msg: "did not find PWD environment variable".into(),
span: Some(span),
help: Some(concat!(
"The environment variable 'PWD' was not found. ",
"It is required to define the current directory when running an external command."
).into()),
inner:Vec::new(),
});
};
process.envs(&self.env_vars);
// If the external is not the last command, its output will get piped
// either as a string or binary
let reader = if matches!(self.out, IoStream::Pipe) && matches!(self.err, IoStream::Pipe) {
let (reader, writer) = os_pipe::pipe()?;
let writer_clone = writer.try_clone()?;
process.stdout(writer);
process.stderr(writer_clone);
Some(reader)
} else {
process.stdout(Stdio::try_from(&self.out)?);
process.stderr(Stdio::try_from(&self.err)?);
None
};
// If there is an input from the pipeline. The stdin from the process
// is piped so it can be used to send the input information
if !input.is_nothing() {
process.stdin(Stdio::piped());
}
Ok((process, reader))
}
fn create_command(&self, cwd: &str) -> Result<CommandSys, ShellError> {
// in all the other cases shell out
if cfg!(windows) {
//TODO. This should be modifiable from the config file.
// We could give the option to call from powershell
// for minimal builds cwd is unused
if self.name.item.ends_with(".cmd") || self.name.item.ends_with(".bat") {
Ok(self.spawn_cmd_command(cwd))
} else {
self.spawn_simple_command(cwd)
}
} else {
self.spawn_simple_command(cwd)
}
}
/// Spawn a command without shelling out to an external shell
pub fn spawn_simple_command(&self, cwd: &str) -> Result<std::process::Command, ShellError> {
let (head, _, _) = trim_enclosing_quotes(&self.name.item);
let head = nu_path::expand_to_real_path(head)
.to_string_lossy()
.to_string();
let mut process = std::process::Command::new(head);
for (arg, arg_keep_raw) in self.args.iter().zip(self.arg_keep_raw.iter()) {
trim_expand_and_apply_arg(&mut process, arg, arg_keep_raw, cwd);
}
Ok(process)
}
/// Spawn a cmd command with `cmd /c args...`
pub fn spawn_cmd_command(&self, cwd: &str) -> std::process::Command {
let mut process = std::process::Command::new("cmd");
// Disable AutoRun
// TODO: There should be a config option to enable/disable this
// Alternatively (even better) a config option to specify all the arguments to pass to cmd
process.arg("/D");
process.arg("/c");
process.arg(&self.name.item);
for (arg, arg_keep_raw) in self.args.iter().zip(self.arg_keep_raw.iter()) {
// https://stackoverflow.com/questions/1200235/how-to-pass-a-quoted-pipe-character-to-cmd-exe
// cmd.exe needs to have a caret to escape a pipe
let arg = Spanned {
item: arg.item.replace('|', "^|"),
span: arg.span,
};
trim_expand_and_apply_arg(&mut process, &arg, arg_keep_raw, cwd)
}
process
}
}
fn trim_expand_and_apply_arg(
process: &mut CommandSys,
arg: &Spanned<String>,
arg_keep_raw: &bool,
cwd: &str,
) {
// if arg is quoted, like "aa", 'aa', `aa`, or:
// if arg is a variable or String interpolation, like: $variable_name, $"($variable_name)"
// `as_a_whole` will be true, so nu won't remove the inner quotes.
let (trimmed_args, mut run_glob_expansion, mut keep_raw) = trim_enclosing_quotes(&arg.item);
if *arg_keep_raw {
keep_raw = true;
// it's a list or a variable, don't run glob expansion either
run_glob_expansion = false;
}
let mut arg = Spanned {
item: if keep_raw {
trimmed_args
} else {
remove_quotes(trimmed_args)
},
span: arg.span,
};
if !keep_raw {
arg.item = nu_path::expand_tilde(arg.item)
.to_string_lossy()
.to_string();
}
let cwd = PathBuf::from(cwd);
if arg.item.contains('*') && run_glob_expansion {
// we need to run glob expansion, so it's NeedExpand.
let path = Spanned {
item: NuGlob::Expand(arg.item.clone()),
span: arg.span,
};
if let Ok((prefix, matches)) = nu_engine::glob_from(&path, &cwd, arg.span, None) {
let matches: Vec<_> = matches.collect();
// FIXME: do we want to special-case this further? We might accidentally expand when they don't
// intend to
if matches.is_empty() {
process.arg(&arg.item);
}
for m in matches {
if let Ok(arg) = m {
let arg = if let Some(prefix) = &prefix {
if let Ok(remainder) = arg.strip_prefix(prefix) {
let new_prefix = if let Some(pfx) = diff_paths(prefix, &cwd) {
pfx
} else {
prefix.to_path_buf()
};
new_prefix.join(remainder).to_string_lossy().to_string()
} else {
arg.to_string_lossy().to_string()
}
} else {
arg.to_string_lossy().to_string()
};
process.arg(&arg);
} else {
process.arg(&arg.item);
}
}
}
} else {
process.arg(&arg.item);
}
}
/// Given an invalid command name, try to suggest an alternative
fn suggest_command(attempted_command: &str, engine_state: &EngineState) -> Option<String> {
let commands = engine_state.get_signatures(false);
let command_folded_case = attempted_command.to_folded_case();
let search_term_match = commands.iter().find(|sig| {
sig.search_terms
.iter()
.any(|term| term.to_folded_case() == command_folded_case)
});
match search_term_match {
Some(sig) => Some(sig.name.clone()),
None => {
let command_names: Vec<String> = commands.iter().map(|sig| sig.name.clone()).collect();
did_you_mean(&command_names, attempted_command)
}
}
}
/// This function returns a tuple with 3 items:
/// 1st item: trimmed string.
/// 2nd item: a boolean value indicate if it's ok to run glob expansion.
/// 3rd item: a boolean value indicate if we need to keep raw string.
fn trim_enclosing_quotes(input: &str) -> (String, bool, bool) {
let mut chars = input.chars();
match (chars.next(), chars.next_back()) {
(Some('"'), Some('"')) => (chars.collect(), false, true),
(Some('\''), Some('\'')) => (chars.collect(), false, true),
// We treat back-quoted strings as bare words, so there's no need to keep them as raw strings
(Some('`'), Some('`')) => (chars.collect(), true, false),
_ => (input.to_string(), true, false),
}
}
fn remove_quotes(input: String) -> String {
let mut chars = input.chars();
match (chars.next_back(), input.contains('=')) {
(Some('"'), true) => chars
.collect::<String>()
.replacen('"', "", 1)
.replace(r#"\""#, "\""),
(Some('\''), true) => chars.collect::<String>().replacen('\'', "", 1),
_ => input,
}
}
struct ByteLines<R: Read>(BufReader<R>);
impl<R: Read> ByteLines<R> {
fn new(read: R) -> Self {
Self(BufReader::new(read))
}
}
impl<R: Read> Iterator for ByteLines<R> {
type Item = Result<Vec<u8>, ShellError>;
fn next(&mut self) -> Option<Self::Item> {
let mut buf = Vec::new();
// `read_until` will never stop reading unless `\n` or EOF is encountered,
// so let's limit the number of bytes using `take` as the Rust docs suggest.
let capacity = self.0.capacity() as u64;
let mut reader = (&mut self.0).take(capacity);
match reader.read_until(b'\n', &mut buf) {
Ok(0) => None,
Ok(_) => Some(Ok(buf)),
Err(e) => Some(Err(e.into())),
}
}
}
// Receiver used for the ListStream
// It implements iterator so it can be used as a ListStream
struct ValueReceiver {
rx: mpsc::Receiver<Value>,
}
impl ValueReceiver {
pub fn new(rx: mpsc::Receiver<Value>) -> Self {
Self { rx }
}
}
impl Iterator for ValueReceiver {
type Item = Value;
fn next(&mut self) -> Option<Self::Item> {
match self.rx.recv() {
Ok(v) => Some(v),
Err(_) => None,
}
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn remove_quotes_argument_with_equal_test() {
let input = r#"--file="my_file.txt""#.into();
let res = remove_quotes(input);
assert_eq!("--file=my_file.txt", res)
}
#[test]
fn argument_without_equal_test() {
let input = r#"--file "my_file.txt""#.into();
let res = remove_quotes(input);
assert_eq!(r#"--file "my_file.txt""#, res)
}
#[test]
fn remove_quotes_argument_with_single_quotes_test() {
let input = r#"--file='my_file.txt'"#.into();
let res = remove_quotes(input);
assert_eq!("--file=my_file.txt", res)
}
#[test]
fn argument_with_inner_quotes_test() {
let input = r#"sh -c 'echo a'"#.into();
let res = remove_quotes(input);
assert_eq!("sh -c 'echo a'", res)
}
}